UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3,942 lines • 158 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { s as raceWithTimeout } from "./src-BPmQBLJp.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage$1 } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { d as withPluginRuntimeRegistryScope, o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { n as waitForAgentDatabaseWriteAdmission } from "./agent-database-preparation-context-CkVoUMTY.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { O as resolveSessionDispatchKind, j as parseAgentSessionKey, l as resolveAgentIdFromSessionKey, y as isAcpSessionKey } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { i as resolveExplicitSessionStorePathForScope, l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { f as resolveAgentWorkspaceDir, r as resolveAgentConfig, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { p as isDiagnosticsEnabled } from "./diagnostic-events-BjAH1Kbx.mjs";
import { s as measureDiagnosticsTimelineSpan } from "./diagnostics-timeline-CSwiG24r.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { s as isFileLogLevelEnabled } from "./logger-1QDNfT7Y.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as applyMergePatch } from "./merge-patch-D-7aajuy.mjs";
import { r as resolveGlobalDedupeCache } from "./dedupe-DxT0h2gR.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { d as getAgentEventLifecycleGeneration, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs";
import { f as normalizeVerboseLevel } from "./thinking.shared-jmDGV33r.mjs";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import { S as readAgentDatabaseAdmissionRefusal } from "./agent-database-admission-CL6wHJ_N.mjs";
import { t as normalizeChatType } from "./chat-type-CL5nBDaO.mjs";
import { t as buildConversationRef } from "./conversation-ref-BiSqlOTe.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { t as captureRequesterOrigin } from "./requester-origin-DG-fk-U0.mjs";
import { t as getChannelPlugin } from "./registry-ByqVE5S3.mjs";
import { a as isInternalMessageChannel } from "./message-channel-DTYVLJT1.mjs";
import { t as resolveGroupSessionKey } from "./group-UpjSVFeV.mjs";
import { n as captureSessionStoreCandidateIdentities } from "./session-store-read-candidates-BjEE1iTg.mjs";
import { n as classifySessionStateActor } from "./session-state-events-ChAYnzQG.mjs";
import { i as resolveSessionWorkStartError } from "./session-work-start-CFJs8WNp.mjs";
import { n as channelRouteDedupeKey } from "./channel-route-E3mkfWI_.mjs";
import { J as waitForReplyOperationSourceRelease, K as waitForReplyBarrierSettlement, X as captureSessionTarget, at as ReplyRunLifecycleAdmissionBlockedError, d as getSessionControllerOperation } from "./session-controller.state-BApgK0mV.mjs";
import { C as markReplyPayloadForSourceSuppressionDelivery, _ as isReplyPayloadStatusNotice, c as getReplyPayloadMetadata, d as isCommandReplyForDelivery, f as isFastModeAutoProgressPayload, k as setReplyPayloadMetadata, o as copyReplyPayloadMetadata, w as readAskUserQuestionId, x as markCommandReplyForDelivery, y as isReplyPayloadTerminalContent } from "./reply-payload-k5WsQWxi.mjs";
import { a as readChannelSourceTurnId, c as setChannelSourceTurnId, r as buildChannelSourceTurnId, u as shouldMintChannelSourceTurnId } from "./session-event-handoff-CC7Ui3SA.mjs";
import { i as getCommandOwnerAuthority } from "./command-owner-authority-BIUd20IP.mjs";
import { r as onSessionIdentityMutation } from "./session-lifecycle-events-DWKmeEvQ.mjs";
import { n as sessionDeliveryChannel } from "./delivery-context.read-BrYAJ7RK.mjs";
import { _ as resolveEffectiveReplyRoute } from "./session-event-target-BPiQeS30.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { r as resolveSqliteSessionKey } from "./session-accessor.sqlite-scope-helpers-5_tKUULP.mjs";
import { v as stripLegacyMediaContextFields } from "./media-facts-B-0Dpo5L.mjs";
import { n as captureSessionStoreReadCandidates } from "./session-store-target-inventory-Cf7beBnr.mjs";
import { i as sanitizeUserFacingText } from "./user-facing-text-Dqp3fcZx.mjs";
import { n as GENERIC_EXTERNAL_RUN_FAILURE_TEXT } from "./user-copy-DFvWpx47.mjs";
import { A as prepareSessionPendingInputDedupeRecovery } from "./session-accessor-CizTbDQj.mjs";
import { a as isSessionWorkStartInvalidatedError, n as SessionWorkStartChangedError } from "./work-start-error-DaHE71YG.mjs";
import { o as buildPersistedUserTurnMessage } from "./session-transcript-rewrite-effects-BVKR4US3.mjs";
import { n as buildChannelUserTurnSender, o as preparePersistedUserTurnMessageForTranscriptWrite } from "./user-turn-transcript.metadata-GFtsH_a_.mjs";
import { _ as sanitizeTranscriptMessage } from "./session-accessor.sqlite-transcript-store-DRtj0wNT.mjs";
import { C as trackSessionControllerSourceWork, W as withSessionControllerSource } from "./session-controller.lifecycle-C_Z3sybN.mjs";
import { s as withPreparedSessionCapabilityRead } from "./subagent-session-store--G7wm9iV.mjs";
import { a as loadSessionEntryReadOnly } from "./session-accessor.sqlite-exact-read-CbvqUmsG.mjs";
import "./lifecycle-BFcckgci.mjs";
import { r as normalizeExplicitSessionKey } from "./session-key-oH67puaB.mjs";
import { c as readChannelContextAdmissionEvidence, l as readChannelContextGatewayContextResolver } from "./admission-evidence-q4_t-NFq.mjs";
import { r as getGatewayLocalUserIngress } from "./local-user-ingress-CLpC74uh.mjs";
import { t as isParentOwnedBackgroundAcpSession } from "./session-interaction-mode-B8LqnFmR.mjs";
import { r as resolveGroupToolPolicy } from "./agent-tools.policy-CM-3Smt9.mjs";
import { i as prepareChannelParticipantObservation } from "./requester-profile-DgtOmQ0f.mjs";
import { i as resolveOriginMessageProvider, r as resolveInboundReplyToolAuthorityOverlay } from "./reply-tool-authority-inbound-BQ8cxNJQ.mjs";
import { _ as releaseSessionControllerClaim, f as claimSessionControllerTask, g as deferSessionControllerClaimBeforeExecution, p as tryClaimSessionControllerTask } from "./session-controller.mailbox-BcK8UF_b.mjs";
import { i as scopePreparedModelRuntimeLease } from "./prepared-model-runtime-generation-scope-Dpvf6WHJ.mjs";
import { n as getGlobalHookRunner, r as getGlobalPluginRegistry } from "./hook-runner-global-DmYyIVDp.mjs";
import { l as getGroupThreadTurn } from "./group-thread-context-DFimpu_J.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { a as createPluginSubagentRequesterContext, l as withClaimingHookAdmission, p as fireAndForgetHook } from "./hooks-BiZpB_10.mjs";
import { n as runAgentHarnessBeforeMessageWriteHook } from "./hook-helpers-DKwpcDXZ.mjs";
import { t as createUserTurnTranscriptRecorder } from "./user-turn-transcript-CQTz-i5Y.mjs";
import { c as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-D6nf-Q3g.mjs";
import "./thinking-Da4gHblr.mjs";
import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs";
import { r as withNativeSubagentRequest } from "./registry-ClBzy_np.mjs";
import { c as shouldCleanTtsDirectiveText, u as normalizeTtsAutoMode } from "./tts-config-CNw5woLC.mjs";
import { o as InboundDedupePendingError } from "./ingress-drain-CMuOTwGV.mjs";
import { a as resolveCommandAuthorizationAsync } from "./command-auth-CC1Z19Eh.mjs";
import { n as resolveAgentIdentity } from "./identity-Cd2mxvzm.mjs";
import { n as resolveSendPolicy } from "./send-policy-Be9xpkMD.mjs";
import { g as RUN_STALE_TAKEOVER_MS } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { n as logMessageDispatchStarted, t as logMessageDispatchCompleted, u as markDiagnosticSessionProgress } from "./diagnostic-C-GjPJGO.mjs";
import { n as resolveDiagnosticModelContentCapturePolicy } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { a as hasOutboundReplyContent } from "./reply-payload-CwASJYas.mjs";
import { a as resolveSendableOutboundReplyParts } from "./reply-payload-parts-0Tn7wkpR.mjs";
import { t as collectTextContentBlocks } from "./content-blocks-DgfxPwgj.mjs";
import { t as createTtsDirectiveTextStreamCleaner } from "./directives-DOxtYHyq.mjs";
import { i as withAcpSessionEntryRead } from "./session-meta-read-BC53uDBL.mjs";
import { a as isExplicitFollowupCommandTurn, l as resolveCommandTurnContext, o as isNativeCommandTurn, u as resolveCommandTurnTargetSessionKey } from "./command-turn-context-BaN4kAo-.mjs";
import { r as isFinalizedInboundContext, t as finalizeInboundContext } from "./inbound-context-0zDtB0Zn.mjs";
import { r as createStructuredOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs";
import { i as prepareConversationRegistryScope } from "./conversation-registry-DTUa0zh7.mjs";
import { n as findConversationTurnDeliveryByReplyTarget, o as markConversationDeliveryReplied, s as markConversationDeliverySent } from "./conversation-delivery-store-CwDySUK3.mjs";
import { n as bindReplyDispatcherConversationContext, o as prepareReplyPayloadForDispatcher, p as suppressPendingFinalDelivery, r as captureReplyDispatchDeliveryOutcome, s as waitForReplyDispatcherIdle, t as attachReplyDispatchUndeliveredFallback } from "./reply-dispatcher-DVZA5pVi.mjs";
import { i as extractShortModelName } from "./normalize-reply-C8AkGgUH.mjs";
import { c as resolveRoutedReplyDeliveryOutcome, l as shouldRetryReplyDispatch, n as ReplyDispatchDeliveryError } from "./reply-dispatch-outcome-C1yqMjJt.mjs";
import { a as toInternalMessageReceivedContext, c as toPluginInboundClaimPair, l as toPluginMessageContext, n as deriveInboundMessageHookContext, u as toPluginMessageReceivedEvent } from "./message-hook-mappers-BCrhfgqk.mjs";
import { n as observeAgentRunStart } from "./agent-run-start-Cf0O0aGQ.mjs";
import { a as isActiveRunSafeCommandTurn, r as findCommandByNativeName } from "./commands-registry-CwAxsNJ9.mjs";
import { n as normalizeCommandBody, r as resolveTextCommand } from "./commands-registry-normalize-dI3NYF5y.mjs";
import { t as shouldHandleTextCommands } from "./commands-text-routing-BYEg7XMZ.mjs";
import { r as waitForReplyDispatcherSettlement, t as registerReplyDispatcherSettledTask } from "./dispatch-dispatcher-DVecxlWg.mjs";
import { y as isPluginOwnedSessionBindingRecord } from "./current-conversation-bindings.kernel-Ap5fhzOe.mjs";
import { i as readConversationBindingRouteFacts } from "./conversation-binding-route-facts-DfCm6YNl.mjs";
import { t as getSessionBindingService } from "./session-binding-service-Bn-zGfS9.mjs";
import { a as resolveConversationBindingContextFromMessage } from "./acp-reset-target-BGHYzzmp.mjs";
import { n as resolveRoutedDeliveryThreadId, t as isSlackDirectRoutedThreadTurn } from "./routed-delivery-thread-C0qY6Hpm.mjs";
import { a as resolveDispatchConversationBinding, n as assertPreparedConversationBindingRouteCurrent, r as readPreparedConversationBindingRouteCurrent, t as assertPreparedConversationBindingRoute } from "./session-conversation-binding-B2fKRrgu.mjs";
import { a as withFullRuntimeReplyConfig, c as bindPreparedReplyDispatchRuntime, d as resolveAuthorizedSessionResetCommand, o as conversationIdentityFromMsgContext, s as stageRemoteInboundMediaIfNeeded, t as resolveRunTypingPolicy, u as normalizeMessageTimestampMs } from "./typing-policy-DLa7P3Cv.mjs";
import { a as resolveReplyOperationRunState, r as recordReplyOperationAgentTurn, t as REPLY_OPERATION_RUN_STATE } from "./reply-operation-run-state--V_f6Ot2.mjs";
import { a as isReplyProfilerEnabled, d as readReplySourceInput, f as readReplySourcePreparationRetry, i as createReplyTimingTracker, m as retireUnadoptedReplySource, t as prepareInternalGetReplyOptions, u as prepareReplySourceInput } from "./get-reply.types-Cne2gAVx.mjs";
import { a as isCaptionedFinalTextPayload, c as DispatchReplyOperationAbortedError, d as runWithDispatchAbortSignal, i as cleanDeferredFinalText, l as createAbortAwareDispatcher, o as mergeDeferredFinalText, r as buildCaptionedFinalTextFallback, s as shouldDeferFinalTtsText, t as finalizeDispatchAndAudit, u as isDispatchReplyOperationAbortedError } from "./dispatch-from-config.finalize-AEMg1XZu.mjs";
import { n as hasTrustedMessageAuditListeners, t as emitTrustedMessageAuditEvent } from "./message-audit-events-Byfl_35A.mjs";
import { r as scopeCommandTranscriptId, t as prepareCommandTranscriptInput } from "./command-transcript-CNcj02a0.mjs";
import { a as isRequiredReplyExpectation, d as resolveReplyCompletion } from "./reply-completion-CrT6uEHT.mjs";
import { a as buildTerminalAgentRunFailureReplyPayload, u as renderPostCompactionModelFailurePayload } from "./agent-runner-failure-reply-NPeAVva_.mjs";
import { _ as setBlockReplyDelivery, a as hasExecApprovalPayload, c as prepareReplyPayloadForSideEffects, d as createBlockReplyContentKey, g as recoverBlockReplySources, i as hasAskUserPayload, l as requiresDurableToolResultDelivery, o as hasExecApprovalUnavailablePayload, p as createBlockReplySource, s as maybeApplyTtsToReplyPayload, u as shouldDeliverDespiteSourceReplySuppression } from "./dispatch-from-config.payloads-BWvEWyjL.mjs";
import { n as resolveCommandContextText } from "./context-text-D9JfaJrk.mjs";
import { n as resolveReplyTurnKind } from "./reply-turn-kind-BDXTUey9.mjs";
import { t as withRequesterNativeSubagents } from "./request-native-subagent-UFrOHyCI.mjs";
import { n as sendReplyWithTranscriptMirror, r as transcriptMirrorForDeliveredPayload, t as mirrorDeliveredReplyToTranscript } from "./dispatch-from-config.transcript-xbIjHFEW.mjs";
import { n as createSessionWriterDeliveryPreparation, r as isDispatchFinalReplySessionWriterAuthorized } from "./session-writer-delivery-authority-DNB-b5xs.mjs";
import { i as isAskUserPromptPending } from "./ask-user-tool-C-rRerhD.mjs";
import { t as settleProgressVisibilityCallbackResult } from "./progress-visibility-BGbXGOwY.mjs";
import { l as formatPlanChecklistLines, p as normalizeAgentPlanSteps } from "./streaming-DsQF8isK.mjs";
import { o as takeCommandSessionMetadataChanges } from "./commands-goal-BISKgDmP.mjs";
import { t as createDiagnosticMessageLifecycle } from "./message-lifecycle-DXuyekCU.mjs";
import { t as hasInboundAudio } from "./inbound-media-BJ8l1Cri.mjs";
import "./session-controller-Bu0l-8-p.mjs";
import { n as prepareTtsPreferences } from "./tts-preferences-CIrFrUQO.mjs";
import { a as resolveVisibleRepliesPolicy, i as createShouldEmitVerboseProgress, r as resolveStableMessageToolAvailability, t as resolveReplyMessageToolAvailability } from "./session-stable-reply-mode-Bboydwa7.mjs";
import { t as isRecoverableTerminalSessionStatus } from "./terminal-status-4Rh8bAKD.mjs";
import { i as buildPluginBindingErrorText, l as hasShownPluginBindingFallbackNotice, m as toPluginConversationBinding, o as buildPluginBindingUnavailableText, r as buildPluginBindingDeclinedText, u as markPluginBindingFallbackNoticeShown } from "./conversation-binding-rxVGCYy7.mjs";
import { a as resolveSourceReplyExpectation, n as isUnauthorizedTextSlashCommand, o as resolveSourceReplyVisibilityPolicy, s as isExplicitCommandTurnContext } from "./source-reply-delivery-mode-mRdJZOCZ.mjs";
import { t as restoreArchivedSession } from "./session-archive-restore-DKQW28x6.mjs";
import { t as isExplicitSteerCommandTurn } from "./explicit-steer-routing-BYQXATds.mjs";
import { a as isReplyOperationStalledBeforeOutput, d as runWithReplyOperationLifecycleAdmission, f as createReplyTurnAdmissionWaiter, l as admitReplyTurn, n as beginReplyOperationFinalizationWork, o as resolveStalledTurnNoticeText, t as resolveTurnCommentaryProgressOwner } from "./commentary-progress-owner-Cm2I90nD.mjs";
import { a as loadReplyMediaPathsRuntime, i as loadPreparedModelRuntime, n as loadFastApproveRuntime, o as loadRouteReplyRuntime, r as loadGetReplyFromConfigRuntime, s as loadRuntimePlugins, t as loadAbortRuntime } from "./dispatch-from-config.runtime.js";
import { t as noteDispatchProcessedOutcome } from "./dispatch-processed-outcome-BVnjMfpJ.mjs";
import { t as appendPreparedTranscriptEvent } from "./session-transcript-event-f6QomfAt.mjs";
import { n as claimPendingConversationTurnReply } from "./conversation-turns-m-vBoIaV.mjs";
import { a as resolveReplyDeliveryAccountId, o as resolveReplyToMode, t as createReplyDeliveryContext } from "./reply-threading-__RxrMKC.mjs";
import { t as getGatewayNativeApprovalRuntime } from "./approval-gateway-runtime-context-B9yxaZi6.mjs";
import { r as hasActiveNativeApprovalRoute } from "./approval-native-route-coordinator-Dm94seHh.mjs";
import { t as PLUGIN_COMMAND_DISPATCH } from "./plugin-command-dispatch-contract-4LAPWU0e.mjs";
import { i as matchPluginCommandInvocation, t as createPluginCommandRuntime } from "./plugin-command-runtime-7c8RYPHl.mjs";
import { r as resolveCommandChannel } from "./commands-context-1C0vIajQ.mjs";
import crypto, { randomUUID } from "node:crypto";
//#region src/auto-reply/reply/dispatch-session-refresh-error.ts
/** Pre-dispatch session state changed before any user-visible work began. */
var DispatchSessionRefreshRequiredError = class extends Error {
	constructor(e) {
		super(e.message, { cause: e });
		this.name = "DispatchSessionRefreshRequiredError";
	}
};
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.context.ts
function shouldLetSlackRoutedThreadBypassBusyReplyOperation(e) {
	return isSlackDirectRoutedThreadTurn(e.ctx) && e.activeOperation?.routeThreadId !== void 0 && e.routeThreadId !== void 0 && String(e.activeOperation.routeThreadId) !== String(e.routeThreadId);
}
async function resolveSessionStoreLookup(e, t, n) {
	n?.();
	const r = resolveCommandTurnTargetSessionKey(e);
	const i = normalizeOptionalString(r ?? e.SessionKey);
	if (!i) return {};
	const a = resolveSessionAgentId({
		sessionKey: i,
		config: t,
		fallbackAgentId: e.AgentId
	});
	const o = {
		agentId: a,
		sessionKey: i,
		storePath: resolveExplicitSessionStorePathForScope({
			agentId: a,
			sessionKey: i
		}) ?? resolveSessionStorePathCore(t.session?.store, { agentId: a })
	};
	try {
		const e = isIncognitoSessionKey(i) ? loadSessionEntryReadOnly({
			...o,
			readConsistency: "latest",
			clone: false
		}) : await readSessionEntryReadOnlyInWorker({
			...o,
			readConsistency: "latest",
			clone: false
		}, n);
		n?.();
		return {
			...o,
			entry: e,
			store: e ? { [i]: e } : void 0
		};
	} catch {
		n?.();
		return o;
	}
}
/** Legacy free-harness keys retain storage identity but use the inspected channel owner. */
function resolveBoundAcpDispatchRuntimeOwner(e) {
	const t = resolveSessionAgentId({
		sessionKey: e.sessionKey,
		config: e.cfg,
		fallbackAgentId: e.ctx.AgentId
	});
	const n = listAgentIds(e.cfg);
	const r = parseAgentSessionKey(e.sessionKey)?.rest.toLowerCase();
	const i = readConversationBindingRouteFacts(e.ctx);
	return !n.includes(t) && r?.startsWith("acp:") && !r.startsWith("acp:binding:") && i?.kind === "agent" && i.targetSessionKey.trim() === e.sessionKey?.trim() && n.includes(i.fallbackAgentId) ? i.fallbackAgentId : t;
}
async function resolveBoundAcpDispatchSessionKey(e) {
	if (resolveCommandTurnTargetSessionKey(e.ctx)) return;
	const t = readConversationBindingRouteFacts(e.ctx);
	const n = t?.conversation ?? resolveConversationBindingContextFromMessage({
		cfg: e.cfg,
		ctx: e.ctx
	});
	if (!n) return;
	const readCurrentBinding = () => t ? readPreparedConversationBindingRouteCurrent(e.ctx) : getSessionBindingService().resolveByConversationAsync(n);
	const r = await readCurrentBinding();
	assertPreparedConversationBindingRoute(e.ctx, r);
	const i = normalizeOptionalString(r?.targetSessionKey);
	if (!r || !i || !isAcpSessionKey(i)) return;
	if (isPluginOwnedSessionBindingRecord(r)) return;
	const { bindingId: a, boundAt: o, targetSessionKey: s, targetKind: c } = r;
	const l = { ...r.conversation };
	await getSessionBindingService().touchAsync(a, void 0, l);
	const u = await readCurrentBinding();
	assertPreparedConversationBindingRoute(e.ctx, u);
	if (u && (u.bindingId !== a || u.boundAt !== o || u.targetSessionKey !== s || u.targetKind !== c || u.conversation.channel !== l.channel || u.conversation.accountId !== l.accountId)) throw new DispatchSessionRefreshRequiredError(/* @__PURE__ */ new Error("conversation binding changed while recording activity"));
	const d = normalizeOptionalString(u?.targetSessionKey);
	return u && d && isAcpSessionKey(d) && !isPluginOwnedSessionBindingRecord(u) ? t ? normalizeOptionalString(e.ctx.SessionKey) : d : void 0;
}
async function resolveDispatchResetAdmission(e) {
	const { ctx: t, entry: n } = e;
	const r = resolveCommandTurnTargetSessionKey(t);
	const i = isNativeCommandTurn(t.CommandTurn) ? r : void 0;
	const a = classifySessionStateActor({ inputProvenance: t.InputProvenance }).actorType;
	let o = false;
	if (!e.hasPluginOwnedBinding && n?.pluginOwnerId === void 0 && t.InboundAccessAuthorized === true && t.InboundEventKind !== "room_event" && (i === void 0 || i === e.sessionKey) && a === "human") {
		const n = normalizeChatType(t.ChatType);
		const r = n != null && n !== "direct" || Boolean(resolveGroupSessionKey(t));
		const { resetCommand: i } = await resolveAuthorizedSessionResetCommand({
			agentId: e.agentId,
			cfg: e.cfg,
			commandAuthorized: t.CommandAuthorized,
			ctx: t,
			isGroup: r
		});
		o = i.matchedResetTriggerLower !== void 0;
	}
	return { resetTriggered: o };
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.audit.ts
const completedInboundAuditReasons = /* @__PURE__ */ new Map([
	["fast_abort", "fast_abort"],
	["plugin-bound-handled", "plugin_bound_handled"],
	["plugin-bound-fallback-missing-plugin", "plugin_bound_unavailable"],
	["plugin-bound-fallback-no-handler", "plugin_bound_unavailable"],
	["plugin-bound-declined", "plugin_bound_declined"],
	["before_dispatch_handled", "before_dispatch_handled"],
	["acp_dispatch", "acp_dispatch_completed"],
	["acp_empty_prompt", "acp_dispatch_empty"],
	["active_run_injected", "active_run_injected"]
]);
const skippedInboundAuditReasons = /* @__PURE__ */ new Map([["duplicate", "duplicate"], ["reply-operation-active", "reply_operation_active"]]);
function resolveInboundMessageAuditTerminal(e, t) {
	if (t === "plugin-bound-error" || t?.startsWith("acp_error:")) return {
		status: "failed",
		outcome: "failed",
		errorCode: "message_processing_failed",
		reasonCode: t === "plugin-bound-error" ? "plugin_bound_error" : "acp_dispatch_failed"
	};
	if (t === "reply_operation_aborted" || t === "acp_aborted") return {
		status: "blocked",
		outcome: "skipped",
		reasonCode: t === "reply_operation_aborted" ? "reply_operation_aborted" : "acp_dispatch_aborted"
	};
	if (e === "completed") {
		const e = completedInboundAuditReasons.get(t);
		return {
			status: "succeeded",
			outcome: "completed",
			...e ? { reasonCode: e } : {}
		};
	}
	if (e === "skipped") {
		const e = skippedInboundAuditReasons.get(t);
		return {
			status: "blocked",
			outcome: "skipped",
			...e ? { reasonCode: e } : {}
		};
	}
	return {
		status: "failed",
		outcome: "failed",
		errorCode: "message_processing_failed"
	};
}
function emitInboundMessageAuditTerminal(e) {
	const { ctx: t, cfg: n } = e;
	const r = Date.now();
	const i = normalizeOptionalString(t.SessionKey) ?? normalizeOptionalString(t.CommandTargetSessionKey);
	const a = normalizeOptionalString(t.SenderId);
	const o = normalizeOptionalString(t.AccountId);
	const s = normalizeOptionalString(t.NativeChannelId) ?? normalizeOptionalString(t.OriginatingTo) ?? normalizeOptionalString(t.To) ?? normalizeOptionalString(t.From);
	const c = normalizeOptionalString(t.MessageSidFull) ?? normalizeOptionalString(t.MessageSid) ?? normalizeOptionalString(t.MessageSidFirst) ?? normalizeOptionalString(t.MessageSidLast);
	const l = resolveInboundMessageAuditTerminal(e.terminal.outcome, e.terminal.options?.reason);
	let u = normalizeOptionalString(t.AgentId);
	try {
		u = resolveSessionAgentId({
			sessionKey: i,
			config: n,
			agentId: t.AgentId
		});
	} catch {}
	try {
		emitTrustedMessageAuditEvent({
			occurredAt: r,
			kind: "message",
			action: "message.inbound.processed",
			...l,
			actorType: a ? "channel_sender" : "system",
			actorId: a ?? "gateway",
			...u ? { agentId: u } : {},
			...normalizeOptionalString(e.observedRunId) ? { runId: normalizeOptionalString(e.observedRunId) } : {},
			direction: "inbound",
			channel: normalizeLowercaseStringOrEmpty(t.OriginatingChannel) || normalizeLowercaseStringOrEmpty(t.Surface) || normalizeLowercaseStringOrEmpty(t.Provider) || "unknown",
			conversationKind: normalizeChatType(t.ChatType) ?? "unknown",
			durationMs: Math.max(0, r - e.startedAt),
			resultCount: e.counts.tool + e.counts.block + e.counts.final,
			...o ? { accountId: o } : {},
			...s ? { conversationId: s } : {},
			...c ? { messageId: c } : {}
		});
	} catch {}
}
/**
* Captures one terminal event for the reply-processing boundary. Channel admission and
* pre-dispatch drops remain outside this boundary and need their own ingress projection.
*/
function createInboundMessageAuditTerminal(e) {
	if (!hasTrustedMessageAuditListeners()) return;
	const t = Date.now();
	let n;
	let r = normalizeOptionalString(e.replyOptions?.runId);
	let i = false;
	const emitTerminal = (n, a) => {
		if (i) return;
		i = true;
		emitInboundMessageAuditTerminal({
			cfg: e.cfg,
			counts: a,
			ctx: e.ctx,
			observedRunId: r,
			startedAt: t,
			terminal: n
		});
	};
	return {
		note(e, t) {
			n = {
				outcome: e,
				...t ? { options: t } : {}
			};
		},
		observeRunId(e) {
			r = normalizeOptionalString(e) ?? r;
		},
		finishSuccess(e) {
			emitTerminal(n ?? { outcome: "completed" }, e.counts);
		},
		finishError() {
			let t = {
				tool: 0,
				block: 0,
				final: 0
			};
			try {
				t = e.dispatcher.getQueuedCounts();
			} catch {}
			emitTerminal({ outcome: "error" }, t);
		}
	};
}
//#endregion
//#region src/auto-reply/reply/channel-command-user-turn.ts
const channelTurns = /* @__PURE__ */ new WeakMap();
/**
* Gateway chat ingress supplies its own run and recorder. Channel ingress has neither,
* so the host mints them here, but only for the operator authority that host ingress
* bound to this verified channel principal. Nothing persists until the gate commits it.
*/
async function prepareChannelCommandUserTurn(e) {
	const { ctx: t, replyOptions: n, binding: r } = e;
	const i = n?.operatorAuthority;
	const a = getCommandOwnerAuthority(t);
	if (n?.runId !== void 0 || n?.userTurnTranscriptRecorder !== void 0 || getGatewayLocalUserIngress(t) !== void 0 || isInternalMessageChannel(t.Provider ?? t.Surface) || !i || !a || a.operatorAuthority !== i || !r.entry.sessionId || !r.storePath || !r.commandBody) return;
	const o = channelTurns.get(e.dispatch);
	if (o) return o;
	const s = await prepareCommandTranscriptInput(r.commandBody);
	if (!s) return;
	const c = channelTurns.get(e.dispatch);
	if (c) return c;
	const l = a.isCurrent();
	const u = normalizeMessageTimestampMs(t.Timestamp);
	const d = readChannelSourceTurnId(t);
	const f = t.ChatType === "group" || t.ChatType === "channel" || t.InboundAccessAuthorized === true && t.SenderIsSelf !== true;
	const p = Object.freeze({
		runId: randomUUID(),
		userTurnTranscriptRecorder: createUserTurnTranscriptRecorder({
			input: {
				text: s,
				senderIsOwner: l,
				requesterOrigin: captureRequesterOrigin({
					...resolveInboundReplyToolAuthorityOverlay({
						ctx: t,
						sessionEntry: r.entry,
						senderIsOwner: l,
						operatorAuthority: i,
						disableTools: false
					}),
					sessionKey: r.sessionKey,
					operatorProfileId: i.profileId
				}),
				...d ? { idempotencyKey: d } : {},
				...t.InputProvenance ? { provenance: t.InputProvenance } : {},
				...u ? { timestamp: u } : {},
				...f ? { sender: buildChannelUserTurnSender(t) } : {}
			},
			target: {
				agentId: r.agentId,
				sessionKey: r.sessionKey,
				sessionId: r.entry.sessionId,
				sessionEntry: r.entry,
				storePath: r.storePath,
				config: e.cfg
			},
			errorContext: "plugin command user turn transcript",
			beforeMessageWrite: runAgentHarnessBeforeMessageWriteHook
		})
	});
	channelTurns.set(e.dispatch, p);
	return p;
}
/** Delivered-command mirror fields: a committed native command turn already holds the input. */
function commandTranscriptMirror(e, t, n) {
	return channelTurns.get(e)?.userTurnTranscriptRecorder.getAdmissionReceipt() ? {
		commandText: t,
		commandId: n,
		commandInputCommitted: true
	} : {
		commandText: t,
		commandId: n
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.commentary.ts
/** Coalesce repeated item snapshots and flush commentary ahead of the final reply. */
function createDispatchCommentaryProgress(e) {
	let t = null;
	const n = /* @__PURE__ */ new Set();
	const deliverCommentaryProgressMessage = async (t) => {
		if (!await e.shouldSendToolSummaries() || await e.shouldSuppressDelivery()) return;
		if (e.isAborted() || e.isFinalDeliveryStarted()) return;
		e.assertCurrent();
		await e.send({ text: `💬 ${t}` });
	};
	const flushPendingCommentaryProgress = async () => {
		const e = t;
		t = null;
		const r = e?.text.trim();
		if (!r) return;
		if (e?.itemId) n.add(e.itemId);
		await deliverCommentaryProgressMessage(r);
	};
	const noteCommentaryProgress = async (r) => {
		const i = r.itemId?.trim() || void 0;
		if (e.isFinalDeliveryStarted() || i && n.has(i)) return;
		const a = r.progressText ?? "";
		const o = t !== null && (t.itemId !== void 0 && t.itemId === i || t.text.trim() === a.trim());
		if (!a.trim()) {
			if (o) t = null;
			return;
		}
		if (t && !o) await flushPendingCommentaryProgress();
		t = {
			itemId: i,
			text: a
		};
	};
	return {
		flushPendingCommentaryProgress,
		noteCommentaryProgress
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.dispatch-admission.ts
/** Acquires the dispatch-phase reply operation, or returns the refused dispatch result. */
async function acquireDispatchTurn(e) {
	const t = e.activeRunSafeCommandTurn ? "command_resolution" : "dispatch";
	const n = await e.traceReplyPhase(`reply.admit_${t}`, () => e.ensureDispatchReplyOperation(t));
	if (n.status === "aborted") return {
		status: "complete",
		result: e.finishReplyOperationAbortedDispatch()
	};
	if (n.status === "busy") return {
		status: "complete",
		result: e.finishReplyOperationBusyDispatch({ dedupeDisposition: "release" })
	};
}
/**
* The ACP takeover runs its turn, so it is admitted before the takeover. Admission leaves a
* busy session's source unclaimed for queue policy, which ACP does not apply; the source
* waits for its own mailbox claim instead, so its turn never queues behind it.
*/
async function acquireAcpDispatchTurn(e) {
	const t = await acquireDispatchTurn(e);
	const n = e.params.replyOptions;
	const r = readReplySourceInput(n);
	if (t || e.activeRunSafeCommandTurn || isNativeCommandTurn(resolveCommandTurnContext(e.ctx)) || e.getDispatchReplyOperation() || r?.phase !== "preparing") return t;
	try {
		await claimSessionControllerTask(r, () => {}, resolveReplyTurnKind(n));
	} catch {
		return {
			status: "complete",
			result: e.finishReplyOperationAbortedDispatch()
		};
	}
	const i = await acquireDispatchTurn(e);
	if (!e.getDispatchReplyOperation() && r.claim) releaseSessionControllerClaim(r.claim);
	return i;
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.events.ts
function admittedSessionSettingsRestrictRuntime(e) {
	return e?.permissionMode !== void 0 && e.permissionMode !== "full" || e?.toolOverrides !== void 0 && Object.keys(e.toolOverrides).length > 0;
}
function createReplyDispatchEvent(e) {
	const { shouldSendToolSummaries: t, shouldSendFullToolDetails: n, ...r } = e;
	return Object.defineProperties(r, {
		shouldSendToolSummaries: {
			enumerable: true,
			get() {
				warnPluginSdkDeprecation({
					family: "reply-visibility",
					method: "reply_dispatch.shouldSendToolSummaries",
					replacement: "await shouldSendToolSummariesAsync()"
				});
				return t();
			}
		},
		shouldSendFullToolDetails: {
			enumerable: true,
			get() {
				warnPluginSdkDeprecation({
					family: "reply-visibility",
					method: "reply_dispatch.shouldSendFullToolDetails",
					replacement: "await shouldSendFullToolDetailsAsync()"
				});
				return n;
			}
		}
	});
}
//#endregion
//#region src/auto-reply/reply/dispatch-native-subagent.ts
function requesterState(e, t) {
	const n = e.params.replyOptions;
	const r = e.sessionStoreEntry.entry;
	const i = e.sessionStoreEntry.sessionKey ?? e.sessionKey;
	return {
		cfg: e.cfg,
		sessionAgentId: e.sessionAgentId,
		sessionKey: i,
		entry: r,
		runId: t?.runId ?? n?.runId,
		operatorAuthority: n?.operatorAuthority,
		authorizeRequester: () => resolveCommandAuthorizationAsync({
			ctx: e.ctx,
			cfg: e.cfg,
			commandAuthorized: e.ctx.CommandAuthorized
		}),
		resolveToolAuthority: (t) => resolveInboundReplyToolAuthorityOverlay({
			ctx: e.ctx,
			sessionEntry: r,
			senderIsOwner: t.senderIsOwner,
			operatorAuthority: n?.operatorAuthority,
			toolsAllow: n?.toolsAllow,
			disableTools: n?.disableTools === true
		}),
		messageChannel: e.ctx.OriginatingChannel ?? e.ctx.Provider ?? e.ctx.Surface,
		messageTo: e.ctx.OriginatingTo ?? e.ctx.To,
		getAbortSignal: () => {
			const t = [e.getPreDispatchAbortSignal(), n?.abortSignal].filter((e) => e !== void 0);
			return t.length ? AbortSignal.any(t) : void 0;
		},
		assertCurrent: () => {
			e.assertProgressCurrent();
			e.turnAdoption?.assertCurrent();
		},
		commitTurn: async (a) => {
			await e.assertCurrentBindingRoute();
			a();
			await e.turnAdoption?.adopt();
			a();
			const o = t?.userTurnTranscriptRecorder ?? n?.userTurnTranscriptRecorder;
			if (!r?.sessionId || !o || !await o.resolveMessage()) return false;
			a();
			await o.persistApproved({
				expectedSessionId: r.sessionId,
				beforeFreshMessageCommit: a
			});
			a();
			const s = o.getAdmissionReceipt();
			return Boolean(s && s.sessionId === r.sessionId && s.sessionKey === i && s.agentId === e.sessionAgentId);
		},
		ingress: {
			ingressKind: "channel",
			boundary: "auto-reply.reply-dispatch",
			evidence: readChannelContextAdmissionEvidence(e.ctx),
			gatewayLocalUserIngress: getGatewayLocalUserIngress(e.ctx)
		}
	};
}
/** Legacy hook and command invocations share the same requester/admission producer. */
async function runWithReplyNativeSubagents(e, t) {
	return await withRequesterNativeSubagents(requesterState(e), (e) => withNativeSubagentRequest(async (t) => {
		const n = await e(t);
		if (!n) throw new Error("Native subagents are unavailable for this requester.");
		return n;
	}, t));
}
const runWithCommandNativeSubagents = async (e, t, n) => {
	const r = e.ctx.InputProvenance;
	const i = e.params.replyOptions;
	if (r && r.kind !== "external_user" || !i?.operatorAuthority || t.agentId !== e.sessionAgentId || t.sessionKey !== e.sessionKey) return await n(void 0);
	const a = i.runId && i.userTurnTranscriptRecorder ? {
		runId: i.runId,
		userTurnTranscriptRecorder: i.userTurnTranscriptRecorder
	} : await prepareChannelCommandUserTurn({
		dispatch: e,
		cfg: e.cfg,
		ctx: e.ctx,
		replyOptions: i,
		binding: t
	});
	if (!a) return await n(void 0);
	const o = requesterState({
		...e,
		sessionAgentId: t.agentId,
		sessionKey: t.sessionKey,
		sessionStoreEntry: {
			sessionKey: t.sessionKey,
			entry: t.entry
		}
	}, a);
	return await withRequesterNativeSubagents({
		...o,
		sessionAgentId: t.agentId,
		sessionKey: t.sessionKey,
		entry: t.entry,
		getAbortSignal: () => {
			const t = [e.getDispatchAbortSignal(), e.params.replyOptions?.abortSignal].filter((e) => e !== void 0);
			return t.length ? AbortSignal.any(t) : void 0;
		},
		ingress: {
			...o.ingress,
			boundary: "auto-reply.plugin-command"
		},
		commandIngressEligible: true,
		enableScheduledTurns: true
	}, n);
};
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.reply-dispatch-hook.ts
function runReplyDispatchHook(e, t) {
	const { hookRunner: n, params: r } = e;
	if (!e.allowInboundHandlers || admittedSessionSettingsRestrictRuntime(r.replyOptions?.admittedSessionSettings) || !n?.hasHooks("reply_dispatch", { dispatchKind: e.dispatchKind })) return;
	const run = () => e.runWithDispatchLifecycleAdmission(async () => {
		return await runWithDispatchAbortSignal(t.isTailDispatch ? e.getDispatchAbortSignal() : e.getPreDispatchAbortSignal(), async () => {
			const i = await e.shouldEmitFullVerboseProgressAsync();
			e.assertProgressCurrent();
			return n.runReplyDispatch(createReplyDispatchEvent({
				ctx: e.ctx,
				runId: r.replyOptions?.runId,
				sessionKey: e.acpDispatchSessionKey,
				toolsAllow: r.replyOptions?.toolsAllow,
				images: r.replyOptions?.images,
				inboundAudio: e.inboundAudio,
				sessionTtsAuto: e.sessionTtsAuto,
				ttsChannel: e.deliveryChannel,
				suppressUserDelivery: e.suppressHookUserDelivery,
				suppressReplyLifecycle: e.suppressHookReplyLifecycle,
				sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
				shouldRouteToOriginating: e.shouldRouteToOriginating,
				originatingChannel: e.routeReplyChannel,
				originatingTo: e.routeReplyTo,
				originatingAccountId: e.replyContextAccountId,
				originatingThreadId: e.routeReplyThreadId,
				originatingChatType: e.replyRoute.chatType,
				shouldSendToolSummaries: t.shouldSendToolSummaries,
				shouldSendToolSummariesAsync: t.shouldSendToolSummariesAsync,
				shouldSendFullToolDetails: i,
				shouldSendFullToolDetailsAsync: e.shouldEmitFullVerboseProgressAsync,
				sendPolicy: e.sendPolicy,
				...t.isTailDispatch ? { isTailDispatch: true } : {}
			}), withClaimingHookAdmission({
				cfg: e.cfg,
				dispatchKind: e.dispatchKind,
				dispatcher: e.dispatchHookDispatcher,
				abortSignal: e.getPreDispatchAbortSignal() ?? r.replyOptions?.abortSignal,
				onReplyStart: r.replyOptions?.onReplyStart,
				onAgentRunStart: r.replyOptions?.onAgentRunStart,
				onPreparedAgentRunStart: r.replyOptions?.onPreparedAgentRunStart,
				turnAdoption: e.turnAdoption,
				userTurnTranscriptRecorder: r.replyOptions?.userTurnTranscriptRecorder,
				prepareAssistantTranscriptMessage: r.replyOptions?.prepareAssistantTranscriptMessage,
				recordProcessed: e.recordProcessed,
				markIdle: e.markIdle
			}, {
				...!t.isTailDispatch ? { prepare: e.assertCurrentBindingRoute } : {},
				assertCurrent: e.turnAdoption?.assertCurrent
			}), (t) => runWithReplyNativeSubagents(e, t));
		}, e.trackDispatchLifecycleWork);
	});
	return t.isTailDispatch ? run() : e.traceReplyPhase("reply.reply_dispatch_hooks", run);
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.session-metadata.ts
function createSessionMetadataChangeNotifier(e) {
	const t = /* @__PURE__ */ new Set();
	const n = {};
	const notifySessionMetadataChanges = (r) => {
		if (!r?.length) return;
		const i = r.filter((e) => {
			const n = JSON.stringify([
				e.sessionKey,
				e.agentId ?? null,
				e.reason
			]);
			if (t.has(n)) return false;
			t.add(n);
			return true;
		});
		if (i.length === 0) return;
		n.sessionMetadataChangesForResult = [...n.sessionMetadataChangesForResult ?? [], ...i];
		e?.(i);
	};
	return {
		notifySessionMetadataChanges,
		routeState: n
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.choose-route.ts
async function chooseDispatchRoute(e) {
	const { acpDispatchSessionKey: t, attachSourceReplyDeliveryMode: n, cfg: r, commitInboundDedupeIfClaimed: i, completeDispatchReplyOperation: a, ctx: o, deliveryChannel: s, dispatcher: c, getPreDispatchAbortSignal: l, hookRunner: u, isRoutedReplyDelivered: d, markIdle: f, markInboundDedupeReplayUnsafe: p, params: m, recordProcessed: h, replyContextAccountId: g, replyRoute: _, resolvePreparedTranscriptBinding: v, routeReplyChannel: y, routeReplyThreadId: b, routeReplyTo: x, runWithDispatchLifecycleAdmission: S, sendPayloadAsync: C, sessionAgentId: w, sessionKey: T, sessionStoreEntry: E, sessionTtsAuto: D, shouldEmitVerboseProgressAsync: O, shouldRouteToOriginating: k, traceReplyPhase: A, trackDispatchLifecycleWork: j, turnLedger: M } = e;
	const shouldSuppressProgressDelivery = async () => e.sendPolicyDenied || e.suppressDelivery && !await shouldDeliverVerboseProgressDespiteSourceSuppression();
	const shouldSendToolSummaries = () => m.replyOptions?.suppressToolProgressMessages !== true && e.shouldEmitVerboseProgress();
	const shouldSendToolSummariesAsync = async () => m.replyOptions?.suppressToolProgressMessages !== true && await O();
	const { notifySessionMetadataChanges: N, routeState: P } = createSessionMetadataChangeNotifier(m.onSessionMetadataChanges);
	const allowsVerboseProgressDespiteSourceSuppression = () => e.suppressAutomaticSourceDelivery && e.sourceReplyDeliveryMode === "message_tool_only" && o.InboundEventKind !== "room_event" && !e.sendPolicyDenied;
	const shouldDeliverVerboseProgressDespiteSourceSuppression = async () => allowsVerboseProgressDespiteSourceSuppression() && await shouldSendToolSummariesAsync();
	const shouldSuppressProgressDeliverySync = () => e.sendPolicyDenied || e.suppressDelivery && !(allowsVerboseProgressDespiteSourceSuppression() && shouldSendToolSummaries());
	const shouldDeliverForcedToolProgressDespiteSourceSuppression = () => allowsVerboseProgressDespiteSourceSuppression() && m.replyOptions?.forceToolResultProgress === true;
	let F = false;
	const I = createSessionWriterDeliveryPreparation({
		storePath: E.storePath,
		retain: (e) => registerReplyDispatcherSettledTask(c, e)
	});
	const isSessionWriterDeliveryAuthorized = (e) => isDispatchFinalReplySessionWriterAuthorized(e, T);
	const shouldSuppressLateTextOnlyToolProgress = (e) => F && !requiresDurableToolResultDelivery(e);
	const { flushPendingCommentaryProgress: L, noteCommentaryProgress: R } = createDispatchCommentaryProgress({
		shouldSendToolSummaries: shouldSendToolSummariesAsync,
		shouldSuppressDelivery: shouldSuppressProgressDelivery,
		isAborted: () => e.isDispatchOperationAborted(),
		isFinalDeliveryStarted: () => F,
		assertCurrent: () => e.assertProgressCurrent(),
		send: k ? C : (e) => {
			p();
			M.sendQueued("tool", e);
		}
	});
	const shouldSuppressMessageToolOnlyTextErrorProgress = async (t) => {
		if (e.sourceReplyDeliveryMode !== "message_tool_only" || await e.shouldEmitFullVerboseProgressAsync() || t.isError !== true) return false;
		return !resolveSendableOutboundReplyParts(t).hasMedia && !hasExecApprovalPayload(t);
	};
	const z = {
		cfg: r,
		preparedTtsPreferences: e.preparedTtsPreferences,
		ttsAuto: D,
		agentId: w,
		channelId: s,
		accountId: _.accountId,
		inboundAudio: e.inboundAudio
	};
	const B = shouldDeferFinalTtsText(z);
	let V = 0;
	const commandBlockMirror = (n) => {
		const r = getReplyPayloadMetadata(n);
		const i = normalizeOptionalString(resolveCommandContextText(o));
		const a = scopeCommandTranscriptId(normalizeOptionalString(e.messageIdForHook), e.hookState.inboundClaimContext);
		if (o.CommandInterpretationSuppressed || !i?.startsWith("/") || !a || Boolean(r?.inlineCommandReply || r?.assistantTranscriptOwned) || r?.assistantMessageIndex !== void 0) return;
		const s = t ?? E.sessionKey ?? T;
		if (!s) return;
		const c = v(s);
		return transcriptMirrorForDeliveredPayload({
			sessionKey: s,
			agentId: w,
			expectedSessionId: c?.sessionId,
			storePath: c?.storePath ?? E.storePath,
			...commandTranscriptMirror(e, i, a),
			preferText: true,
			idempotencyKey: `command-block:${a}:${++V}`,
			deliveryMirror: {
				kind: "channel-final",
				sourceMessageId: a
			}
		}, n);
	};
	const H = shouldCleanTtsDirectiveText(z);
	const U = /* @__PURE__ */ new Map();
	const recordBlockOutcome = (e, t) => {
		setBlockReplyDelivery(t, e);
		if (getReplyPayloadMetadata(e)?.independentDeliveryIntentId !== void 0) return;
		const n = createBlockReplyContentKey(e);
		const r = U.get(n) ?? [];
		r.push(t);
		U.set(n, r);
	};
	const sendTrackedBlockReply = (e) => {
		const t = e.kind === "prepared" ? e.plan.payload : e.payload;
		const n = sendReplyWithTranscriptMirror({
			dispatcher: c,
			cfg: r,
			metadata: commandBlockMirror(t),
			payload: t,
			kind: "block",
			send: () => e.kind === "prepared" ? M.sendPreparedQueued("block", e.plan) : M.sendQueued("block", t)
		});
		recordBlockOutcome(t, n.queued ? n.outcome?.then((e) => ({
			outcome: e,
			pending: n.hasPendingDelivery?.()
		})) ?? Promise.resolve({ outcome: "failed-deliver" }) : Promise.resolve({ outcome: "cancelled" }));
		return n;
	};
	const recordRoutedBlockReplyDelivery = (e, t) => {
		if (!t) {
			recordBlockOutcome(e, Promise.resolve({ outcome: "cancelled" }));
			return;
		}
		const n = resolveRoutedReplyDeliveryOutcome(t);
		if (n === "delivered") {
			const t = commandBlockMirror(e);
			if (t) registerReplyDispatcherSettledTask(c, () => mirrorDeliveredReplyToTranscript({
				metadata: t,
				cfg: r
			}));
		}
		recordBlockOutcome(e, Promise.resolve({
			outcome: n,
			pending: t.queueCustody === "held" || t.ambiguous === true
		}));
		return n;
	};
	const getBlockReplyOutcome = async (e, t) => {
		const n = U.get(createBlockReplyContentKey(e));
		if (!n || t?.aborted) return;
		const r = await runWithDispatchAbortSignal(t, () => Promise.all(n));
		return r.find(({ outcome: e }) => e === "delivered") ?? r.find(({ outcome: e, pending: t }) => t || !shouldRetryReplyDispatch(e)) ?? r[0];
	};
	const sendFinalPayload = async (n, i = {}) => {
		const a = i.abortSignal === false ? void 0 : i.abortSignal ?? e.getDispatchAbortSignal();
		const throwIfFinalDeliveryAborted = () => {
			if (a?.aborted) throw new DispatchReplyOperationAbortedError();
		};
		throwIfFinalDeliveryAborted();
		await L();
		throwIfFinalDeliveryAborted();
		const s = prepareReplyPayloadForDispatcher(c, "final", n);
		if (s.kind === "suppress") {
			await suppressPendingFinalDelivery(n);
			return {
				queuedFinal: false,
				routedFinalCount: 0,
				suppressionReason: s.reason
			};
		}
		const l = renderPostCompactionModelFailurePayload(s.payload);
		const u = getReplyPayloadMetadata(l);
		const f = normalizeOptionalString(m.replyOptions?.runId);
		const h = E.entry?.lifecycleRevision;
		const transcriptWriterMetadata = (e) => ({
			...e ? { expectedSessionId: e.sessionId } : {},
			...h !== void 0 ? { expectedLifecycleRevision: h } : {},
			...f ? { expectedWriterRunId: f } : {},
			storePath: e?.storePath ?? E.storePath
		});
		const g = v(u?.sourceReplyTranscriptMirror?.sessionKey);
		let _ = u?.sourceReplyTranscriptMirror ? {
			...u.sourceReplyTranscriptMirror,
			...transcriptWriterMetadata(g)
		} : void 0;
		const y = u?.assistantMessageIndex !== void 0 || Boolean(u?.inlineCommandReply || u?.assistantTranscriptOwned);
		const b = hasOutboundReplyContent(l, { trimText: true });
		if (b) {
			p();
			F = true;
		}
		const x = B && isCaptionedFinalTextPayload(l);
		const S = x ? mergeDeferredFinalText(i.deferredTtsText ?? "", l.text) : void 0;
		const C = x ? copyReplyPayloadMetadata(l, {
			...l,
			text: S
		}) : l;
		const D = x ? H ? cleanDeferredFinalText(S) : S : void 0;
		let O = l;
		if (!i.skipTts && l.isReasoning !== true && l.isCommentary !== true) try {
			O = await e.maybeApplyTtsWithFinalizationLease(C, "final");
		} catch (e) {
			if (!x) throw e;
			logVerbose(`dispatch-from-config: final TTS failed: ${formatErrorMessage$1(e)}`);
		}
		const k = x ? copyReplyPayloadMetadata(O, {
			...O,
			text: D || void 0
		}) : O;
		throwIfFinalDeliveryAborted();
		let A;
		try {
			A = await e.normalizeReplyMediaPayload(k);
		} catch (e) {
			if (!x || !D) throw e;
			logVerbose(`dispatch-from-config: media normalization failed: ${formatErrorMessage$1(e)}`);
			A = buildCaptionedFinalTextFallback(k);
		}
		throwIfFinalDeliveryAborted();
		const j = getReplyPayloadMetadata(l)?.blockReplySources;
		let N;
		if (j) {
			const e = await runWithDispatchAbortSignal(a, () => recoverBlockReplySources(A, j));
			A = e.payload;
			N = e.delivery;
		} else N = await getBlockReplyOutcome(l, a);
		throwIfFinalDeliveryAborted();
		const P = N?.outcome;
		const R = N?.pending && P !== "delivered";
		if (P && (R || !shouldRetryReplyDispatch(P))) {
			if (P === "channel-transform" || P === "failed-deliver" && !R && !j || createBlockReplyContentKey(A) === createBlockReplyContentKey(l)) return {
				blockDeliveryOutcome: P,
				pendingBlock: R,
				queuedFinal: false,
				routedFinalCount: 0
			};
			A = copyReplyPayloadMetadata(A, {
				...A,
				text: void 0
			});
			if (R) await suppressPendingFinalDelivery(l);
			if (R || j) {
				setReplyPayloadMetadata(A, { pendingFinalDeliveryCompletion: void 0 });
				_ = _ ? transcriptMirrorForDeliveredPayload(_, A) : void 0;
			}
			if (!hasOutboundReplyContent(A, { trimText: true })) return {
				blockDeliveryOutcome: P,
				pendingBlock: R,
				queuedFinal: false,
				routedFinalCount: 0
			};
		}
		await I(A);
		const z = t ?? E.sessionKey ?? T;
		const V = normalizeOptionalString(e.messageIdForHook) ?? normalizeOptionalString(m.replyOptions?.runId);
		const U = v(z);
		const W = o.CommandInterpretationSuppressed ? void 0 : normalizeOptionalString(resolveCommandContextText(o));
		const G = !y && W?.startsWith("/");
		const K = G ? scopeCommandTranscriptId(V, e.hookState.inboundClaimContext) : void 0;
		const q = _ ?? ((e.normalizedCurrentSurface === "slack" || G) && b && z ? transcriptMirrorForDeliveredPayload({
			sessionKey: z,
			agentId: w,
			...transcriptWriterMetadata(U),
			preferText: true,
			...G && W && K ? commandTranscriptMirror(e, W, K) : {},
			...y ? { transcriptOwner: true } : {},
			idempotencyKey: V ? `channel-final:${K ?? V}:${i.deliveryId ?? "single"}` : void 0,
			deliveryMirror: {
				kind: "channel-final",
				...V ? { sourceMessageId: V } : {}
			}
		}, A) : void 0);
		const routeFinalPayload = (t) => e.routeReplyToOriginating(t, {
			abortSignal: a,
			kind: "final",
			...y || G ? { mirror: false } : {}
		});
		let J = await routeFinalPayload(A);
		if (J) {
			let e = resolveRoutedReplyDeliveryOutcome(J);
			if (!J.ok) logVerbose(`dispatch-from-config: route-reply (final) failed: ${J.error ?? "unknown error"}`);
			const t = B && A.mediaUrl ? normalizeOptionalString(A.text) : void 0;
			if (t && shouldRetryReplyDispatch(e)) {
				J = await routeFinalPayload(copyReplyPayloadMetadata(A, { text: t })) ?? J;
				e = resolveRoutedReplyDeliveryOutcome(J);
			}
			if (d(J)) await mirrorDeliveredReplyToTranscript({
				metadata: G ? q : _,
				cfg: r
			});
			return {
				blockDeliveryOutcome: j ? P : void 0,
				pendingBlock: R,
				queuedFinal: J.ok,
				routedFinalCount: d(J) ? 1 : 0,
				routedOutcome: e,
				...J.reason === "channel_transform" ? { suppressionReason: "channel_transform" } : {}
			};
		}
		throwIfFinalDeliveryAborted();
		p();
		const { queued: Y, outcome: ee } = sendReplyWithTranscriptMirror({
			dispatcher: c,
			cfg: r,
			metadata: q,
			payload: A,
			send: (e) => {
				if (B && e.mediaUrl && e.text?.trim()) attachReplyDispatchUndeliveredFallback(e, buildCaptionedFinalTextFallback(e));
				return M.sendQueued("final", e);
			}
		});
		return {
			blockDeliveryOutcome: j ? P : void 0,
			pendingBlock: R,
			queuedFinal: Y,
			routedFinalCount: 0,
			...Y && ee ? { dispatcherOutcome: ee } : {}
		};
	};
	let W;
	if (e.allowInboundHandlers && !admittedSessionSettingsRestrictRuntime(m.replyOptions?.admittedSessionSettings) && u?.hasHooks("before_dispatch")) {
		const t = E.sessionKey ?? T;
		const n = createPluginSubagentRequesterContext({
			sessionKey: t,
			origin: {
				channel: y,
				to: x,
				accountId: g,
				threadId: b
			}
		});
		const r = await A("reply.before_dispatch_hooks", () => S(() => runWithDispatchAbortSignal(l(), () => {
			const r = e.hookState.hookContext;
			const i = {
				messageId: r.messageId,
				sessionKey: t,
				senderId: r.senderId,
				replyToId: r.replyToId,
				replyToIdFull: r.replyToIdFull,
				replyToBody: r.replyToBody,
				replyToSender: r.replyToSender,
				replyToIsQuote: r.replyToIsQuote
			};
			return u.runBeforeDispatch({
				...i,
				content: r.content,
				body: r.bodyForAgent ?? r.body,
				channel: r.channelId,
				isGroup: r.isGroup,
				timestamp: r.timestamp
			}, withClaimingHookAdmission({
				...i,
				channelId: r.channelId,
				accountId: r.accountId,
				conversationId: e.hookState.inboundClaimContext.conversationId
			}, { prepare: e.assertCurrentBindingRoute }), n);
		}, j)));
		if (r?.handled) W = {
			payload: { text: r.text },
			deliveryId: "before-dispatch",
			recordProcessed: () => h("completed", { reason: "before_dispatch_handled" })
		};
	}
	if (!W && e.dispatchKind === "acp" && admittedSessionSettingsRestrictRuntime(m.replyOptions?.admittedSessionSettings)) {
		const t = "This session's bound runtime cannot enforce its permission or tool policy; use an embedded runtime for this restricted conversation.";
		W = {
			payload: {
				text: t,
				isError: true
			},
			deliveryId: "restricted-runtime-takeover",
			recordProcessed: () => e.recordProcessed("error", {
				reason: "restricted_runtime_takeover",
				error: t
			})
		};
	}
	if (W) {
		const { queuedFinal: t, routedFinalCount: r } = W.payload.text && !e.suppressDelivery ? await sendFinalPayload(W.payload, {
			abortSignal: l(),
			deliveryId: W.deliveryId
		}) : {
			queuedFinal: false,
			routedFinalCount: 0
		};
		const o = c.getQueuedCounts();
		o.final += r;
		W.recordProcessed();
		f("message_completed");
		i();
		a();
		return {
			status: "complete",
			result: n({
				queuedFinal: t,
				counts: o
			})
		};
	}
	const G = e.dispatchKind === "acp" ? await acquireAcpDispatchTurn(e) : void 0;
	if (G) return G;
	const K = await runReplyDispatchHook(e, {
		shouldSendToolSummaries,
		shouldSendToolSummariesAsync
	});
	if (K?.handled) {
		i();
		a();
		return {
			status: "complete",
			result: n({
				queuedFinal: K.queuedFinal,
				counts: K.counts
			})
		};
	}
	const q = e.dispatchKind === "acp" ? void 0 : await acquireDispatchTurn(e);
	if (q) return q;
	return {
		status: "ready",
		state: Object.assign(e, {
			shouldSuppressProgressDelivery,
			shouldSuppressProgressDeliverySync,
			shouldSendToolSummaries,
			shouldSendToolSummariesAsync,
			notifySessionMetadataChanges: N,
			shouldDeliverVerboseProgressDespiteSourceSuppression,
			shouldDeliverForcedToolProgressDespiteSourceSuppression,
			shouldSuppressLateTextOnlyToolProgress,
			flushPendingCommentaryProgress: L,
			noteCommentaryProgress: R,
			shouldSuppressMessageToolOnlyTextErrorProgress,
			sendTrackedBlockReply,
			recordRoutedBlockReplyDelivery,
			sendFinalPayload,
			isSessionWriterDeliveryAuthorized,
			deferFinalTtsText: B,
			routeState: P
		})
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.block-reply.ts
function createDispatchBlockReplyHandler(e) {
	const { cleanBlockTtsDirectiveText: t, commentaryPayloadsEnabled: n, deferFinalTtsText: r, dispatcher: i, flushPendingCommentaryProgress: a, isDispatchOperationAborted: o, markInboundDedupeReplayUnsafe: s, markProgress: c, maybeApplyTtsWithFinalizationLease: l, normalizeReplyMediaPayload: u, params: d, reasoningPayloadsEnabled: f, shouldRouteToOriginating: p, trackDispatchLifecycleWork: m } = e;
	let h;
	let drain;
	const dispatchBlockReply = (g, _) => {
		const v = g.kind === "prepared" ? g.plan.payload : g.payload;
		setBlockReplyDelivery(Promise.resolve({ outcome: "cancelled" }));
		c();
		const run = async () => {
			if (o()) return;
			await a();
			const c = _?.deliveryIntentId !== void 0;
			if (c && e.suppressAcpChildUserDelivery) return;
			if (e.suppressDelivery && !shouldDeliverDespiteSourceReplySuppression(v, e)) return;
			if (v.isReasoning === true && !f || v.isCommentary === true && !n) return;
			const y = prepareReplyPayloadForSideEffects(i, "block", v, e.progressState, s);
			if (!y) return;
			const b = !isReplyPayloadStatusNotice(y) && !c && y.isReasoning !== true && y.isCommentary !== true;
			if (y.text && b) {
				const n = t?.hasBufferedDirectiveText() === true;
				if (e.progressState.accumulatedBlockText.length > 0) e.progressState.accumulatedBlockText += "\n";
				e.progressState.accumulatedBlockText += y.text;
				if (e.progressState.accumulatedBlockTtsText.length > 0 && !n) e.progressState.accumulatedBlockTtsText += "\n";
				e.progressState.accumulatedBlockTtsText += y.text;
			}
			let x;
			let S = y;
			if (y.text && t && b) {
				if (!r) x = h ?? createBlockReplySource();
				const e = t.push(y.text);
				const n = t.hasBufferedDirectiveText();
				x?.setComplete(!n);
				h = n ? x : void 0;
				S = copyReplyPayloadMetadata(y, {
					...y,
					text: e.trim() ? e : void 0
				});
			}
			const sendPrepared = async (t, n = false) => {
				let a = t;
				if (n) setBlockReplyDelivery(Promise.resolve({ outcome: "cancelled" }), a);
				if (r && b) {
					if (!Boolean(a.mediaUrl || a.mediaUrls?.length || a.presentation || a.interactive || a.channelData)) return;
					a = copyReplyPayloadMetadata(a, {
						...a,
						text: void 0
					});
				}
				if (!hasOutboundReplyContent(a, { trimText: true })) return;
				const f = getReplyPayloadMetadata(y);
				const h = f?.assistantMessageIndex !== void 0 ? {
					..._,
					assistantMessageIndex: f.assistantMessageIndex
				} : _;
				if (o()) return;
				const v = n || y.isReasoning === true || y.isCommentary === true ? a : await l(a, "block");
				const x = await u(v);
				let S = {
					kind: "raw",
					payload: x
				};
				if (g.kind === "prepared") {
					const e = createStructuredOutboundPayloadPlan([x])[0];
					if (!e) return;
					S = {
						kind: "prepared",
						plan: e
					};
				}
				if (o()) return;
				if (p || c && e.canRouteDurableBlockReply) {
					const t = await e.sendReplyOperationAsync(S, _?.abortSignal, "block", _?.deliveryIntentId);
					if (e.recordRoutedBlockReplyDelivery(x, t) === "delivered" && !e.suppressAutomaticSourceDelivery) await d.replyOptions?.onBlockReplyQueued?.(a, h);
				} else {
					s();
					const t = e.sendTrackedBlockReply(S);
					e.observeDeliveryProgress(t.outcome, "reply:block_delivered");
					if (t.queued) {
						const n = (t.outcome ?? i.waitForIdle()).then(() => void 0);
						n.catch(() => void 0);
						e.progressState.pendingDirectBlockReplyDelivery = n;
					}
					if (t.queued && !e.suppressAutomaticSourceDelivery && d.replyOptions?.onBlockReplyQueued) m((t.outcome ?? Promise.resolve("delivered")).then(async (e) => {
						if (e === "delivered" && !_?.abortSignal?.aborted) await d.replyOptions?.onBlockReplyQueued?.(a, h);
					}), "delivery");
				}
			};
			const sendWithSource = (e, t = false) => {
				const send = () => sendPrepared(e, t);
				return x ? x.run(send) : send();
			};
			if (t && b && y.text) drain = async (e) => {
				if (!e || r) {
					x?.setComplete(true);
					return;
				}
				if (o()) return;
				const t = buildCaptionedFinalTextFallback(y);
				t.text = e;
				x?.setComplete(true);
				await sendWithSource(t, true);
			};
			await sendWithSource(S);
		};
		return run();
	};
	const onBlockReply = (e, t) => dispatchBlockReply({
		kind: "raw",
		payload: e
	}, t);
	const onPreparedBlockReply = (e, t) => dispatchBlockReply({
		kind: "prepared",
		plan: e
	}, t);
	return {
		onBlockReply,
		onPreparedBlockReply,
		flush: async () => {
			if (!t?.hasBufferedDirectiveText()) return;
			const e = t.flush();
			const n = drain;
			drain = void 0;
			h = void 0;
			await n?.(e);
		}
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.turn-ledger.ts
const SETTLE_QUEUED_TIMEOUT_MS = 3e4;
const RAW_REPLY_SEND_METHODS = {
	tool: "sendToolResult",
	block: "sendBlockReply",
	final: "sendFinalReply"
};
async function requireQueuedReplyDelivery(e) {
	if (!e.delivery.queued) throw new Error("queued reply delivery failed");
	const t = e.delivery.outcome;
	if (!t) {
		const t = await waitForReplyDispatcherIdle(e.dispatcher, e.abortSignal);
		if (e.dispatcher.supportsSettledReceipt === true && t?.anyVisibleDelivered !== true) throw new Error("queued reply delivery failed");
		return;
	}
	const n = await runWithDispatchAbortSignal(e.abortSignal, () => t);
	if (n !== "delivered") throw new ReplyDispatchDeliveryError(n);
}
function createReplyTurnLedger(e) {
	const t = /* @__PURE__ */ new Set();
	let n = false;
	let r = "missing";
	const mayHaveDelivered = () => t.has("delivered") || t.has("failed-deliver");
	const recordDelivery = (e, i, a, o) => {
		n ||= o;
		if (!hasOutboundReplyContent(i, { trimText: true })) return;
		t.add(a);
		const s = e === "final" && i.isError === true && i.isStatusNotice === true;
		if (e === "tool" || !isReplyPayloadTerminalContent(i) && !s) return;
		if (a === "delivered" && !o) r = "delivered";
		else if (r !== "delivered" && (o || a === "failed-deliver" || a === "recovery-owned")) r = "pending";
	};
	const sendOperation = (t, n) => {
		const r = n.kind === "prepared" ? n.plan.payload : n.payload;
		const i = e.supportsSettledReceipt === true ? captureReplyDispatchDeliveryOutcome(r) : void 0;
		if (!(n.kind === "prepared" && e.sendPreparedReply ? e.sendPreparedReply(t, n.plan) : e[RAW_REPLY_SEND_METHODS[t]](r))) return { queued: false };
		if (!i || !i.isTracked()) {
			recordDelivery(t, r, "failed-deliver", false);
			return { queued: true };
		}
		return {
			queued: true,
			outcome: i.promise.then((e) => {
				recordDelivery(t, r, e, i.hasPendingDelivery());
				return e;
			}),
			hasPendingDelivery: i.hasPendingDelivery
		};
	};
	return {
		sendQueued: (e, t) => sendOperation(e, {
			kind: "raw",
			payload: t
		}),
		sendPreparedQueued: (e, t) => sendOperation(e, {
			kind: "prepared",
			plan: t
		}),
		recordRoutedDelivery(e, t, n) {
			const r = resolveRoutedReplyDeliveryOutcome(n);
			recordDelivery(e, t, r, n.queueCustody === "held" || n.ambiguous === true || r === "recovery-owned");
		},
		async settleQueued(r) {
			if (r?.aborted) return "aborted";
			const i = await raceWithTimeout(() => waitForReplyDispatcherIdle(e), SETTLE_QUEUED_TIMEOUT_MS, () => "timed-out", {
				ref: false,
				signal: r,
				onAbort: () => "aborted"
			});
			if (r?.aborted) return "aborted";
			if (i === "timed-out" || i === "aborted") return i;
			if (e.supportsSettledReceipt === true && i) for (const e of Object.values(i.counts)) {
				if (e.delivered > 0) t.add("delivered");
				if (e.failedAfterSend > 0) t.add("failed-deliver");
			}
			n ||= i?.hasPendingDelivery === true;
			return "settled";
		},
		mayHaveDelivered,
		hasObservedDelivery: () => t.has("delivered"),
		canAttemptFallback: () => !mayHaveDelivered() && !n && !t.has("recovery-owned"),
		resolveTerminalDelivery: () => r
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.execute.ts
async function executeDispatch(e) {
	const { cfg: t, commentaryPayloadsEnabled: n, ctx: r, deferFinalTtsText: i, dispatcher: a, failDispatchReplyOperation: o, flushPendingCommentaryProgress: s, getAgentRunTerminalOutcome: c, getDispatchAbortOperation: l, getDispatchAbortSignal: u, isDispatchOperationAborted: d, markInboundDedupeReplayUnsafe: f, markProgress: p, maybeApplyTtsWithFinalizationLease: m, normalizeReplyMediaPayload: h, noteCapturedFinalResponse: g, notifySessionMetadataChanges: _, onToolResultFromReplyOptions: v, onReasoningStream: y, params: b, reasoningPayloadsEnabled: x, replyConfig: S, resolveToolDeliveryPayload: C, runWithDispatchLifecycleAdmission: w, sendPayloadAsync: T, shouldForwardProgressCallback: E, shouldRouteToOriginating: D, trackDispatchLifecycleWork: O, typing: k, waitForPendingDirectBlockReplyDelivery: A, wrapProgressCallback: j } = e;
	const M = bindPreparedReplyDispatchRuntime(b.configOverride ? void 0 : e.preparedReplyDispatchRuntime, e.replyResolver);
	const N = readReplySourcePreparationRetry(readReplySourceInput(b.replyOptions));
	const P = N ? (...e) => N(() => M(...e)) : M;
	let F = false;
	let I;
	let L;
	const releasePendingContinuation = async () => {
		const e = I;
		I = void 0;
		await e?.settle(false);
	};
	let R = false;
	let z;
	const B = /* @__PURE__ */ new Set();
	let V;
	const { onBlockReply: H, onPreparedBlockReply: U, flush: W } = createDispatchBlockReplyHandler(e);
	const flushDeferredFinalText = async () => {
		try {
			if (!e.deferFinalTtsText) return;
			const t = e.cleanBlockTtsDirectiveText ? cleanDeferredFinalText(e.progressState.accumulatedBlockTtsText) : e.progressState.accumulatedBlockText;
			if (!t.trim()) return;
			const n = await e.sendFinalPayload({ text: t }, {
				abortSignal: d() ? false : void 0,
				skipTts: true
			});
			if (n.queuedFinal || n.routedFinalCount !== 0) {
				e.progressState.accumulatedBlockText = "";
				e.progressState.accumulatedBlockTtsText = "";
				R = true;
			}
		} catch (e) {
			logVerbose(`dispatch-from-config: deferred final text fallback failed: ${formatErrorMessage$1(e)}`);
		}
	};
	const forwardToolProgress = async (t) => {
		if (d()) return;
		p();
		await A(l()?.abortSignal);
		if (d()) return;
		f();
		if (await E({
			forwardWhenSourceDeliverySuppressed: true,
			requiresToolSummaryVisibility: true
		}) && !d()) {
			e.assertProgressCurrent();
			await t();
		}
	};
	const G = await w(async () => {
		const o = runWithDispatchAbortSignal(u(), () => e.traceReplyPhase("reply.run_reply_resolver", async () => {
			const o = {
				forwardWhenSourceDeliverySuppressed: true,
				requiresToolSummaryVisibility: true,
				waitForDirectBlockReplyDelivery: true
			};
			const c = {
				...o,
				allowWhenToolSummariesHidden: b.replyOptions?.allowToolLifecycleWhenProgressHidden === true
			};
			const w = e.getReplyOptions();
			const M = await P(r, {
				...w,
				...observeAgentRunStart(w, () => {
					if (!V && isExplicitFollowupCommandTurn(r) && e.replyOperationRunState.admission?.status !== "accepted") {
						V = Promise.resolve(H(markReplyPayloadForSourceSuppressionDelivery({
							text: "Your followup has started.",
							isStatusNotice: true
						})));
						O(V, "delivery");
					}
				}),
				preparedTtsPreferences: e.preparedTtsPreferences,
				withCommandNativeSubagents: (t, n) => runWithCommandNativeSubagents(e, t, n),
				[REPLY_OPERATION_RUN_STATE]: e.replyOperationRunState,
				sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
				sessionPromptSourceReplyDeliveryMode: e.sessionStableSourceReplyDeliveryMode,
				...e.sourceReplyDeliveryRuntimeOptions,
				mediaNormalizationOwner: e.isInternalWebchatTurn ? "gateway" : void 0,
				onPendingContinuation: (e) => {
					F = true;
					I ??= e;
				},
				...resolveDiagnosticModelContentCapturePolicy(t).outputMessages ? { onRawLlmResponse: (e) => {
					L = e;
					g(e);
				} } : {},
				onSessionMetadataChanges: _,
				onSessionPrepared: e.notePreparedSession,
				onRunVerbosityResolved: (t) => {
					e.noteRunVerbosity(t);
					b.replyOptions?.onRunVerbosityResolved?.(t);
				},
				onObservedReplyDelivery: e.markObservedReplyDelivery,
				typingPolicy: k.typingPolicy,
				suppressTyping: k.suppressTyping,
				onPartialReply: i ? void 0 : j(b.replyOptions?.onPartialReply, {
					onForward: async () => {
						await V;
						if (!e.deliverStandaloneCommentaryProgress) return;
						await Promise.allSettled(B);
						await s();
						await waitForReplyDispatcherIdle(a, u());
					},
					onVisible: (t) => {
						R ||= hasOutboundReplyContent(t, { trimText: true });
						if (R) e.getDispatchReplyOperation()?.watchdog.progress("finalization", "reply:partial_delivered");
					}
				}),
				onReasoningStream: y,
				onReasoningProgress: j(b.replyOptions?.onReasoningProgress, { forwardWhenSourceDeliverySuppressed: true }),
				streamReasoningInNonStreamModes: b.replyOptions?.streamReasoningInNonStreamModes,
				onReasoningEnd: j(b.replyOptions?.onReasoningEnd),
				onAssistantMessageStart: j(b.replyOptions?.onAssistantMessageStart),
				onQueuedFollowupSettled: async () => {
					try {
						await W();
						await A();
						if (a.getFailedCounts().block > 0 && e.turnLedger.canAttemptFallback()) await a.waitForIdle();
					} catch (e) {
						try {
							await b.replyOptions?.onQueuedFollowupSettled?.();
						} catch (e) {
							logVerbose(`dispatch-from-config: queued cleanup failed; preserving delivery error: ${formatErrorMessage$1(e)}`);
						}
						throw e;
					}
					await b.replyOptions?.onQueuedFollowupSettled?.();
				},
				onBlockReplyQueued: j(b.replyOptions?.onBlockReplyQueued),
				onToolStart: j(b.replyOptions?.onToolStart, {
					...c,
					onForward: async () => {
						await s();
					}
				}),
				onItemEvent: e.onItemEvent,
				commentaryProgressEnabled: e.deliverStandaloneCommentaryProgress || e.canForwardSuppressedSourceItemEvents || b.replyOptions?.commentaryProgressEnabled,
				reasoningPayloadsEnabled: x,
				commentaryPayloadsEnabled: n,
				onCommandOutput: j(b.replyOptions?.onCommandOutput, o),
				onCompactionStart: j(b.replyOptions?.onCompactionStart, c),
				onCompactionEnd: j(b.replyOptions?.onCompactionEnd, c),
				onToolResult: (t) => {
					e.getDispatchReplyOperation()?.recordActivity();
					p();
					const run = async () => {
						if (d()) return;
						await A(l()?.abortSignal);
						if (d()) return;
						f();
						await s();
						const n = isFastModeAutoProgressPayload(t);
						const i = e.shouldDeliverForcedToolProgressDespiteSourceSuppression();
						const o = b.replyOptions?.forceToolResultProgress === true;
						const c = b.replyOptions?.allowProgressCallbacksWhenSourceDeliverySuppressed === true && r.InboundEventKind !== "room_event";
						const u = requiresDurableToolResultDelivery(t);
						const p = o && u;
						const g = n && (!e.suppressAutomaticSourceDelivery && (o || await e.shouldSendToolSummariesAsync()) || i || await e.shouldDeliverVerboseProgressDespiteSourceSuppression());
						if (b.replyOptions?.suppressToolProgressMessages && !u) return;
						const _ = (o ? !p && (n || !await e.shouldEmitVerboseProgressAsync()) && await E({ forwardWhenSourceDeliverySuppressed: c }) : (await e.shouldSendToolSummariesAsync() || n && b.replyOptions?.allowToolLifecycleWhenProgressHidden === true) && await E(n ? { forwardWhenSourceDeliverySuppressed: c } : void 0)) ? v : void 0;
						let y = false;
						if (d()) return;
						e.assertProgressCurrent();
						if (_) y = (await settleProgressVisibilityCallbackResult(_(t))).visible;
						if (d()) return;
						if (_ && (n ? y || !g : o)) return;
						if (e.sendPolicyDenied) return;
						const x = i || g;
						if (await e.shouldSuppressProgressDelivery() && !x && !hasAskUserPayload(t)) return;
						const S = prepareReplyPayloadForSideEffects(a, "tool", x ? t : await C(t), e.progressState);
						if (!S) return;
						const w = await m(S, "tool");
						const O = await h(w);
						const k = x ? O : await C(O);
						if (!k || d()) return;
						if (e.shouldSuppressLateTextOnlyToolProgress(k) && !x) return;
						if (await e.shouldSuppressMessageToolOnlyTextErrorProgress(k)) return;
						if (!await e.shouldSendToolSummariesAsync() && !x && !requiresDurableToolResultDelivery(k)) return;
						const j = readAskUserQuestionId(k);
						if (j !== void 0 && !await isAskUserPromptPending(j)) return;
						if (d()) return;
						e.assertProgressCurrent();
						if (D) await T(k);
						else {
							const t = e.turnLedger.sendQueued("tool", k);
							if (hasAskUserPayload(k)) await requireQueuedReplyDelivery({
								delivery: t,
								dispatcher: a,
								abortSignal: l()?.abortSignal
							});
						}
					};
					const n = run();
					B.add(n);
					n.then(() => B.delete(n), () => B.delete(n));
					return n;
				},
				onPlanUpdate: async (t) => {
					if (d()) return;
					const n = normalizeAgentPlanSteps(t.steps);
					const r = {
						phase: t.phase,
						title: t.title,
						explanation: t.explanation,
						...t.explanationFormat ? { explanationFormat: t.explanationFormat } : {},
						steps: n,
						source: t.source
					};
					await forwardToolProgress(() => e.onPlanUpdateFromReplyOptions?.(r));
					if (d()) return;
					if (t.phase !== "update" || !await e.shouldSendToolSummariesAsync()) return;
					await e.sendPlanUpdate({
						explanation: r.explanation,
						explanationFormat: r.explanationFormat,
						steps: n
					});
				},
				onApprovalEvent: (t) => forwardToolProgress(() => e.onApprovalEventFromReplyOptions?.(t)),
				onPatchSummary: (t) => forwardToolProgress(() => e.onPatchSummaryFromReplyOptions?.(t)),
				onBlockReply: (e, t) => V ? V.then(() => H(e, t)) : H(e, t),
				onPreparedBlockReply: (e, t) => V ? V.then(() => U(e, t)) : U(e, t)
			}, e.preparedReplyDispatchRuntime && !b.configOverride ? void 0 : S);
			for (const e of Array.isArray(M) ? M : M ? [M] : []) {
				const t = getReplyPayloadMetadata(e)?.progressContinuation;
				if (t) {
					if (d()) t.close();
					else registerReplyDispatcherSettledTask(a, t.close);
				}
			}
			return M;
		}), O);
		try {
			return await o;
		} finally {
			await V;
			await W();
		}
	}).catch(async (t) => {
		await releasePendingContinuation();
		await flushDeferredFinalText();
		const n = c() === "failed";
		const r = e.turnAdoptionState?.adopted === true;
		if (!n && !R && !r || d()) throw t;
		if (isFileLogLevelEnabled("debug")) z = truncateUtf16Safe(formatErrorMessage(t, { redact: redactToolPayloadText }), 2048);
		o(t, "failed");
		if (!R) return r && isRequiredReplyExpectation(e.replyOperationRunState.replyCompletion?.expectation) && e.replyOperationRunState.replyCompletion?.outcome !== "blocked" && !e.suppressDelivery && !e.getObservedReplyDelivery() ? {
			text: GENERIC_EXTERNAL_RUN_FAILURE_TEXT,
			isError: true
		} : void 0;
		return buildTerminalAgentRunFailureReplyPayload({
			replyExpectation: e.replyOperationRunState.replyCompletion?.expectation ?? "required",
			visibleReplyDelivered: true
		});
	});
	try {
		if (d()) await flushDeferredFinalText();
		_(takeCommandSessionMetadataChanges(r));
		const t = isCommandReplyForDelivery(G) ? { status: "ready" } : await e.ensureDispatchReplyOperation("dispatch");
		if (t.status === "aborted") return {
			status: "complete",
			result: e.finishReplyOperationAbortedDispatch()
		};
		if (t.status === "busy") return {
			status: "complete",
			result: e.finishReplyOperationBusyDispatch({
				recordAgentDispatchCompleted: true,
				...e.routeState.sessionMetadataChangesForResult ? { sessionMetadataChanges: e.routeState.sessionMetadataChangesForResult } : {}
			})
		};
		if (e.ctx.AcpDispatchTailAfterReset === true) {
			e.ctx.AcpDispatchTailAfterReset = false;
			const t = await runReplyDispatchHook(e, {
				shouldSendToolSummaries: e.shouldSendToolSummaries,
				shouldSendToolSummariesAsync: e.shouldSendToolSummariesAsync,
				isTailDispatch: true
			});
			if (t?.handled) {
				e.commitInboundDedupeIfClaimed();
				e.recordAgentDispatchCompleted("completed");
				e.completeDispatchReplyOperation();
				return {
					status: "complete",
					result: e.attachSourceReplyDeliveryMode({
						queuedFinal: t.queuedFinal,
						counts: t.counts,
						...e.routeState.sessionMetadataChangesForResult ? { sessionMetadataChanges: e.routeState.sessionMetadataChangesForResult } : {}
					})
				};
			}
		}
		const n = Object.assign(e, {
			pendingContinuation: F,
			pendingContinuationSettlement: I,
			replyResult: G,
			replyResolverError: z,
			rawLlmResponse: L
		});
		I = void 0;
		return {
			status: "ready",
			state: n
		};
	} finally {
		await releasePendingContinuation();
	}
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.claim-retry.ts
/** Release only a proven pre-execution refusal while preserving its exact source and FIFO order. */
async function deferLifecycleBlockedDispatchClaim(e, t) {
	if (!(e instanceof ReplyRunLifecycleAdmissionBlockedError) || !t || t.operation || !deferSessionControllerClaimBeforeExecution(t)) return;
	releaseSessionControllerClaim(t);
	await t.settlement.promise;
	return e;
}
//#endregion
//#region src/auto-reply/reply/dispatch-session-archive.ts
async function restoreArchivedDispatchSession(e) {
	const { ctx: t, entry: n, hasPluginOwnedBinding: r, sessionKey: i, storePath: a } = e;
	if (!n || !i || !a || n.archivedAt === void 0 || r || t.InboundAccessAuthorized !== true || t.InboundEventKind === "room_event" || isNativeCommandTurn(t.CommandTurn) && t.CommandTurn?.authorized !== true || classifySessionStateActor({ inputProvenance: t.InputProvenance }).actorType !== "human") return n;
	try {
		return await restoreArchivedSession({
			...e,
			entry: n,
			sessionKey: i,
			storePath: a
		});
	} catch (e) {
		if (e instanceof SessionWorkStartChangedError) throw new DispatchSessionRefreshRequiredError(e);
		throw e;
	}
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.lifecycle.ts
function createDispatchReplyOperationCoordinator(e) {
	let t;
	let n;
	let r;
	let i;
	let a;
	let o;
	let removePreDispatchLifecycleAbortListener;
	let s;
	let c;
	let l = false;
	let u = false;
	const d = {
		owner: /* @__PURE__ */ new Set(),
		delivery: /* @__PURE__ */ new Set()
	};
	const trackDispatchLifecycleWork = (t, n = "owner") => {
		const r = readReplySourceInput(e.replyOptions);
		if (r && (n === "owner" || !r.claim?.operation)) trackSessionControllerSourceWork(r, t.catch((e) => {
			if (!(e instanceof DispatchSessionRefreshRequiredError) && (!r.abortSignal.aborted || e !== r.abortSignal.reason)) throw e;
		}));
		const i = d[n];
		const a = t.then(() => {}, () => {});
		i.add(a);
		a.then(() => {
			i.delete(a);
		});
	};
	const waitForDispatchDelivery = async () => {
		await Promise.allSettled(Array.from(d.delivery));
		await waitForReplyDispatcherIdle(e.dispatcher);
	};
	const waitForDispatchSettlement = async () => {
		await Promise.allSettled(Array.from(d.delivery));
		await waitForReplyDispatcherSettlement(e.dispatcher);
	};
	const releasePreDispatchLifecycleAdmission = async (t) => {
		removePreDispatchLifecycleAbortListener?.();
		removePreDispatchLifecycleAbortListener = void 0;
		const n = o;
		const r = s;
		const i = c;
		o = void 0;
		if (!n) return;
		const a = [...d.owner, ...d.delivery];
		const clearAbortControllers = () => {
			if (s === r) s = void 0;
			if (c === i) c = void 0;
		};
		try {
			if (t || a.length > 0) await Promise.allSettled(a);
			if (t) await waitForReplyBarrierSettlement(t(), e.dispatcher.resolveFollowupAdmissionBarrierTimeoutPolicy?.());
		} finally {
			clearAbortControllers();
			n.release();
		}
	};
	const armPreDispatchLifecycleAbortRelease = () => {
		const t = e.replyOptions?.turnAdoptionLifecycle?.abortSignal ?? e.replyOptions?.abortSignal;
		if (!t || !o) return;
		removePreDispatchLifecycleAbortListener?.();
		const onAbort = () => {
			releasePreDispatchLifecycleAdmission(() => waitForReplyDispatcherSettlement(e.dispatcher));
		};
		t.addEventListener("abort", onAbort, { once: true });
		removePreDispatchLifecycleAbortListener = () => t.removeEventListener("abort", onAbort);
		if (t.aborted) onAbort();
	};
	const runWithDispatchLifecycleAdmission = async (n) => {
		if (t) return await runWithReplyOperationLifecycleAdmission(t, n);
		const r = readReplySourceInput(e.replyOptions);
		const i = r ? () => withSessionControllerSource(r, n) : n;
		const a = o ? o.run(i) : Promise.resolve().then(i);
		if (r) trackSessionControllerSourceWork(r, a.catch((e) => {
			if (!isDispatchReplyOperationAbortedError(e)) throw e;
		}));
		return await a;
	};
	const ensureDispatchReplyOperation = async (d, f = false) => {
		const p = readReplySourceInput(e.replyOptions);
		const assertRequestCurrent = () => {
			const t = p?.sourceAdapter?.authority;
			t?.assertCurrent();
			if (e.replyOptions?.operatorAuthority !== t) e.replyOptions?.operatorAuthority?.assertCurrent();
			e.replyOptions?.internalEventExecution?.assertCurrent?.();
		};
		const m = resolveCommandTurnContext(e.ctx);
		const h = isActiveRunSafeCommandTurn({
			commandTurn: m,
			cfg: e.cfg,
			provider: e.ctx.Provider ?? e.ctx.Surface
		});
		if (isNativeCommandTurn(m) || h || resolveCommandTurnTargetSessionKey(e.ctx) && resolveCommandTurnTargetSessionKey(e.ctx) !== e.dispatchOperationSessionKey) {
			assertRequestCurrent();
			if (getPreDispatchAbortSignal()?.aborted || d !== "dispatch" && p?.retirementRequested) return { status: "aborted" };
			return { status: "ready" };
		}
		if (d === "pre_dispatch") {
			e.operationSessionStoreEntry.entry = await restoreArchivedDispatchSession({
				assertCurrent: () => getPreDispatchAbortSignal()?.throwIfAborted(),
				ctx: e.ctx,
				entry: e.operationSessionStoreEntry.entry,
				hasPluginOwnedBinding: f,
				placementContext: e.sessionWorkerPlacementContext,
				sessionKey: e.dispatchOperationSessionKey,
				storePath: e.operationSessionStoreEntry.storePath
			});
			({resetTriggered: u} = await resolveDispatchResetAdmission({
				agentId: e.agentId,
				cfg: e.cfg,
				ctx: e.ctx,
				entry: e.operationSessionStoreEntry.entry,
				hasPluginOwnedBinding: f,
				sessionKey: e.dispatchOperationSessionKey
			}));
		}
		if (d !== "pre_dispatch" && l) return { status: t ? "aborted" : "busy" };
		if (t) return { status: "ready" };
		if (i && !i.result) return { status: "busy" };
		if (d !== "pre_dispatch" && a?.result && a.result.kind !== "completed" && e.allowActiveQueueResolution !== true) {
			i = a;
			return { status: "busy" };
		}
		const g = e.dispatchOperationSessionKey;
		if (!g) return { status: "ready" };
		const _ = i?.sessionId ?? e.operationSessionStoreEntry.entry?.sessionId ?? crypto.randomUUID();
		const v = resolveReplyTurnKind(e.replyOptions);
		const y = p ? p.mailbox.owner.active : getSessionControllerOperation(g, e.operationSessionStoreEntry.storePath ? captureSessionTarget({
			storeScope: e.operationSessionStoreEntry.storePath,
			sessionKey: g,
			agentId: e.agentId,
			incarnation: e.operationSessionStoreEntry.entry?.sessionId
		}) : void 0);
		const b = isExplicitSteerCommandTurn(e.ctx) || isExplicitFollowupCommandTurn(e.ctx);
		const x = (isExplicitCommandTurnContext(e.ctx, e.cfg) || isUnauthorizedTextSlashCommand(e.ctx)) && !h && !b;
		const S = v === "visible" || e.replyOptions?.internalEventExecution !== void 0;
		const C = S && !x && (b || e.replyOptions?.turnAdoptionLifecycle !== void 0 || e.allowActiveQueueResolution === true);
		const w = S && (d === "pre_dispatch" || d === "command_resolution");
		const T = d !== "pre_dispatch" && C && y !== void 0;
		if (T) return { status: "ready" };
		if (d !== "pre_dispatch") {
			await releasePreDispatchLifecycleAdmission(() => waitForReplyDispatcherIdle(e.dispatcher));
			if (l) return { status: t ? "aborted" : "busy" };
		}
		const E = d !== "pre_dispatch" && shouldLetSlackRoutedThreadBypassBusyReplyOperation({
			activeOperation: y,
			ctx: e.ctx,
			routeThreadId: e.routeThreadId
		});
		const D = w || E ? new AbortController() : void 0;
		const onLifecycleInterrupt = () => {
			l = true;
			D?.abort();
		};
		if (p && (p.custody.enqueued || p.phase === "consumed" || p.injection)) return { status: "ready" };
		let O = p ? tryClaimSessionControllerTask(p, v) : void 0;
		if (p && d === "dispatch" && C) while (!O) {
			if (p.abortSignal.aborted || p.retirementRequested) return { status: "aborted" };
			if (p.mailbox.owner.active) return { status: "ready" };
			const t = p.mailbox.entries.filter((e) => e.sequence < p.sequence && e.phase !== "consumed" && !e.retirementRequested);
			if (!t.length) break;
			if (!await createReplyTurnAdmissionWaiter(p.mailbox.owner, {
				sessionKey: g,
				runId: e.replyOptions?.runId,
				upstreamAbortSignal: p.abortSignal
			}).inputs(void 0, t)) return { status: "aborted" };
			O = tryClaimSessionControllerTask(p, v);
		}
		if (p && !O) {
			if (p.abortSignal.aborted || p.retirementRequested) return { status: "aborted" };
			const t = p.mailbox.owner.active;
			if (t && isRecoverableTerminalSessionStatus(e.operationSessionStoreEntry.entry?.status)) {
				await t.watchdog.tick();
				O = tryClaimSessionControllerTask(p, v);
			}
			if (!O && (w || E)) return { status: "ready" };
			if (!O) {
				const e = claimSessionControllerTask(p, () => {}, v);
				try {
					O = await e;
				} catch (e) {
					if (p.abortSignal.aborted) return { status: "aborted" };
					throw e;
				}
			}
		}
		let k;
		try {
			k = await admitReplyTurn({
				mailboxClaim: O,
				runId: e.replyOptions?.runId,
				onDatabaseRegistration: e.replyOptions?.onDatabaseRegistration,
				assertRequestCurrent,
				providerReviewAcknowledgment: e.replyOptions?.providerReviewAcknowledgment,
				agentId: e.agentId,
				sessionKey: g,
				resolveGatewayContext: readChannelContextGatewayContextResolver(e.ctx) ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext,
				sessionId: _,
				expectedSessionId: e.replyOptions?.expectedExistingSessionId ?? e.resolveOperationExpectedSessionId(),
				expectedActiveOperations: [e.replyOptions?.expectedActiveReplyOperation, e.initialDispatchReplyOperation].filter((e) => e !== void 0),
				storePath: e.operationSessionStoreEntry.storePath,
				expectedDatabaseIncarnation: r,
				kind: v,
				resetTriggered: u,
				routeThreadId: e.routeThreadId,
				originatingLeafEntryId: e.replyOptions?.turnAdoptionLifecycle?.originatingLeafEntryId,
				upstreamAbortSignal: p?.abortSignal ?? e.replyOptions?.abortSignal,
				waitForActive: !w && !E,
				retainLifecycleAdmissionOnActive: w || E,
				onLifecycleInterrupt
			});
			if (O) {
				const e = O;
				if (k.status === "owned") {
					const releaseClaim = () => releaseSessionControllerClaim(e);
					waitForReplyOperationSourceRelease(k.operation).then(releaseClaim);
				} else releaseSessionControllerClaim(e);
			}
		} catch (e) {
			const t = await deferLifecycleBlockedDispatchClaim(e, O);
			if (t) {
				if (p?.abortSignal.aborted || p?.retirementRequested) return { status: "aborted" };
				r ??= t.databaseIncarnation;
				return await ensureDispatchReplyOperation(d, f);
			}
			if (O) releaseSessionControllerClaim(O);
			if (d === "pre_dispatch" && v === "visible" && isSessionWorkStartInvalidatedError(e)) throw new DispatchSessionRefreshRequiredError(e);
			throw e;
		}
		n = k.status === "owned" ? k.operation.sessionId : k.sessionEntry?.sessionId;
		const A = resolveReplyOperationRunState(e.replyOptions);
		if (A && A.admission?.status !== "accepted") A.admission = k.status === "owned" ? { status: "owned" } : {
			status: "skipped",
			reason: k.reason
		};
		if (k.status === "skipped") {
			if (k.error) e.replyOptions?.internalEventExecution?.onFailed?.(k.error);
			if (k.reason === "active-run" && !O && (w || shouldLetSlackRoutedThreadBypassBusyReplyOperation({
				activeOperation: k.activeOperation,
				ctx: e.ctx,
				routeThreadId: e.routeThreadId
			}))) {
				if (w && !T) a = k.activeOperation;
				o = k.lifecycleAdmission;
				if (w && d === "pre_dispatch") s = D;
				else c = D;
				armPreDispatchLifecycleAbortRelease();
				return { status: "ready" };
			}
			k.lifecycleAdmission?.release();
			i = k.activeOperation;
			logVerbose(`dispatch-from-config: skipped reply operation admission for ${g}; reason=${k.reason}`);
			return { status: "busy" };
		}
		if (v === "visible" && isRecoverableTerminalSessionStatus(e.operationSessionStoreEntry.entry?.status) && _ === e.operationSessionStoreEntry.entry?.sessionId) k.operation.markTerminalRecovery();
		t = k.operation;
		i = k.operation;
		e.replyOptions?.onReplyOperationOwned?.(k.operation);
		return { status: "ready" };
	};
	let f;
	let p;
	let m;
	let h;
	const getPreDispatchAbortSignal = () => {
		const t = (i ?? a)?.abortSignal;
		const n = s?.signal;
		const r = e.replyOptions?.abortSignal;
		if (f === t && p === n && m === r) return h;
		const o = [
			t,
			n,
			r
		].filter((e) => Boolean(e));
		h = o.length > 1 ? AbortSignal.any(o) : o[0];
		f = t;
		p = n;
		m = r;
		return h;
	};
	const getDispatchAbortSignal = () => {
		if (t) return t.abortSignal;
		const n = c?.signal ?? s?.signal;
		const r = e.replyOptions?.abortSignal;
		return n && r ? AbortSignal.any([n, r]) : n ?? r;
	};
	const getQueuedFollowupAbortSignal = () => e.replyOptions?.turnAdoptionLifecycle?.abortSignal ?? t?.abortSignal ?? e.replyOptions?.abortSignal;
	let g = false;
	let _;
	const observeDeliveryProgress = (e, n) => {
		const r = t;
		e?.then((e) => {
			if (e === "delivered") r?.watchdog.progress("finalization", n);
		}, () => {});
	};
	const markObservedReplyDelivery = async () => {
		if (g) return;
		g = true;
		t?.watchdog.progress("finalization", "reply:delivery_observed");
		await e.replyOptions?.onObservedReplyDelivery?.();
	};
	const getReplyOptions = () => {
		const r = getDispatchAbortSignal();
		const o = e.replyOptions?.expectedExistingSessionId ? t?.sessionId ?? e.replyOptions.expectedActiveReplyOperation?.sessionId ?? a?.sessionId ?? n : void 0;
		return {
			...e.replyOptions,
			...o ? { expectedExistingSessionId: o } : {},
			...r ? {
				abortSignal: r,
				queuedFollowupAbortSignal: getQueuedFollowupAbortSignal()
			} : {},
			...observeAgentRunStart(e.replyOptions, (t) => {
				_ = "completed";
				e.messageAuditTerminal?.observeRunId(t.runId);
			}),
			onAgentRunTerminalOutcome: (t) => {
				if (t === "failed" || _ === void 0) _ = t;
				e.replyOptions?.onAgentRunTerminalOutcome?.(t);
			},
			...t ? { replyOperation: t } : {},
			onReplyOperationOwned: (r) => {
				if (t && t !== r) throw new Error("Reply dispatch already owns another operation");
				r.abortSignal.throwIfAborted();
				e.replyOptions?.abortSignal?.throwIfAborted();
				e.replyOptions?.onReplyOperationOwned?.(r);
				e.replyOptions?.internalEventExecution?.assertCurrent?.();
				t = r;
				i = r;
				n = r.sessionId;
				return true;
			}
		};
	};
	const completeDispatchReplyOperation = () => {
		releasePreDispatchLifecycleAdmission(waitForDispatchSettlement);
		const n = t;
		if (!n) return;
		const r = e.dispatcher.resolveFollowupAdmissionBarrierTimeoutPolicy?.();
		const complete = () => {
			if (e.replyOptions?.internalEventExecution) {
				const settle = () => n.completeWithAfterClearBarrier(waitForReplyDispatcherSettlement(e.dispatcher), r);
				waitForDispatchDelivery().then(settle, settle);
			} else n.completeWithAfterClearBarrier(waitForDispatchSettlement(), r);
		};
		if (d.owner.size > 0) Promise.allSettled(Array.from(d.owner)).then(complete);
		else complete();
	};
	const failDispatchReplyOperation = (e, n) => {
		if (n === "failed") _ = "failed";
		t?.freezeAbort();
		if (t && !t.result) t.fail("run_failed", e);
		completeDispatchReplyOperation();
	};
	const isDispatchOperationAborted = () => getDispatchAbortSignal()?.aborted === true;
	const isPreDispatchOperationAborted = () => getPreDispatchAbortSignal()?.aborted === true;
	const throwIfDispatchOperationAborted = () => {
		if (isDispatchOperationAborted()) throw new DispatchReplyOperationAbortedError();
	};
	const v = createReplyTurnLedger(e.dispatcher);
	return {
		completeDispatchReplyOperation,
		dispatchHookDispatcher: createAbortAwareDispatcher({
			dispatcher: {
				...e.dispatcher,
				sendToolResult: (e) => v.sendQueued("tool", e).queued,
				sendBlockReply: (e) => v.sendQueued("block", e).queued,
				sendFinalReply: (e) => v.sendQueued("final", e).queued,
				...e.dispatcher.sendPreparedReply ? { sendPreparedReply: (e, t) => v.sendPreparedQueued(e, t).queued } : {}
			},
			isAborted: isPreDispatchOperationAborted
		}),
		turnLedger: v,
		ensureDispatchReplyOperation,
		failDispatchReplyOperation,
		getAgentRunTerminalOutcome: () => _,
		getDispatchAbortOperation: () => i,
		getDispatchAbortSignal,
		getDispatchReplyOperation: () => t,
		getReplyOptions,
		getObservedReplyDelivery: () => g,
		getPreDispatchAbortSignal,
		isDispatchOperationAborted,
		isPreDispatchOperationAborted,
		markObservedReplyDelivery,
		observeDeliveryProgress,
		releasePreDispatchLifecycleAdmission,
		runWithDispatchLifecycleAdmission,
		throwIfDispatchOperationAborted,
		trackDispatchLifecycleWork
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.timing.ts
const replyHotPathTimingLog = createSubsystemLogger("auto-reply/reply-timing");
function createReplyHotPathTimingTracker(e = {}) {
	const t = createReplyTimingTracker({
		log: replyHotPathTimingLog,
		enabled: e.profilerEnabled === true,
		formatMessage: (e, t, n) => `reply hot path timings channel=${e.channel} messageId=${e.messageId ?? "unknown"} runId=${e.runId ?? "unknown"} sessionId=${e.sessionId ?? "unknown"} sessionKey=${e.sessionKey ?? "unknown"} outcome=${e.outcome} totalMs=${t.totalMs} stages=${n}${e.reason ? ` reason=${e.reason}` : ""}`,
		detailKeys: () => [
			"channel",
			"messageId",
			"runId",
			"sessionId",
			"sessionKey",
			"outcome",
			"reason"
		]
	});
	return {
		measure: t.measure,
		logIfSlow(n, r) {
			if (!e.profilerEnabled && !r?.beforeReplyResolver) return;
			t.logIfSlow(n);
		},
		logPreparationIfSlow(e) {
			t.logIfSlow({
				...e,
				outcome: "milestone",
				reason: "before_reply_resolver"
			}, { repeat: true });
		}
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.gather.ts
async function gatherDispatchRequest(e, t, n = false, r, i) {
	const a = getAgentEventLifecycleGeneration();
	const o = isFinalizedInboundContext(e.ctx) ? e.ctx : finalizeInboundContext(e.ctx);
	const s = e.replyOptions?.turnAdoptionLifecycle;
	prepareChannelParticipantObservation(o);
	const c = { adopted: false };
	const l = {
		...e,
		ctx: o,
		replyOptions: {
			...e.replyOptions,
			...s ? { turnAdoptionLifecycle: {
				...s,
				onAdopted: async () => {
					await s.onAdopted();
					c.adopted = true;
				}
			} } : {}
		}
	};
	let u;
	const d = l.replyOptions?.turnAdoptionLifecycle?.onAdopted;
	if (d) {
		let e = true;
		let t;
		let n;
		const assertCurrent = () => {
			if (!e) throw new Error("Reply input adoption is no longer active.");
			if (n) throw n.error;
		};
		u = {
			assertCurrent,
			adopt: () => {
				assertCurrent();
				return t ??= Promise.resolve().then(d).catch((e) => {
					n = { error: e };
					throw e;
				});
			}
		};
		i?.(() => {
			e = false;
		});
	}
	const f = resolveReplyOperationRunState(l.replyOptions) ?? {};
	let p = false;
	const m = {
		params: l,
		turnAdoption: u,
		messageAuditTerminal: t,
		allowInboundHandlers: !e.replyOptions?.internalEventExecution,
		get inboundDedupeReplayUnsafe() {
			const e = f.admission;
			return p || e?.status === "accepted" && e.mode === "steer" || e?.status === "skipped" && (e.reason === "question-response-indeterminate" || e.reason === "collaborative-steering-disabled");
		},
		turnAdoptionState: s ? c : void 0
	};
	const { cfg: h, dispatcher: g } = l;
	bindReplyDispatcherConversationContext(g, o.agentText);
	const _ = resolveSessionAgentId({
		sessionKey: resolveCommandTurnTargetSessionKey(o) ?? o.SessionKey,
		config: h,
		fallbackAgentId: o.AgentId
	});
	await waitForAgentDatabaseWriteAdmission(_, { signal: e.replyOptions?.abortSignal });
	const v = readAgentDatabaseAdmissionRefusal(_);
	if (v) {
		const n = e.replyOptions?.abortSignal?.aborted === true;
		const r = !n && g.sendFinalReply({
			text: `${v.reason}\n${v.repairHint}`,
			isError: true
		});
		const i = n ? "skipped" : "error";
		const a = n ? "reply_operation_aborted" : v.code;
		noteDispatchProcessedOutcome({
			outcome: i,
			reason: a
		});
		t?.note(i, { reason: a });
		return {
			status: "complete",
			result: {
				queuedFinal: r,
				counts: g.getQueuedCounts()
			}
		};
	}
	const y = isDiagnosticsEnabled(h);
	const b = normalizeLowercaseStringOrEmpty(o.Surface ?? o.Provider ?? "unknown");
	const x = o.To ?? o.From;
	const S = o.MessageSidFull ?? o.MessageSid ?? o.MessageSidFirst ?? o.MessageSidLast;
	const C = normalizeOptionalString(o.SessionKey) ?? normalizeOptionalString(o.CommandTargetSessionKey);
	const w = y ? Date.now() : 0;
	const T = y && Boolean(C);
	const assertRequestCurrent = () => e.replyOptions?.operatorAuthority?.assertCurrent();
	const E = await resolveSessionStoreLookup(o, h, assertRequestCurrent);
	assertRequestCurrent();
	const D = E.sessionKey === C ? E.entry?.sessionId : void 0;
	const O = o.Body ?? o.RawBody ?? "";
	const k = createDiagnosticMessageLifecycle({
		enabled: y,
		channel: b,
		chatId: x,
		messageId: S,
		sessionKey: C,
		sessionId: D,
		agentId: _,
		source: "dispatch",
		processingReason: "message_start",
		startedAtMs: w,
		trackSessionState: T,
		userPrompt: O
	});
	const A = {
		surface: b,
		hasSessionKey: Boolean(C),
		hasRunId: e.replyOptions?.runId !== void 0
	};
	const j = createReplyHotPathTimingTracker({ profilerEnabled: isReplyProfilerEnabled({ config: h }) });
	const traceReplyPhase = (e, t) => j.measure(e, () => measureDiagnosticsTimelineSpan(e, t, {
		phase: "agent-turn",
		config: h,
		attributes: A
	}));
	let M = 0;
	let N;
	const noteCapturedFinalResponse = (e) => {
		N = e;
	};
	const recordProcessed = (n, r) => {
		const i = r?.finalResponse === void 0 && N !== void 0 ? {
			...r,
			finalResponse: N
		} : r;
		noteDispatchProcessedOutcome({
			outcome: n,
			...i?.reason !== void 0 ? { reason: i.reason } : {}
		});
		t?.note(n, i);
		if (y) j.logIfSlow({
			channel: b,
			messageId: S,
			runId: e.replyOptions?.runId,
			sessionId: D,
			sessionKey: C,
			outcome: n,
			reason: i?.reason
		}, { beforeReplyResolver: M === 0 });
		k.markProcessed(n, i);
	};
	const finishReplyOperationAborted = () => {
		recordProcessed("skipped", { reason: "reply_operation_aborted" });
		return {
			status: "complete",
			result: {
				queuedFinal: false,
				counts: g.getQueuedCounts()
			}
		};
	};
	if (e.replyOptions?.abortSignal?.aborted) return finishReplyOperationAborted();
	const recordAgentDispatchStarted = () => {
		if (!y || M > 0) return;
		M = Date.now();
		j.logPreparationIfSlow({
			channel: b,
			messageId: S,
			runId: e.replyOptions?.runId,
			sessionId: D,
			sessionKey: C
		});
		logMessageDispatchStarted({
			channel: b,
			sessionKey: F,
			source: "replyResolver"
		});
	};
	const recordAgentDispatchCompleted = (e, t) => {
		if (!y || M <= 0) return;
		logMessageDispatchCompleted({
			channel: b,
			sessionKey: F,
			source: "replyResolver",
			durationMs: Date.now() - M,
			outcome: e,
			reason: t?.reason,
			error: t?.error
		});
	};
	const markInboundDedupeReplayUnsafe = () => {
		p = true;
	};
	const P = m.allowInboundHandlers ? await resolveBoundAcpDispatchSessionKey({
		ctx: o,
		cfg: h
	}) : void 0;
	const F = P ?? E.sessionKey ?? C;
	const I = normalizeOptionalString(o.SessionKey);
	const L = I ?? E.sessionKey ?? C ?? F;
	const R = I && E.sessionKey && I !== E.sessionKey ? await resolveSessionStoreLookup({
		...o,
		CommandTargetSessionKey: void 0
	}, h, assertRequestCurrent) : E;
	assertRequestCurrent();
	if (e.replyOptions?.abortSignal?.aborted) return finishReplyOperationAborted();
	const z = readReplySourceInput(l.replyOptions);
	const B = z ? z.mailbox.owner.active : L ? getSessionControllerOperation(L, R.storePath ? captureSessionTarget({
		storeScope: R.storePath,
		sessionKey: L,
		agentId: R.agentId,
		incarnation: R.entry?.sessionId
	}) : void 0) : void 0;
	const markProgress = () => {
		if (!T || !C) return;
		markDiagnosticSessionProgress({ sessionKey: C });
		if (F && F !== C) markDiagnosticSessionProgress({ sessionKey: F });
	};
	const V = P ? await resolveSessionStoreLookup({
		...o,
		SessionKey: P
	}, h, assertRequestCurrent) : E;
	assertRequestCurrent();
	if (e.replyOptions?.abortSignal?.aborted) return finishReplyOperationAborted();
	const H = resolveSessionDispatchKind(F, V.entry);
	const toSessionBinding = ({ sessionKey: e, entry: t, storePath: n }) => e && t?.sessionId ? {
		sessionKey: e,
		sessionId: t.sessionId,
		lifecycleRevision: t.lifecycleRevision,
		storePath: n
	} : void 0;
	let U = toSessionBinding(V);
	let W = toSessionBinding(R);
	const sessionKeysMatch = (e, t) => Boolean(e && t && normalizeExplicitSessionKey(e, o) === normalizeExplicitSessionKey(t, o));
	const notePreparedSession = (t) => {
		if (sessionKeysMatch(t.sessionKey, V.sessionKey)) U = t;
		if (sessionKeysMatch(t.sessionKey, R.sessionKey)) W = t;
		e.replyOptions?.onSessionPrepared?.(t);
	};
	const resolveOperationExpectedSessionId = () => W?.sessionId ?? R.entry?.sessionId;
	const resolvePreparedTranscriptBinding = (e) => U && sessionKeysMatch(e, U.sessionKey) ? U : void 0;
	const G = resolveSessionAgentId({
		sessionKey: F,
		config: h,
		fallbackAgentId: o.AgentId
	});
	const K = resolveAgentConfig(h, G);
	const q = resolveEffectiveReplyRoute({
		ctx: o,
		entry: V.entry
	});
	const J = resolveRoutedDeliveryThreadId({
		ctx: o,
		sessionKey: F
	});
	const Y = q.threadId ?? J;
	const ee = hasInboundAudio(o);
	const te = normalizeTtsAutoMode(V.entry?.ttsAuto);
	const ne = P ? resolveBoundAcpDispatchRuntimeOwner({
		sessionKey: C,
		cfg: h,
		ctx: o
	}) : G;
	let X;
	let re;
	try {
		X = await traceReplyPhase("reply.load_prepared_dispatch_runtime", async () => {
			const { loadPublishedGatewayReplyDispatchRuntime: t } = await loadPreparedModelRuntime();
			return await t({
				agentId: ne,
				demand: e.replyOptions?.scheduledAutomation ? "scheduled" : "interactive",
				abortSignal: e.replyOptions?.abortSignal,
				onRuntimeLease: r
			});
		});
		re = await prepareTtsPreferences();
		e.replyOptions?.abortSignal?.throwIfAborted();
		e.replyOptions?.operatorAuthority?.assertCurrent();
	} catch (t) {
		if (e.replyOptions?.abortSignal?.aborted && isAbortError(t)) return finishReplyOperationAborted();
		throw t;
	}
	const ie = X?.workspaceDir ?? resolveAgentWorkspaceDir(h, G);
	const ae = createDispatchReplyOperationCoordinator({
		allowActiveQueueResolution: n,
		agentId: R.agentId ?? G,
		cfg: h,
		ctx: o,
		dispatcher: g,
		dispatchOperationSessionKey: L,
		initialDispatchReplyOperation: B,
		messageAuditTerminal: t,
		operationSessionStoreEntry: R,
		replyOptions: l.replyOptions,
		resolveOperationExpectedSessionId,
		routeThreadId: J,
		sessionWorkerPlacementContext: l.sessionWorkerPlacementContext
	});
	const { getPreDispatchAbortSignal: oe } = ae;
	const assertProgressCurrent = () => {
		assertAgentRunLifecycleGenerationCurrent(a);
		e.replyOptions?.abortSignal?.throwIfAborted();
		ae.getDispatchAbortSignal()?.throwIfAborted();
		assertRequestCurrent();
	};
	const Z = createShouldEmitVerboseProgress({
		agentId: G,
		sessionKey: F,
		storePath: V.storePath,
		initialExplicitLevel: V.entry?.verboseLevel,
		assertCurrent: assertProgressCurrent,
		fallbackLevel: normalizeVerboseLevel(V.entry?.verboseLevel ?? K?.verboseDefault ?? h.agents?.defaults?.verboseDefault ?? "") ?? "off"
	});
	i?.(Z.release);
	const se = X?.inboundPluginRegistry ?? await traceReplyPhase("reply.load_runtime_plugin_registry_handle", async () => {
		const { loadAgentRuntimePluginRegistryHandle: e } = await traceReplyPhase("reply.load_runtime_plugins", loadRuntimePlugins);
		return e({
			config: h,
			workspaceDir: ie,
			allowGatewaySubagentBinding: true
		});
	});
	const ce = getGlobalHookRunner();
	const le = o.Timestamp !== void 0 && Number.isFinite(o.Timestamp) ? o.Timestamp : void 0;
	const ue = o.MessageSidFull ?? o.MessageSid ?? o.MessageSidFirst ?? o.MessageSidLast;
	const Q = { ...o };
	const buildHookState = (e) => {
		const t = deriveInboundMessageHookContext(e, { messageId: ue });
		const n = toPluginInboundClaimPair(t, {
			commandAuthorized: o.CommandAuthorized,
			wasMentioned: o.WasMentioned
		});
		return {
			hookContext: t,
			inboundClaimContext: n.context,
			inboundClaimEvent: n.event
		};
	};
	const $ = buildHookState(Q);
	const { isGroup: de, groupId: fe } = $.hookContext;
	let pe = false;
	let me = false;
	const prepareHookMediaMetadata = async () => {
		if (pe) return;
		pe = true;
		if (await traceReplyPhase("reply.stage_remote_media_for_dispatch", () => stageRemoteInboundMediaIfNeeded({
			ctx: Q,
			cfg: h,
			agentId: G,
			sessionKey: F,
			workspaceDir: ie,
			remoteMediaMode: "cache",
			abortSignal: oe()
		}))) {
			me = true;
			Object.assign($, buildHookState(Q));
		}
	};
	const buildMessageReceivedHookContext = () => {
		const e = normalizeOptionalString(o.MediaRemoteHost);
		const { hookContext: t } = $;
		const n = Boolean(t.media?.length);
		if (me || !e || !n) return t;
		const r = { ...Q };
		stripLegacyMediaContextFields(r);
		delete r.media;
		return {
			...buildHookState(r).hookContext,
			mediaRemoteHost: e,
			mediaStagingPending: true,
			originalMedia: t.media?.map((e) => ({ ...e })),
			originalMediaPath: t.mediaPath,
			originalMediaUrl: t.mediaUrl,
			originalMediaType: t.mediaType,
			originalMediaPaths: t.mediaPaths,
			originalMediaUrls: t.mediaUrls,
			originalMediaTypes: t.mediaTypes
		};
	};
	return {
		status: "ready",
		state: Object.assign(m, {
			ctx: o,
			cfg: h,
			dispatcher: g,
			sessionKey: C,
			traceReplyPhase,
			recordProcessed,
			noteCapturedFinalResponse,
			recordAgentDispatchStarted,
			recordAgentDispatchCompleted,
			markProcessing: () => k.markProcessing(),
			markIdle: (e) => k.markIdle(e),
			markInboundDedupeReplayUnsafe,
			acpDispatchSessionKey: F,
			dispatchKind: H,
			markProgress,
			sessionStoreEntry: V,
			notePreparedSession,
			resolvePreparedTranscriptBinding,
			sessionAgentId: G,
			dispatchOperationSessionKey: L,
			operationSessionStoreEntry: R,
			noteRunVerbosity: Z.noteRunVerbosity,
			assertProgressCurrent,
			shouldEmitVerboseProgress: Z.shouldEmit,
			shouldEmitFullVerboseProgress: Z.shouldEmitFull,
			shouldEmitVerboseProgressAsync: Z.shouldEmitAsync,
			shouldEmitFullVerboseProgressAsync: Z.shouldEmitFullAsync,
			replyRoute: q,
			routeReplyThreadId: Y,
			inboundAudio: ee,
			sessionTtsAuto: te,
			workspaceDir: ie,
			preparedReplyDispatchRuntime: X,
			preparedTtsPreferences: re,
			pluginRegistry: se,
			replyOperationRunState: f,
			...ae,
			hookRunner: ce,
			timestamp: le,
			messageIdForHook: ue,
			isGroup: de,
			groupId: fe,
			hookState: $,
			prepareHookMediaMetadata,
			buildMessageReceivedHookContext
		})
	};
}
//#endregion
//#region src/auto-reply/reply/conversation-turn-capture.ts
const CONVERSATION_TURN_REPLY_CUSTOM_TYPE = "openclaw.conversation-turn-reply";
function readPersistedReplyText(e) {
	const t = e?.content;
	return normalizeOptionalString(typeof t === "string" ? t : collectTextContentBlocks(t).join("\n"));
}
async function capturePendingConversationTurnReplyUnsafe(e) {
	if (e.ctx.InboundAccessAuthorized !== true) return false;
	const t = normalizeOptionalString(e.ctx.SessionKey);
	const n = normalizeOptionalString(e.ctx.MessageSidFull) ?? normalizeOptionalString(e.ctx.MessageSid) ?? normalizeOptionalString(e.ctx.MessageSidFirst) ?? normalizeOptionalString(e.ctx.MessageSidLast);
	const r = normalizeOptionalString(e.ctx.agentText);
	if (!t || !n || !r) return false;
	const i = conversationIdentityFromMsgContext({ ctx: e.ctx });
	if (!i) return false;
	const a = normalizeOptionalString(e.ctx.ReplyToIdFull) ?? normalizeOptionalString(e.ctx.ReplyToId);
	if (!a) return false;
	const o = e.ctx.MessageThreadId == null ? void 0 : normalizeOptionalString(String(e.ctx.MessageThreadId));
	const s = {
		messageId: n,
		...a ? { replyToId: a } : {},
		...o ? { threadId: o } : {}
	};
	const c = normalizeOptionalString(e.ctx.AgentId) ?? resolveAgentIdFromSessionKey(t);
	const l = resolveSessionStorePathCore(e.cfg.session?.store, { agentId: c });
	const u = new Set([...captureSessionStoreCandidateIdentities(captureSessionStoreReadCandidates(l)).values()].map((e) => e.key));
	const d = resolveSqliteSessionKey(t, c);
	let f = false;
	const p = onSessionIdentityMutation((e) => {
		if (typeof e.databaseIdentity === "string" && u.has(`file:${e.databaseIdentity}`) && (e.previous.sessionKeys.includes(d) || e.kind !== "delete" && e.current.sessionKeys.includes(d))) f = true;
	});
	let m;
	let h;
	try {
		m = await prepareConversationRegistryScope({
			agentId: c,
			config: e.cfg
		});
		h = await readSessionEntryReadOnlyInWorker({
			...m,
			sessionKey: t,
			readConsistency: "latest"
		}, () => {
			if (f) throw new Error("session changed before captured reply persistence");
		});
	} finally {
		p();
	}
	if (!h) return false;
	const g = normalizeMessageTimestampMs(e.ctx.Timestamp);
	const _ = o ? i.parentConversationRef ?? buildConversationRef({
		channel: i.channel,
		accountId: i.accountId,
		kind: i.kind,
		peerId: i.peerId
	}) : void 0;
	const v = {
		text: r,
		timestamp: g,
		idempotencyKey: `conversation-inbound:${i.conversationRef}:${n}`,
		...e.ctx.InputProvenance ? { provenance: e.ctx.InputProvenance } : {},
		transport: {
			channel: i.channel,
			conversationRef: i.conversationRef,
			...s
		},
		sender: i.kind === "group" || i.kind === "channel" ? buildChannelUserTurnSender(e.ctx) : void 0
	};
	const y = await claimPendingConversationTurnReply({
		agentId: c,
		conversationRef: i.conversationRef,
		..._ ? { parentConversationRef: _ } : {},
		sessionId: h.sessionId,
		messageId: n,
		replyToId: a,
		threadId: o,
		text: r,
		timestamp: g
	});
	if (!y) {
		const e = await findConversationTurnDeliveryByReplyTarget(m, {
			conversationRef: i.conversationRef,
			replyToId: a
		}) ?? (_ && _ !== i.conversationRef ? await findConversationTurnDeliveryByReplyTarget(m, {
			conversationRef: _,
			replyToId: a
		}) : void 0);
		if (e?.status === "replied" && e.reply?.messageId === n) return true;
		if (e && e.status !== "replied") await markConversationDeliverySent(m, e.operationId, a);
		return false;
	}
	let b = false;
	try {
		if (h.sessionId !== y.sessionId) throw new Error(`session changed before captured reply persistence: ${t}`);
		const e = preparePersistedUserTurnMessageForTranscriptWrite(buildPersistedUserTurnMessage(v), {
			agentId: c,
			sessionKey: t,
			beforeMessageWrite: runAgentHarnessBeforeMessageWriteHook
		});
		if (!e) throw new Error("captured conversation turn reply was blocked before persistence");
		const n = sanitizeTranscriptMessage(e);
		const r = readPersistedReplyText(n);
		if (!r) throw new Error("captured conversation turn reply has no persistable text");
		await markConversationDeliveryReplied(m, {
			operationId: y.turnId,
			session: {
				sessionKey: t,
				sessionId: y.sessionId,
				lifecycleRevision: h.lifecycleRevision
			},
			reply: {
				...s,
				text: r,
				timestamp: g ?? Date.now()
			}
		}, y.assertCurrent);
		b = true;
		y.assertCurrent();
		const a = `conversation-turn-reply-${y.turnId}`;
		let o = false;
		try {
			o = await appendPreparedTranscriptEvent({
				...m,
				sessionId: h.sessionId,
				sessionKey: t,
				expectedOwner: {
					lifecycleRevision: h.lifecycleRevision,
					activeWriterRunId: h.activeWriterRunId
				}
			}, {
				type: "custom",
				id: a,
				customType: CONVERSATION_TURN_REPLY_CUSTOM_TYPE,
				appendMode: "side",
				timestamp: g ?? Date.now(),
				data: {
					turnId: y.turnId,
					conversationRef: i.conversationRef,
					...s,
					message: n
				}
			}, y.assertCurrent);
		} catch (e) {
			logVerbose(`captured conversation turn reply audit persistence failed: ${String(e)}`);
		}
		if (!o) logVerbose("captured conversation turn reply audit artifact was not persisted");
		y.complete(o ? { transcriptArtifactId: a } : void 0);
		return true;
	} catch (e) {
		y.release();
		logVerbose(`conversation turn reply capture failed: ${String(e)}`);
		return b;
	}
}
/** Consumes a correlated channel reply before it can start a second local agent turn. */
async function capturePendingConversationTurnReply(e) {
	try {
		return await capturePendingConversationTurnReplyUnsafe(e);
	} catch (e) {
		logVerbose(`conversation turn reply capture unavailable: ${String(e)}`);
		return false;
	}
}
//#endregion
//#region src/auto-reply/reply/inbound-dedupe.ts
const DEFAULT_INBOUND_DEDUPE_TTL_MS = 12e5;
const DEFAULT_INBOUND_DEDUPE_MAX = 5e3;
/**
* Keep inbound dedupe shared across bundled chunks so the same provider
* message cannot bypass dedupe by entering through a different chunk copy.
*/
const INBOUND_DEDUPE_CACHE_KEY = Symbol.for("openclaw.inboundDedupeCache");
const INBOUND_DEDUPE_INFLIGHT_KEY = Symbol.for("openclaw.inboundDedupeClaims");
const inboundDedupeCache = resolveGlobalDedupeCache(INBOUND_DEDUPE_CACHE_KEY, {
	ttlMs: DEFAULT_INBOUND_DEDUPE_TTL_MS,
	maxSize: DEFAULT_INBOUND_DEDUPE_MAX
});
const inboundDedupeInFlight = resolveGlobalSingleton(INBOUND_DEDUPE_INFLIGHT_KEY, () => /* @__PURE__ */ new Map());
function resolveInboundDedupeSessionScope(e) {
	const t = resolveCommandTurnTargetSessionKey(e);
	if (t) return t;
	const n = normalizeOptionalString(e.SessionKey) || "";
	const r = parseAgentSessionKey(n);
	return r ? `agent:${r.agentId}` : n;
}
function buildInboundDedupeKey(e) {
	const t = normalizeOptionalLowercaseString(e.OriginatingChannel ?? e.Provider ?? e.Surface) || "";
	const n = normalizeOptionalString(e.MessageSid);
	if (!t || !n) return null;
	const r = e.OriginatingTo ?? e.To ?? e.From ?? e.SessionKey;
	if (!r) return null;
	const i = resolveInboundDedupeSessionScope(e);
	const a = normalizeOptionalString(e.AccountId) ?? "";
	const o = channelRouteDedupeKey({
		channel: t,
		to: r,
		accountId: a,
		threadId: e.MessageThreadId
	});
	return JSON.stringify([
		i,
		o,
		n
	]);
}
function claimInboundDedupe(e, t) {
	const n = buildInboundDedupeKey(e);
	if (!n) return { status: "invalid" };
	const r = inboundDedupeCache.peek(n);
	if (inboundDedupeInFlight.has(n)) return { status: r ? "duplicate" : "inflight" };
	const i = t?.reclaimPendingInput?.() === true;
	if (r) {
		if (!i) return { status: "duplicate" };
		inboundDedupeCache.delete(n);
	}
	const a = {};
	inboundDedupeInFlight.set(n, a);
	return {
		status: "claimed",
		commit: () => {
			if (inboundDedupeInFlight.get(n) === a) {
				inboundDedupeCache.check(n, void 0, a);
				inboundDedupeInFlight.delete(n);
			}
		},
		release: () => {
			if (inboundDedupeInFlight.get(n) === a) inboundDedupeInFlight.delete(n);
			inboundDedupeCache.delete(n, a);
		}
	};
}
function resetInboundDedupe() {
	inboundDedupeCache.clear();
	inboundDedupeInFlight.clear();
}
//#endregion
//#region src/auto-reply/reply/message-received-hooks.ts
/** Emit observation hooks once for an accepted inbound turn, independent of reply dispatch. */
function emitMessageReceivedHooks(e) {
	if (e.ctx.SuppressMessageReceivedHooks === true) return;
	const t = e.buildContext ?? (() => deriveInboundMessageHookContext(e.ctx, { messageId: e.ctx.MessageSidFull ?? e.ctx.MessageSid ?? e.ctx.MessageSidFirst ?? e.ctx.MessageSidLast }));
	if (e.hookRunner?.hasHooks("message_received") === true) {
		const n = t();
		fireAndForgetHook(e.hookRunner.runMessageReceived(toPluginMessageReceivedEvent(n), toPluginMessageContext(n)), "message_received plugin hook failed");
	}
	if (e.sessionKey) {
		const n = t();
		fireAndForgetHook(triggerInternalHook(createInternalHookEvent("message", "received", e.sessionKey, {
			...toInternalMessageReceivedContext(n),
			timestamp: e.timestamp
		})), "message_received internal hook failed");
	}
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.prepare-context.ts
async function prepareDispatchOperationContext(e) {
	const { acpDispatchSessionKey: t, buildMessageReceivedHookContext: n, cfg: r, ctx: i, dispatcher: a, hookRunner: o, isInternalWebchatTurn: s, markIdle: c, params: l, recordAgentDispatchCompleted: u, recordProcessed: d, replyRoute: f, sessionAgentId: p, sessionKey: m, sessionStoreEntry: h } = e;
	const sendBindingNotice = async (t, n, r) => {
		if (M.suppressAutomaticSourceDelivery) return false;
		return await e.deliverBindingPayload(t, n, r);
	};
	const g = e.allowInboundHandlers ? await resolveDispatchConversationBinding(r, i) : null;
	const _ = toPluginConversationBinding(g);
	const v = normalizeOptionalString(g?.targetSessionKey);
	const y = g?.targetKind;
	const persistPluginBindingUserTurn = async () => {
		const t = l.replyOptions?.userTurnTranscriptRecorder;
		if (!t || !v) return;
		const n = resolveSessionAgentId({
			sessionKey: v,
			config: r,
			fallbackAgentId: i.AgentId
		});
		const blockedOwner = (e) => ({
			agentId: n,
			sessionKey: v,
			...e ? { expectedSessionId: e } : {},
			transcriptWriteBlocked: true
		});
		if (t.hasPersisted()) return blockedOwner();
		const assertCurrent = () => {
			e.getPreDispatchAbortSignal()?.throwIfAborted();
			l.replyOptions?.operatorAuthority?.assertCurrent();
		};
		let a;
		for (let e = 0; e < 2; e += 1) {
			const e = await resolveSessionStoreLookup({
				...i,
				CommandTargetSessionKey: void 0,
				SessionKey: v
			}, r, assertCurrent);
			assertCurrent();
			const o = e.entry;
			if (!o || o.sessionId === a?.expectedSessionId) break;
			a = {
				agentId: n,
				expectedSessionId: o.sessionId,
				sessionKey: v
			};
			if (await t.persistApproved({
				target: {
					sessionId: o.sessionId,
					sessionKey: v,
					sessionEntry: o,
					...e.store ? { sessionStore: e.store } : {},
					storePath: e.storePath,
					agentId: n,
					cwd: resolveAgentWorkspaceDir(r, n),
					config: r
				},
				expectedSessionId: o.sessionId,
				retryIfUnpersisted: true
			})) return a;
		}
		t.markBlocked();
		if (a) logVerbose(`plugin-bound user-turn persistence skipped after the target session changed`);
		return blockedOwner(a?.expectedSessionId);
	};
	const b = resolveSendPolicy({
		cfg: r,
		entry: h.entry,
		sessionKey: h.sessionKey ?? m,
		channel: (e.shouldRouteToOriginating ? e.routeReplyChannel : void 0) ?? sessionDeliveryChannel(h.entry) ?? f.channel ?? i.Surface ?? i.Provider ?? void 0,
		chatType: h.entry?.chatType
	});
	const x = normalizeChatType(i.ChatType);
	e.replyOperationRunState.replyCompletion = resolveReplyCompletion(resolveSourceReplyExpectation({
		ctx: i,
		cfg: r,
		scheduledAutomation: l.replyOptions?.scheduledAutomation !== void 0
	}), "empty");
	const { configuredVisibleReplies: S, harnessDefaultVisibleReplies: C } = await resolveVisibleRepliesPolicy({
		cfg: r,
		chatType: x,
		ctx: i,
		entry: h.entry,
		sessionAgentId: p,
		sessionKey: t,
		sessionStore: h.store,
		turnModelOverride: l.replyOptions?.modelOverride
	});
	const w = S ?? C;
	const T = l.replyOptions?.sourceReplyDeliveryMode === "message_tool_only" || i.InboundEventKind === "room_event" && !s || l.replyOptions?.sourceReplyDeliveryMode === void 0 && !isExplicitCommandTurnContext(i, r) && (S === "message_tool" || !s && w === "message_tool");
	const E = resolveGroupSessionKey(i);
	const D = resolveOriginMessageProvider({
		originatingChannel: i.OriginatingChannel,
		provider: i.Provider ?? i.Surface
	});
	const O = resolveGroupToolPolicy({
		config: r,
		sessionKey: t,
		messageProvider: D,
		groupId: E?.id,
		groupChannel: normalizeOptionalString(i.GroupChannel) ?? normalizeOptionalString(i.GroupSubject),
		groupSpace: normalizeOptionalString(i.GroupSpace),
		accountId: i.AccountId,
		senderId: normalizeOptionalString(i.SenderId),
		senderName: normalizeOptionalString(i.SenderName),
		senderUsername: normalizeOptionalString(i.SenderUsername),
		senderE164: normalizeOptionalString(i.SenderE164)
	});
	const k = await withPreparedSessionCapabilityRead(() => resolveReplyMessageToolAvailability({
		cfg: r,
		sessionAgentId: p,
		sessionKey: t,
		groupPolicy: O,
		prefersMessageToolDelivery: T
	}));
	const A = w === "message_tool" ? await withPreparedSessionCapabilityRead(() => resolveStableMessageToolAvailability({
		cfg: r,
		ctx: i,
		sessionEntry: h.entry,
		sessionAgentId: p,
		sessionKey: t
	})) : void 0;
	const j = {
		cfg: r,
		ctx: i,
		scheduledAutomation: l.replyOptions?.scheduledAutomation !== void 0,
		strictMessageToolOnly: i.InboundEventKind === "room_event" && !s,
		sendPolicy: b,
		suppressAcpChildUserDelivery: e.suppressAcpChildUserDelivery,
		explicitSuppressTyping: l.replyOptions?.suppressTyping === true,
		shouldSuppressTyping: e.shouldSuppressTyping,
		messageToolAvailable: k,
		sessionStableMessageToolAvailable: A,
		requested: l.replyOptions?.sourceReplyDeliveryMode
	};
	let M = resolveSourceReplyVisibilityPolicy({
		...j,
		defaultVisibleReplies: C
	});
	const N = C === "message_tool" ? "automatic" : "message_tool";
	const P = {
		sourceReplyDeliveryModeOrigin: resolveSourceReplyVisibilityPolicy({
			...j,
			defaultVisibleReplies: N
		}).sourceReplyDeliveryMode === M.sourceReplyDeliveryMode ? "stable_policy" : "runtime_default",
		onSourceReplyDeliveryModeResolved: (t) => {
			const n = M.sessionStableSourceReplyDeliveryMode;
			M = resolveSourceReplyVisibilityPolicy({
				...j,
				requested: t
			});
			M.sessionStableSourceReplyDeliveryMode = n;
			Object.assign(e, M, { sourceReplyPolicy: M });
		}
	};
	Object.assign(M, P);
	const F = l.replyOptions?.reasoningPayloadsEnabled === true;
	const I = l.replyOptions?.commentaryPayloadsEnabled === true;
	const attachSourceReplyDeliveryMode = (e) => M.sourceReplyDeliveryMode === "message_tool_only" || M.sendPolicyDenied ? {
		...e,
		...M.sourceReplyDeliveryMode === "message_tool_only" ? { sourceReplyDeliveryMode: M.sourceReplyDeliveryMode } : {},
		...M.sendPolicyDenied ? { sendPolicyDenied: true } : {}
	} : e;
	const baseDispatchResult = (e = false) => ({
		queuedFinal: e,
		counts: a.getQueuedCounts()
	});
	const L = isExplicitCommandTurnContext(i, r);
	const R = L && isActiveRunSafeCommandTurn({
		commandTurn: resolveCommandTurnContext(i),
		cfg: r,
		provider: i.Provider ?? i.Surface
	});
	const z = (x === "group" || x === "channel") && isUnauthorizedTextSlashCommand(i);
	const B = !M.suppressAutomaticSourceDelivery || L || i.InboundEventKind !== "room_event" && !z;
	const skipDuplicate = () => {
		d("skipped", { reason: "duplicate" });
		return {
			status: "complete",
			result: attachSourceReplyDeliveryMode(baseDispatchResult())
		};
	};
	const V = readChannelSourceTurnId(i) ?? (shouldMintChannelSourceTurnId(i.Provider ?? i.Surface) ? buildChannelSourceTurnId({
		provider: resolveOriginMessageProvider({
			originatingChannel: f.channel,
			provider: i.Provider ?? i.Surface
		}),
		accountId: f.accountId,
		conversationId: f.to,
		messageId: normalizeOptionalString(i.MessageSidFull) ?? normalizeOptionalString(i.MessageSid)
	}) : void 0);
	setChannelSourceTurnId(i, V);
	const H = normalizeOptionalString(i.MessageSid);
	const U = l.replyOptions?.userTurnTranscriptRecorder;
	let W;
	if (U?.getPendingInputMessage?.() && !U.hasPersisted() && H && h.sessionKey && h.entry?.sessionId) {
		const e = {
			agentId: h.agentId ?? p,
			storePath: h.storePath,
			sessionKey: h.sessionKey,
			sessionId: h.entry.sessionId
		};
		W = await prepareSessionPendingInputDedupeRecovery(e, H);
	}
	const claimInput = () => {
		const e = W;
		return claimInboundDedupe(i, { reclaimPendingInput: e ? () => !U.hasPersisted() && e() : void 0 });
	};
	const G = W && U?.withPendingInputCurrent ? await U.withPendingInputCurrent(claimInput) : claimInput();
	const K = l.replyOptions?.turnAdoptionLifecycle;
	if (G.status === "inflight" && K?.admission === "exclusive") throw new InboundDedupePendingError();
	if (G.status === "duplicate" || G.status === "inflight") return skipDuplicate();
	const commitInboundDedupeIfClaimed = () => {
		const t = e.replyOperationRunState.admission;
		if (K?.admission === "exclusive" && t?.status === "accepted" && t.mode === "followup" && !e.turnAdoptionState?.adopted && !e.inboundDedupeReplayUnsafe) return;
		G.commit?.();
	};
	const releaseInboundDedupeIfClaimed = () => G.release?.();
	if (K && G.status === "claimed") {
		const t = K.onAdopted;
		K.onAdopted = async () => {
			await t();
			G.commit();
		};
		const n = K.onSettled;
		K.onSettled = () => {
			G.commit();
			return n?.();
		};
		const r = K.onAbandoned;
		K.onAbandoned = () => {
			if (!e.inboundDedupeReplayUnsafe && !e.turnAdoptionState?.adopted) G.release();
			return r?.();
		};
	}
	const finishReplyOperationBusyDispatch = (t) => {
		e.releasePreDispatchLifecycleAdmission(() => waitForReplyDispatcherSettlement(a));
		if (t?.recordAgentDispatchCompleted) u("completed", { reason: "reply-operation-active" });
		d("skipped", { reason: "reply-operation-active" });
		c("message_completed");
		if (t?.dedupeDisposition === "release") releaseInboundDedupeIfClaimed();
		else commitInboundDedupeIfClaimed();
		return attachSourceReplyDeliveryMode({
			...baseDispatchResult(),
			...t?.sessionMetadataChanges ? { sessionMetadataChanges: t.sessionMetadataChanges } : {}
		});
	};
	const finishReplyOperationAbortedDispatch = () => {
		const t = e.getDispatchReplyOperation();
		recordReplyOperationAgentTurn([e.replyOperationRunState], t);
		const n = isReplyOperationStalledBeforeOutput(t) && e.replyOperationRunState.continueStalledTurn?.() !== true ? a.sendFinalReply({
			text: resolveStalledTurnNoticeText(t),
			isError: true
		}) : false;
		if (e.turnAdoptionState && !e.turnAdoptionState.adopted && !e.inboundDedupeReplayUnsafe) releaseInboundDedupeIfClaimed();
		else commitInboundDedupeIfClaimed();
		d("skipped", { reason: "reply_operation_aborted" });
		c("message_completed");
		e.completeDispatchReplyOperation();
		return attachSourceReplyDeliveryMode({
			...baseDispatchResult(n),
			...e.turnLedger.hasObservedDelivery() ? { observedReplyDelivery: true } : {}
		});
	};
	const q = {};
	const emitMessageReceivedHooks$1 = () => {
		if (!e.allowInboundHandlers) return;
		emitMessageReceivedHooks({
			ctx: i,
			hookRunner: o,
			sessionKey: m,
			timestamp: e.timestamp,
			buildContext: n
		});
	};
	e.markProcessing();
	if (e.allowInboundHandlers && await capturePendingConversationTurnReply({
		cfg: r,
		ctx: i
	})) {
		emitMessageReceivedHooks$1();
		commitInboundDedupeIfClaimed();
		d("completed", { reason: "conversation-turn-reply" });
		c("message_completed");
		return {
			status: "complete",
			result: attachSourceReplyDeliveryMode({
				...baseDispatchResult(),
				observedReplyDelivery: true
			})
		};
	}
	return {
		status: "ready",
		state: Object.assign(e, {
			sendBindingNotice,
			pluginOwnedBinding: _,
			pluginBindingSessionKey: v,
			pluginBindingTargetKind: y,
			persistPluginBindingUserTurn,
			sendPolicy: b,
			chatType: x,
			sourceReplyPolicy: M,
			sourceReplyDeliveryRuntimeOptions: P,
			...M,
			reasoningPayloadsEnabled: F,
			commentaryPayloadsEnabled: I,
			attachSourceReplyDeliveryMode,
			explicitCommandTurnCtx: L,
			activeRunSafeCommandTurn: R,
			shouldDeliverPluginBindingReply: B,
			inboundDedupeClaim: G,
			commitInboundDedupeIfClaimed,
			finishReplyOperationBusyDispatch,
			finishReplyOperationAbortedDispatch,
			emitMessageReceivedHooks: emitMessageReceivedHooks$1,
			bindingState: q
		})
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.prepare-delivery.ts
function resolveReplyPolicyConversationType(e) {
	const t = e.SessionKey;
	const n = resolveCommandTurnTargetSessionKey(e);
	if (n && n !== t) return;
	const r = normalizeChatType(e.ChatType);
	return r === "channel" ? "group" : r;
}
async function prepareDispatchDelivery(e) {
	const { cfg: t, ctx: n, groupId: r, markInboundDedupeReplayUnsafe: i, replyRoute: a, sessionStoreEntry: o, turnLedger: s } = e;
	const assertPreparationCurrent = () => {
		e.getPreDispatchAbortSignal()?.throwIfAborted();
		e.params.replyOptions?.operatorAuthority?.assertCurrent();
	};
	const c = o.sessionKey ? await withAcpSessionEntryRead({
		cfg: t,
		agentId: o.agentId,
		sessionKey: o.sessionKey,
		assertCurrent: assertPreparationCurrent
	}, (e) => isParentOwnedBackgroundAcpSession(e?.entry ? {
		...e.entry,
		acp: e.acp
	} : void 0), { includeMetadata: (e) => Boolean(normalizeOptionalString(e?.spawnedBy) || normalizeOptionalString(e?.parentSessionKey)) }) : false;
	assertPreparationCurrent();
	const l = n.ExplicitDeliverRoute === true || a.inheritedExternalRoute === true;
	const resolveRouting = (e) => {
		const t = normalizeMessageChannel(a.channel);
		const r = normalizeMessageChannel(n.Provider);
		const i = normalizeMessageChannel(n.Surface);
		const o = r ?? i;
		const s = o === "webchat" && (i === "webchat" || !i) && !l;
		const u = Boolean(!c && !s && e(t) && a.to && t !== o);
		return {
			originatingChannel: t,
			currentSurface: o,
			isInternalWebchatTurn: s,
			shouldRouteToOriginating: u,
			shouldSuppressTyping: c || u || t === "webchat"
		};
	};
	const { currentSurface: u, isInternalWebchatTurn: d, shouldRouteToOriginating: f } = resolveRouting(Boolean);
	const p = f ? await loadRouteReplyRuntime() : void 0;
	const { originatingChannel: m, currentSurface: h, shouldRouteToOriginating: g, shouldSuppressTyping: _ } = resolveRouting(p?.isRoutableChannel ?? (() => false));
	const v = a.to;
	const y = Boolean(!c && !d && m && v && m === u);
	const b = g ? m ?? h : h;
	const { preparedTtsPreferences: x, getDispatchReplyOperation: S } = e;
	const maybeApplyTtsWithFinalizationLease = async (n, r) => {
		const i = {
			cfg: t,
			channel: b,
			ttsAuto: e.sessionTtsAuto,
			agentId: e.sessionAgentId,
			accountId: a.accountId
		};
		const o = S();
		const s = o ? beginReplyOperationFinalizationWork(o, RUN_STALE_TAKEOVER_MS) : void 0;
		try {
			const t = await maybeApplyTtsToReplyPayload({
				...i,
				payload: n,
				kind: r,
				preparedTtsPreferences: x,
				inboundAudio: e.inboundAudio || e.getDispatchReplyOperation()?.acceptedSteeredInboundAudio === true
			});
			o?.watchdog.progress("finalization", "reply:tts_prepared");
			return t;
		} finally {
			s?.();
		}
	};
	const C = m ? resolveReplyDeliveryAccountId(t, m, a.accountId) : void 0;
	let w;
	const normalizeReplyMediaPayload = async (i) => {
		if (d || !resolveSendableOutboundReplyParts(i).hasMedia) return i;
		if (!w) {
			const { createReplyMediaPathNormalizer: i } = await loadReplyMediaPathsRuntime();
			w = i({
				cfg: t,
				agentId: e.sessionAgentId,
				sessionKey: e.acpDispatchSessionKey,
				workspaceDir: e.workspaceDir,
				messageProvider: b,
				accountId: C,
				groupId: r,
				groupChannel: n.GroupChannel,
				groupSpace: n.GroupSpace,
				requesterSenderId: n.SenderId,
				requesterSenderName: n.SenderName,
				requesterSenderUsername: n.SenderUsername,
				requesterSenderE164: n.SenderE164
			});
		}
		return await w(i);
	};
	const routeReplyOperationToOriginating = async (o, c) => {
		const l = o.kind === "prepared" ? o.plan.payload : o.payload;
		const u = c?.deliveryIntentId !== void 0 && y;
		const d = p ?? (u ? await loadRouteReplyRuntime() : void 0);
		if (!g && !u || !m || !v || !d) {
			if (c?.deliveryIntentId) throw new Error("durable block reply route unavailable");
			return null;
		}
		i();
		const f = c?.sessionKey ?? (n.CommandSource === "native" ? resolveCommandTurnTargetSessionKey(n) ?? n.SessionKey : n.SessionKey);
		const h = {
			channel: m,
			to: v,
			agentId: e.sessionAgentId,
			sessionKey: f,
			policySessionKey: c?.sessionKey ?? resolveCommandTurnTargetSessionKey(n) ?? n.SessionKey,
			policyConversationType: resolveReplyPolicyConversationType(n),
			accountId: C,
			requesterSenderId: n.SenderId,
			requesterSenderName: n.SenderName,
			requesterSenderUsername: n.SenderUsername,
			requesterSenderE164: n.SenderE164,
			threadId: e.routeReplyThreadId,
			replyDelivery: createReplyDeliveryContext(resolveReplyToMode(t, m, C, a.chatType), a.chatType),
			cfg: t,
			abortSignal: c?.abortSignal,
			mirror: c?.mirror,
			isGroup: e.isGroup,
			groupId: r,
			replyKind: c?.kind ?? "final",
			runId: e.params.replyOptions?.runId,
			responsePrefixContext: c?.responsePrefixContext,
			deliveryIntentId: c?.deliveryIntentId
		};
		const _ = o.kind === "prepared" ? await d.routePreparedReply({
			...h,
			plan: o.plan
		}) : await d.routeReply({
			...h,
			payload: l
		});
		s.recordRoutedDelivery(c?.kind ?? "final", l, _);
		if (_.delivered && !_.ambiguous) e.getDispatchReplyOperation()?.watchdog.progress("finalization", "reply:routed_delivery");
		return _;
	};
	const routeReplyToOriginating = (e, t) => routeReplyOperationToOriginating({
		kind: "raw",
		payload: e
	}, t);
	const isRoutedReplyDelivered = (e) => e.delivered && e.ambiguous !== true;
	const sendReplyOperationAsync = async (t, n, r = "tool", i) => {
		const a = t.kind === "prepared" ? t.plan.payload : t.payload;
		if (!p && !i) return null;
		const o = n ?? e.getDispatchAbortSignal();
		if (o?.aborted) return null;
		const s = await routeReplyOperationToOriginating(t, {
			abortSignal: o,
			mirror: false,
			kind: r,
			deliveryIntentId: i
		});
		if (s && !s.ok) {
			logVerbose(`dispatch-from-config: route-reply failed: ${s.error ?? "unknown error"}`);
			if (i && s.queueCustody !== "held") throw new Error(s.error ?? "durable block reply delivery failed", { cause: s.cause });
		}
		if (hasAskUserPayload(a) && !o?.aborted && !s?.delivered) throw new Error("ask_user prompt delivery failed");
		return s;
	};
	const sendPayloadAsync = (e) => sendReplyOperationAsync({
		kind: "raw",
		payload: e
	});
	const deliverBindingPayload = async (e, t, n) => {
		const r = setReplyPayloadMetadata(copyReplyPayloadMetadata(e, { ...e }), { sourceReplyTranscriptMirror: n ? {
			sessionKey: n.sessionKey,
			agentId: n.agentId,
			...n.expectedSessionId ? { expectedSessionId: n.expectedSessionId } : {},
			...n.transcriptWriteBlocked ? { transcriptWriteBlocked: true } : {}
		} : void 0 });
		const a = await routeReplyToOriginating(r, {
			kind: t === "terminal" ? "final" : "tool",
			sessionKey: n?.sessionKey
		});
		if (a) {
			if (!a.ok) logVerbose(`dispatch-from-config: route-reply (plugin binding notice) failed: ${a.error ?? "unknown error"}`);
			return a.delivered || a.suppressed === true;
		}
		i();
		return s.sendQueued(t === "additive" ? "tool" : "final", r).queued;
	};
	return Object.assign(e, {
		suppressAcpChildUserDelivery: c,
		normalizedCurrentSurface: u,
		isInternalWebchatTurn: d,
		routeReplyChannel: m,
		canRouteDurableBlockReply: y,
		shouldRouteToOriginating: g,
		shouldSuppressTyping: _,
		routeReplyTo: v,
		deliveryChannel: b,
		maybeApplyTtsWithFinalizationLease,
		replyContextAccountId: C,
		normalizeReplyMediaPayload,
		routeReplyToOriginating,
		isRoutedReplyDelivered,
		sendPayloadAsync,
		sendReplyOperationAsync,
		deliverBindingPayload
	});
}
//#endregion
//#region src/channels/plugins/exec-approval-local.ts
async function shouldSuppressLocalExecApprovalPromptAsync(e) {
	const t = e.channel ? normalizeAnyChannelId(e.channel) : null;
	if (!t) return false;
	const n = getChannelPlugin(t)?.outbound;
	return await (n?.shouldSuppressLocalPayloadPromptAsync ?? n?.shouldSuppressLocalPayloadPrompt)?.({
		cfg: e.cfg,
		accountId: e.accountId,
		payload: e.payload,
		hint: {
			kind: "approval-pending",
			approvalKind: "exec",
			nativeRouteActive: hasActiveNativeApprovalRoute(getGatewayNativeApprovalRuntime()?.routeCoordinator, {
				channel: t,
				accountId: e.accountId,
				approvalKind: "exec"
			})
		}
	}) ?? false;
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.prepare-execution.ts
async function prepareDispatchExecution(e) {
	const { cfg: t, ctx: n, isDispatchOperationAborted: r, markInboundDedupeReplayUnsafe: i, markProgress: a, noteCommentaryProgress: o, params: s, sendPayloadAsync: c, sessionKey: l, shouldEmitVerboseProgressAsync: u, shouldRouteToOriginating: d, shouldSendToolSummariesAsync: f, shouldSuppressProgressDelivery: p, turnLedger: m } = e;
	if (e.suppressDelivery) logVerbose(`Delivery suppressed by ${e.deliverySuppressionReason} for session ${e.sessionStoreEntry.sessionKey ?? l ?? "unknown"} — agent will still process the message`);
	let h = false;
	const sendPlanUpdate = async (t) => {
		if (await p() || !await f() || h || r()) return;
		h = true;
		const n = t.explanation?.replace(/\s+/g, " ").trim();
		const a = formatPlanChecklistLines(t.steps ?? [], {
			maxLines: t.steps?.length ?? 0,
			maxLineChars: 120
		});
		const o = {
			text: a.length > 0 ? a.join("\n") : t.explanationFormat === "plain" ? "Progress updated" : n || "Planning next steps.",
			isStatusNotice: true
		};
		e.assertProgressCurrent();
		if (d) {
			await c(o);
			return;
		}
		i();
		m.sendQueued("tool", o);
	};
	const g = {
		accumulatedBlockText: "",
		accumulatedBlockTtsText: "",
		acceptedReplyPayload: false,
		channelTransformSuppressed: false,
		pendingDirectBlockReplyDelivery: Promise.resolve(),
		progressCallbackStartTail: Promise.resolve()
	};
	const _ = shouldCleanTtsDirectiveText({
		cfg: t,
		preparedTtsPreferences: e.preparedTtsPreferences,
		ttsAuto: e.sessionTtsAuto,
		agentId: e.sessionAgentId,
		channelId: e.deliveryChannel,
		accountId: e.replyRoute.accountId
	}) ? createTtsDirectiveTextStreamCleaner() : void 0;
	const resolveToolDeliveryPayload = async (e) => {
		if (await shouldSuppressLocalExecApprovalPromptAsync({
			channel: normalizeMessageChannel(n.Surface ?? n.Provider),
			cfg: t,
			accountId: n.AccountId,
			payload: e
		})) return null;
		if (await f() || hasExecApprovalPayload(e) || hasExecApprovalUnavailablePayload(e) || hasAskUserPayload(e)) return e;
		if (!resolveSendableOutboundReplyParts(e).hasMedia) return null;
		return {
			...e,
			text: void 0
		};
	};
	const v = resolveRunTypingPolicy({
		requestedPolicy: s.replyOptions?.typingPolicy,
		suppressTyping: e.sourceReplyPolicy.suppressTyping,
		originatingChannel: e.routeReplyChannel,
		systemEvent: d
	});
	const y = s.replyOptions?.onToolResult;
	const b = s.replyOptions?.onPlanUpdate;
	const x = s.replyOptions?.onApprovalEvent;
	const S = s.replyOptions?.onPatchSummary;
	const C = s.replyOptions?.allowProgressCallbacksWhenSourceDeliverySuppressed === true;
	const waitForPendingDirectBlockReplyDelivery = (e) => waitForReplyDispatcherIdle({ waitForIdle: () => g.pendingDirectBlockReplyDelivery }, e);
	const shouldForwardProgressCallback = async (t) => {
		if (e.sendPolicyDenied) return false;
		if (s.replyOptions?.progressRequiresReply === true && !isRequiredReplyExpectation(e.replyOperationRunState.replyCompletion?.expectation)) return false;
		if (t?.requiresToolSummaryVisibility === true && !await f() && s.replyOptions?.suppressDefaultToolProgressMessages !== true && t.allowWhenToolSummariesHidden !== true) return false;
		return !e.suppressAutomaticSourceDelivery || C && t?.forwardWhenSourceDeliverySuppressed === true;
	};
	const w = s.replyOptions?.preserveProgressCallbackStartOrder === true;
	const wrapProgressCallback = (t, n) => {
		if (!t) return;
		return async (...i) => {
			const o = w ? createDeferredCore() : void 0;
			if (o) {
				const e = g.progressCallbackStartTail;
				g.progressCallbackStartTail = o.promise;
				await e;
			}
			try {
				if (r()) return;
				e.getDispatchReplyOperation()?.recordActivity();
				a();
				if (n?.waitForDirectBlockReplyDelivery) {
					await waitForPendingDirectBlockReplyDelivery(e.getDispatchAbortOperation()?.abortSignal);
					if (r()) return;
				}
				if (await shouldForwardProgressCallback(n) && !r()) {
					if (!w || n?.onForward) await n?.onForward?.(...i);
					if (r()) return;
					e.assertProgressCurrent();
					const a = t(...i);
					o?.resolve();
					const s = await a;
					if (s === false) return s;
					e.assertProgressCurrent();
					await n?.onVisible?.(...i);
				}
				return;
			} finally {
				o?.resolve();
			}
		};
	};
	const T = s.replyOptions?.onReasoningStream;
	const E = T ? wrapProgressCallback((e) => {
		const t = sanitizeUserFacingText(e.text, {
			conversationContext: n.BodyForAgent ?? n.Body,
			streaming: true
		});
		const r = {
			...e,
			text: t
		};
		if (!t.trim() && !resolveSendableOutboundReplyParts(r).hasMedia) return false;
		return T(r);
	}) : void 0;
	const D = await u();
	e.assertProgressCurrent();
	const resolveVerboseProgressVisibility = () => D && e.shouldSendToolSummaries() && !e.shouldSuppressProgressDeliverySync();
	const { commentaryPayloadsEnabled: O, draftOwnsCommentaryProgress: k } = await resolveTurnCommentaryProgressOwner({
		commentaryPayloadsEnabled: e.commentaryPayloadsEnabled,
		options: s.replyOptions,
		resolveVerboseProgressVisibility,
		resolveVerboseProgressVisibilityAsync: async () => {
			const t = D && await e.shouldSendToolSummariesAsync() && !await e.shouldSuppressProgressDelivery();
			e.assertProgressCurrent();
			return t;
		}
	});
	e.assertProgressCurrent();
	const A = D && !k;
	const j = Boolean(s.replyOptions?.onItemEvent);
	const M = C && !e.sendPolicyDenied && j;
	const shouldDeliverDurableCommentaryProgress = (e) => A && e.kind === "preamble" && e.suppressDurableProgress !== true;
	const N = wrapProgressCallback(s.replyOptions?.onItemEvent, {
		forwardWhenSourceDeliverySuppressed: true,
		requiresToolSummaryVisibility: true,
		waitForDirectBlockReplyDelivery: true,
		onForward: (e) => w && shouldDeliverDurableCommentaryProgress(e) ? o(e) : void 0
	});
	const P = wrapProgressCallback(s.replyOptions?.onItemEvent, {
		forwardWhenSourceDeliverySuppressed: true,
		waitForDirectBlockReplyDelivery: true
	});
	const F = A || j ? async (e) => {
		if (r()) return;
		if (!N && A) a();
		if ((!N || !w) && shouldDeliverDurableCommentaryProgress(e)) await o(e);
		return e.kind === "model-wait" ? await P?.(e) : await N?.(e);
	} : void 0;
	const I = s.replyResolver ?? (await e.traceReplyPhase("reply.load_reply_resolver", () => loadGetReplyFromConfigRuntime())).getReplyFromConfig;
	const L = e.preparedReplyDispatchRuntime?.config ?? t;
	const R = withFullRuntimeReplyConfig(s.configOverride ? applyMergePatch(L, s.configOverride) : L);
	e.recordAgentDispatchStarted();
	return Object.assign(e, {
		sendPlanUpdate,
		cleanBlockTtsDirectiveText: _,
		resolveToolDeliveryPayload,
		typing: v,
		onToolResultFromReplyOptions: y,
		onPlanUpdateFromReplyOptions: b,
		onApprovalEventFromReplyOptions: x,
		onPatchSummaryFromReplyOptions: S,
		waitForPendingDirectBlockReplyDelivery,
		shouldForwardProgressCallback,
		preserveProgressCallbackStartOrder: w,
		wrapProgressCallback,
		onReasoningStream: E,
		deliverStandaloneCommentaryProgress: A,
		canForwardSuppressedSourceItemEvents: M,
		onItemEvent: F,
		commentaryPayloadsEnabled: O,
		replyResolver: I,
		replyConfig: R,
		progressState: g
	});
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.plugin-binding.ts
function shouldBypassPluginOwnedBindingForCommand(e, t, n) {
	if (e.CommandAuthorized !== void 0 && typeof e.CommandAuthorized !== "boolean") return false;
	const r = e.CommandTurn;
	if ((r.kind === "native" || r.kind === "text-slash") && !r.authorized) return false;
	if (isNativeCommandTurn(r) && r.authorized) return true;
	if (!(r.kind === "text-slash" && r.authorized || r.kind === "normal" && typeof e.CommandAuthorized === "boolean" && e.CommandAuthorized) || !shouldHandleTextCommands({
		cfg: t,
		surface: e.Surface ?? e.Provider ?? "",
		commandSource: e.CommandSource
	})) return false;
	const i = normalizeCommandBody(r.body ?? resolveCommandContextText(e), { botUsername: e.BotUsername });
	if (!i.startsWith("/")) return false;
	if (n?.[PLUGIN_COMMAND_DISPATCH]) return true;
	const a = resolveCommandChannel(e);
	const o = matchPluginCommandInvocation(createPluginCommandRuntime(), i, { channel: a });
	if (o) {
		if (n) Object.assign(n, { [PLUGIN_COMMAND_DISPATCH]: o.dispatch });
		return true;
	}
	if (!isExplicitCommandTurnContext(e, t)) return false;
	if (resolveTextCommand(i)) return true;
	const s = normalizeOptionalString(e.Provider ?? e.Surface);
	return Boolean(r.commandName && findCommandByNativeName(r.commandName, s, { includeBundledChannelFallback: true }));
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.prepare-operation.ts
async function prepareDispatchOperation(e) {
	const { attachSourceReplyDeliveryMode: t, cfg: n, chatType: r, commitInboundDedupeIfClaimed: i, completeDispatchReplyOperation: a, ctx: o, deliverySuppressionReason: s, dispatcher: c, emitMessageReceivedHooks: l, finishReplyOperationAbortedDispatch: u, hookRunner: d, isPreDispatchOperationAborted: f, markIdle: p, params: m, persistPluginBindingUserTurn: h, pluginOwnedBinding: g, recordProcessed: _, sendBindingNotice: v, sessionAgentId: y, sessionKey: b, sessionStoreEntry: x, suppressDelivery: S, turnLedger: C } = e;
	const w = readReplySourceInput(m.replyOptions);
	const assertRequestCurrent = () => {
		m.replyOptions?.assertChannelAuthority?.();
		const e = w?.sourceAdapter?.authority;
		e?.assertCurrent();
		if (m.replyOptions?.operatorAuthority !== e) m.replyOptions?.operatorAuthority?.assertCurrent();
		m.replyOptions?.internalEventExecution?.assertCurrent?.();
		if (f() || w?.retirementRequested) throw new DispatchReplyOperationAbortedError();
	};
	const T = e.operationSessionStoreEntry.entry;
	const E = e.dispatchOperationSessionKey;
	if (isNativeCommandTurn(o.CommandTurn) && T?.archivedAt !== void 0 && E) {
		assertRequestCurrent();
		const n = await restoreArchivedDispatchSession({
			assertCurrent: assertRequestCurrent,
			ctx: o,
			entry: T,
			hasPluginOwnedBinding: Boolean(g),
			placementContext: m.sessionWorkerPlacementContext,
			sessionKey: E,
			storePath: e.operationSessionStoreEntry.storePath
		});
		assertRequestCurrent();
		const r = resolveSessionWorkStartError(E, n, { expectedSessionId: T.sessionId });
		if (r) {
			const n = {
				text: r,
				isError: true
			};
			markCommandReplyForDelivery(n);
			const a = !e.sendPolicyDenied && c.sendFinalReply(n);
			_("skipped", { reason: "session-directive-rejected" });
			p("message_completed");
			i();
			return {
				status: "complete",
				result: t({
					queuedFinal: a,
					counts: c.getQueuedCounts(),
					...e.sendPolicyDenied ? { deliberateSilentTerminalReply: true } : {}
				})
			};
		}
		e.operationSessionStoreEntry.entry = n;
	}
	const D = m.fastAbortResolver ? null : await loadAbortRuntime();
	const O = m.fastAbortResolver ?? D?.tryFastAbortFromMessage;
	const k = m.formatAbortReplyTextResolver ?? D?.formatAbortReplyText;
	if (!O || !k) throw new Error("abort runtime unavailable");
	const finishFastCommand = async (r) => {
		if (g) await getSessionBindingService().touchAsync(g.bindingId, void 0, g);
		l();
		let u = false;
		let d = 0;
		if (!S && r.payload) {
			const t = resolveSessionModelRef(n, x.entry, y);
			const i = {
				...t,
				thinkLevel: x.entry?.thinkingLevel
			};
			const a = {
				identityName: normalizeOptionalString(resolveAgentIdentity(n, y)?.name),
				provider: t.provider,
				model: extractShortModelName(t.model),
				modelFull: `${t.provider}/${t.model}`,
				thinkingLevel: i.thinkLevel ?? "off"
			};
			const s = scopeCommandTranscriptId(normalizeOptionalString(e.messageIdForHook), e.hookState.inboundClaimContext);
			const l = b && s ? {
				sessionKey: b,
				agentId: y,
				expectedSessionId: x.entry?.sessionId,
				commandText: o.commandText,
				commandId: s,
				text: r.payload.text,
				preferText: true,
				idempotencyKey: `${r.logKind}:${s}`
			} : void 0;
			const f = await e.routeReplyToOriginating(r.payload, {
				responsePrefixContext: a,
				...l ? { mirror: false } : {}
			});
			if (f) {
				u = f.ok;
				if (e.isRoutedReplyDelivered(f)) {
					d += 1;
					await mirrorDeliveredReplyToTranscript({
						metadata: l,
						cfg: n
					});
				}
				if (!f.ok) logVerbose(`dispatch-from-config: route-reply (${r.logKind}) failed: ${f.error ?? "unknown error"}`);
			} else {
				e.markInboundDedupeReplayUnsafe();
				m.replyOptions?.onModelSelected?.(i);
				u = sendReplyWithTranscriptMirror({
					dispatcher: c,
					cfg: n,
					metadata: l,
					payload: r.payload,
					send: (e) => C.sendQueued("final", e)
				}).queued;
			}
		} else if (S) logVerbose(`dispatch-from-config: ${r.logKind} reply suppressed by ${s} (session=${b ?? "unknown"})`);
		const f = c.getQueuedCounts();
		f.final += d;
		_("completed", { reason: r.reason });
		p("message_completed");
		i();
		a();
		return {
			status: "complete",
			result: t({
				queuedFinal: u,
				counts: f
			})
		};
	};
	const A = createDeferredCore();
	const j = await O({
		ctx: o,
		cfg: n,
		isCommandTargetCurrent: m.replyOptions?.isCommandTargetCurrent,
		onAbortRequest: () => e.trackDispatchLifecycleWork(A.promise, "delivery")
	}).catch((e) => {
		A.resolve(void 0);
		throw e;
	});
	if (j.handled) {
		if (j.aborted || (j.stoppedSubagents ?? 0) > 0) e.markInboundDedupeReplayUnsafe();
		return await finishFastCommand({
			payload: { text: k(j.stoppedSubagents, j.rejectionReason, j.failedSubagents, j.localModelMayStillBeFinishing) },
			reason: "fast_abort",
			logKind: "fast_abort"
		}).finally(() => {
			A.resolve(waitForReplyBarrierSettlement(waitForReplyDispatcherSettlement(c), c.resolveFollowupAdmissionBarrierTimeoutPolicy?.()));
		});
	}
	A.resolve(void 0);
	if (/^\s*\/approve(?:@[^\s]+)?(?:\s|$)/i.test(o.commandText)) {
		const e = await (await loadFastApproveRuntime()).tryFastApproveFromMessage({
			ctx: o,
			cfg: n,
			agentId: y,
			sessionKey: b
		});
		if (e.handled) return await finishFastCommand({
			...e.reply ? { payload: e.reply } : {},
			reason: "before_dispatch_handled",
			logKind: "fast_approve"
		});
	}
	const assertCurrentBindingRoute = async () => {
		if (o.InternalTurnSource === void 0 && readConversationBindingRouteFacts(o)) {
			await assertPreparedConversationBindingRouteCurrent(o);
			if (f()) throw new DispatchReplyOperationAbortedError();
		}
	};
	await assertCurrentBindingRoute();
	if (g) await runWithDispatchAbortSignal(e.getPreDispatchAbortSignal(), async () => {
		assertRequestCurrent();
		await getSessionBindingService().touchAsync(g.bindingId, void 0, g);
		const t = await getSessionBindingService().resolveByConversationAsync(g);
		if (t?.bindingId !== g.bindingId || t.boundAt !== g.boundAt || t.targetSessionKey !== e.pluginBindingSessionKey || t.targetKind !== e.pluginBindingTargetKind || t.metadata?.pluginBindingOwner !== "plugin" || t.metadata?.pluginId !== g.pluginId || t.metadata?.pluginRoot !== g.pluginRoot) throw new DispatchSessionRefreshRequiredError(/* @__PURE__ */ new Error("conversation binding changed while recording activity"));
	}, e.trackDispatchLifecycleWork);
	const M = await e.traceReplyPhase("reply.admit_pre_dispatch", () => e.ensureDispatchReplyOperation("pre_dispatch", Boolean(g)));
	if (M.status === "aborted") return {
		status: "complete",
		result: u()
	};
	if (M.status === "busy") return {
		status: "complete",
		result: e.finishReplyOperationBusyDispatch({ dedupeDisposition: "release" })
	};
	const finishPluginBindingDispatch = async (n) => {
		if (await C.settleQueued(e.getPreDispatchAbortSignal()) === "aborted" || f()) return {
			status: "complete",
			result: u()
		};
		p(n === "handled" ? "plugin_binding_dispatch" : `plugin_binding_${n}`);
		_("completed", { reason: `plugin-bound-${n}` });
		i();
		a();
		return {
			status: "complete",
			result: t({
				queuedFinal: false,
				counts: c.getQueuedCounts(),
				...C.hasObservedDelivery() ? { observedReplyDelivery: true } : {}
			})
		};
	};
	if (g) {
		if (f()) return {
			status: "complete",
			result: u()
		};
		m.replyOptions ??= {};
		const l = shouldBypassPluginOwnedBindingForCommand(o, n, m.replyOptions);
		if (!l && (e.sendPolicyDenied || S && !e.suppressAutomaticSourceDelivery)) logVerbose(`plugin-bound inbound skipped under ${s} (plugin=${g.pluginId} session=${b ?? "unknown"}); falling through to suppressed agent processing`);
		else if (!l) {
			const s = await resolveCommandAuthorizationAsync({
				ctx: o,
				cfg: n,
				commandAuthorized: o.CommandAuthorized
			});
			const l = d?.runInboundClaimForPluginOutcome ? await (async () => {
				await runWithDispatchAbortSignal(e.getPreDispatchAbortSignal(), e.prepareHookMediaMetadata, e.trackDispatchLifecycleWork);
				if (f()) throw new DispatchReplyOperationAbortedError();
				const t = {
					...e.hookState.inboundClaimEvent,
					senderIsOwner: s.senderIsOwner
				};
				const n = e.runWithDispatchLifecycleAdmission(async () => await d.runInboundClaimForPluginOutcome(g.pluginId, t, withClaimingHookAdmission({
					...e.hookState.inboundClaimContext,
					pluginBinding: g
				}, { prepare: assertCurrentBindingRoute })));
				e.trackDispatchLifecycleWork(n);
				return await n;
			})() : getGlobalPluginRegistry()?.plugins.some((e) => e.id === g.pluginId && e.status === "loaded") ? { status: "no_handler" } : { status: "missing_plugin" };
			if (f()) return {
				status: "complete",
				result: u()
			};
			switch (l.status) {
				case "handled": {
					const t = await h();
					if (l.result.reply && e.shouldDeliverPluginBindingReply) await e.deliverBindingPayload(l.result.reply, "terminal", t);
					return await finishPluginBindingDispatch("handled");
				}
				case "missing_plugin":
				case "no_handler":
					e.bindingState.pluginFallbackReason = l.status === "missing_plugin" ? "plugin-bound-fallback-missing-plugin" : "plugin-bound-fallback-no-handler";
					if ((r === "group" || r === "channel") && o.WasMentioned === false && !e.explicitCommandTurnCtx && o.GroupRequireMention !== false) {
						p("plugin_binding_fallback_unmentioned");
						_("completed", { reason: e.bindingState.pluginFallbackReason });
						i();
						a();
						return {
							status: "complete",
							result: t({
								queuedFinal: false,
								counts: c.getQueuedCounts()
							})
						};
					}
					if (!hasShownPluginBindingFallbackNotice(g.bindingId, g)) {
						if (await v({ text: buildPluginBindingUnavailableText(g) }, "additive")) markPluginBindingFallbackNoticeShown(g.bindingId, g);
					}
					break;
				case "declined":
				case "error": {
					const e = await h();
					if (l.status === "error") logVerbose(`plugin-bound inbound claim failed for ${g.pluginId}: ${l.error}`);
					await v({ text: l.status === "error" ? buildPluginBindingErrorText(g) : buildPluginBindingDeclinedText(g) }, "terminal", e);
					return await finishPluginBindingDispatch(l.status);
				}
			}
		}
	}
	l();
	return {
		status: "ready",
		state: Object.assign(e, { assertCurrentBindingRoute })
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-from-config.ts
async function dispatchReplyFromConfig(e) {
	return await dispatchReplyFromConfigWithQueuePolicy(e, false);
}
/** Low-level plugin dispatch must reach queue policy before waiting on the active reply owner. */
async function dispatchLowLevelChannelReplyFromConfig(e) {
	return await dispatchReplyFromConfigWithQueuePolicy(e, !getGroupThreadTurn());
}
async function dispatchReplyFromConfigWithQueuePolicy(e, t) {
	const n = await prepareReplySourceInput(e.ctx, e.cfg, prepareInternalGetReplyOptions(e.replyOptions, e.ctx));
	const r = {
		...e,
		replyOptions: n.options
	};
	const i = createInboundMessageAuditTerminal(r);
	let a = false;
	try {
		while (true) try {
			const e = await dispatchReplyFromConfigInner(r, i, t);
			i?.finishSuccess(e);
			return e;
		} catch (e) {
			if (e instanceof DispatchSessionRefreshRequiredError && !a && n.input?.retirementRequested !== true && n.input?.claim?.releaseRequested !== true && r.replyOptions?.abortSignal?.aborted !== true) {
				a = true;
				continue;
			}
			i?.finishError();
			throw e;
		}
	} finally {
		if (n.created) retireUnadoptedReplySource(n.input);
	}
}
async function dispatchReplyFromConfigInner(e, t, n) {
	try {
		var r = _usingCtx();
		const i = r.a(new AsyncDisposableStack());
		let a;
		const o = await gatherDispatchRequest(e, t, n, (e) => {
			a = i.use(scopePreparedModelRuntimeLease(e));
		}, (e) => i.defer(e));
		if (o.status === "complete") return o.result;
		const execute = async () => {
			const e = await prepareDispatchDelivery(o.state);
			const t = await prepareDispatchOperationContext(e);
			if (t.status === "complete") return t.result;
			const n = t.state;
			try {
				const e = await prepareDispatchOperation(t.state);
				if (e.status === "complete") return e.result;
				const n = await chooseDispatchRoute(e.state);
				if (n.status === "complete") return n.result;
				const r = await prepareDispatchExecution(n.state);
				const i = await executeDispatch(r);
				if (i.status === "complete") return i.result;
				return await finalizeDispatchAndAudit(i.state);
			} catch (e) {
				const { failDispatchReplyOperation: t, finishReplyOperationAbortedDispatch: r, inboundDedupeClaim: i, markIdle: a, recordAgentDispatchCompleted: o, recordProcessed: s } = n;
				if (isDispatchReplyOperationAbortedError(e)) return r();
				if (i.status === "claimed") {
					if (n.turnAdoptionState?.adopted || n.inboundDedupeReplayUnsafe) i.commit();
					else i.release();
				}
				if (e instanceof DispatchSessionRefreshRequiredError) a("session_refresh");
				else {
					o("error", { error: String(e) });
					s("error", { error: String(e) });
					a("message_error");
				}
				t(e);
				throw e;
			}
		};
		const runWithRegistry = () => withPluginRuntimeRegistryScope(o.state.pluginRegistry, execute);
		return a ? await a.run(runWithRegistry) : await runWithRegistry();
	} catch (e) {
		r.e = e;
	} finally {
		await r.d();
	}
}
//#endregion
export { emitInboundMessageAuditTerminal as a, resetInboundDedupe as i, dispatchReplyFromConfig as n, resolveBoundAcpDispatchSessionKey as o, emitMessageReceivedHooks as r, DispatchSessionRefreshRequiredError as s, dispatchLowLevelChannelReplyFromConfig as t };