UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,363 lines • 51.9 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { a as resolveAgentDir, f as resolveAgentWorkspaceDir, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { p as isDiagnosticsEnabled } from "./diagnostic-events-BjAH1Kbx.mjs";
import { n as createLazyPromise, t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { a as generateSecureUuid } from "./secure-random-CW5OZnK1.mjs";
import { l as getAdmittedRunDelegatedAuthority, o as closeAdmittedRunDelegatedAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { n as classifySessionStateActor } from "./session-state-events-ChAYnzQG.mjs";
import { i as buildAgentRunTerminalOutcomeFromLifecycleEvent } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { d as toolPolicyRestrictsTools } from "./tool-policy-BR4v75RA.mjs";
import { S as markReplyPayloadAsTtsSupplement, _ as isReplyPayloadStatusNotice, b as isReplyPayloadTtsSupplement, c as getReplyPayloadMetadata, k as setReplyPayloadMetadata, o as copyReplyPayloadMetadata, y as isReplyPayloadTerminalContent } from "./reply-payload-k5WsQWxi.mjs";
import { n as trimTextPreservingCode, t as combineNonStreamingReplyParts } from "./trim-code-text-Dr7f3RLr.mjs";
import { r as createVerifiedConversationContextStreamFilter } from "./user-facing-text-Dqp3fcZx.mjs";
import { c as readChannelContextAdmissionEvidence } from "./admission-evidence-q4_t-NFq.mjs";
import { r as getGatewayLocalUserIngress } from "./local-user-ingress-CLpC74uh.mjs";
import { i as prepareChannelParticipantObservation } from "./requester-profile-DgtOmQ0f.mjs";
import { n as resolveInboundConversationToolPolicy } from "./reply-tool-authority-inbound-BQ8cxNJQ.mjs";
import { n as recordRuntimeActionDecision } from "./runtime-action-decision-B14EMX8j.mjs";
import { r as logVerbose } from "./globals-CgepmiqE.mjs";
import { c as shouldCleanTtsDirectiveText, r as resolveConfiguredTtsMode } from "./tts-config-CNw5woLC.mjs";
import { a as toAcpRuntimeError, n as AcpRuntimeError } from "./errors-DGA2X_Nu.mjs";
import { t as formatAcpRuntimeErrorText } from "./error-text-B6ggyOpO.mjs";
import { o as isSessionIdentityPending, u as resolveSessionIdentityFromMeta } from "./session-identity-BhobFDyP.mjs";
import { i as resolveAcpThreadSessionDetailLines } from "./session-identifiers-dCLUDxk0.mjs";
import "./errors-C4nx2HUe.mjs";
import { u as markDiagnosticSessionProgress } from "./diagnostic-C-GjPJGO.mjs";
import { a as hasOutboundReplyContent } from "./reply-payload-CwASJYas.mjs";
import { r as truncateUtf16WithEllipsis } from "./text-truncate-BXvItwne.mjs";
import { i as resolveAcpDispatchPolicyError, r as resolveAcpAgentPolicyError } from "./policy-De5rDLTI.mjs";
import { t as createTtsDirectiveTextStreamCleaner } from "./directives-DOxtYHyq.mjs";
import { o as prepareReplyPayloadForDispatcher, r as captureReplyDispatchDeliveryOutcome, s as waitForReplyDispatcherIdle, t as attachReplyDispatchUndeliveredFallback } from "./reply-dispatcher-DVZA5pVi.mjs";
import { r as normalizeReplyPayloadOutcome } from "./normalize-reply-C8AkGgUH.mjs";
import { c as resolveRoutedReplyDeliveryOutcome, l as shouldRetryReplyDispatch } from "./reply-dispatch-outcome-C1yqMjJt.mjs";
import { n as resolveRoutedDeliveryThreadId } from "./routed-delivery-thread-C0qY6Hpm.mjs";
import { n as assertPreparedConversationBindingRouteCurrent } from "./session-conversation-binding-B2fKRrgu.mjs";
import { i as cleanDeferredFinalText, n as needsTtsFallback, o as mergeDeferredFinalText, r as buildCaptionedFinalTextFallback, s as shouldDeferFinalTtsText } from "./dispatch-from-config.finalize-AEMg1XZu.mjs";
import { t as resolveStatusTtsSnapshot } from "./status-config-JypAFcu_.mjs";
import { _ as setBlockReplyDelivery, f as createBlockReplyPipeline, h as hasBlockReplyDeliveryCustody, p as createBlockReplySource } from "./dispatch-from-config.payloads-BWvEWyjL.mjs";
import { t as prepareChannelRunAdmission } from "./channel-run-admission-V419E9U5.mjs";
import { n as QuestionAnswerUnconfirmedError, t as PreparedQuestionAnswerRefusedError } from "./gateway-question-dispatch-BdJ_mO-C.mjs";
import { i as claimPreparedPendingAgentQuestionAnswer } from "./gateway-question-u5Q7erev.mjs";
import { n as formatToolSummary, o as resolveToolDisplay } from "./tool-display-BQXZgFy6.mjs";
import { r as hasInboundMediaForUnderstanding } from "./inbound-media-BJ8l1Cri.mjs";
import { n as prepareTtsPreferences } from "./tts-preferences-CIrFrUQO.mjs";
import { a as resolveReplyDeliveryAccountId, o as resolveReplyToMode, t as createReplyDeliveryContext } from "./reply-threading-__RxrMKC.mjs";
import { r as bindUserTurnInput } from "./user-turn-transcript-runtime-context-BZjNfwCQ.mjs";
import { n as resolveEffectiveBlockStreamingConfig } from "./block-streaming-BjSQtS33.mjs";
import { t as stripExtractedFileImageMetadata } from "./extracted-file-images-BWHilGLT.mjs";
import { a as appendRecentHistoryImageContext, i as resolveInlineAgentImageAttachments, n as loadAgentTurnMediaRuntime, r as resolveAgentTurnAttachments, t as collectDescribedImageAttachmentIndexes } from "./agent-turn-attachments-CA7-U-lB.mjs";
import { t as recordAcceptedSessionParticipantInput } from "./session-participant-input-recording-_5WgfQwo.mjs";
import { r as createChannelReplyTransform } from "./reply-transform-VMjxflBU.mjs";
import { r as prefixSystemMessage } from "./system-message-BhIoe23V.mjs";
import { t as EmbeddedBlockChunker } from "./embedded-agent-block-chunker-D13d7ur3.mjs";
import { t as createLazyAcpElicitationHandler } from "./acp-elicitation-handler-lazy-ByC_3Jl7.mjs";
import { t as resolveAcpToolTerminalOutcome } from "./tool-status-CTT8W9yj.mjs";
import { n as resolveAcpProjectionSettings, t as isAcpTagVisible } from "./acp-stream-settings-CE2vsJ4q.mjs";
//#region src/auto-reply/reply/acp-projector.ts
const ACP_BLOCK_REPLY_TIMEOUT_MS = 15e3;
const ACP_MAX_OUTPUT_CHARS = 24e3;
const ACP_MAX_SESSION_UPDATE_CHARS = 320;
const ACP_LIVE_IDLE_FLUSH_FLOOR_MS = 750;
const ACP_LIVE_IDLE_MIN_CHARS = 80;
const ACP_LIVE_SOFT_FLUSH_CHARS = 220;
const ACP_LIVE_HARD_FLUSH_CHARS = 480;
const HIDDEN_BOUNDARY_TAGS = /* @__PURE__ */ new Set(["tool_call", "tool_call_update"]);
function createAcpReplyProjector(e) {
	const t = resolveAcpProjectionSettings(e.cfg);
	const n = t.deliveryMode === "live";
	const r = n ? " " : "\n\n";
	const i = resolveEffectiveBlockStreamingConfig({
		cfg: e.cfg,
		provider: e.provider,
		accountId: e.accountId,
		maxChunkChars: 1800,
		coalesceIdleMs: 350
	});
	let a = false;
	const o = createBlockReplyPipeline({
		onBlockReply: async (t) => {
			setReplyPayloadMetadata(t, { streamedSourceBoundary: a && t.text?.startsWith("\n") ? true : void 0 });
			const n = await e.deliver("block", copyReplyPayloadMetadata(t, {
				...t,
				textMode: "delta"
			}));
			a ||= n && Boolean(t.text?.trim());
		},
		timeoutMs: ACP_BLOCK_REPLY_TIMEOUT_MS,
		coalescing: n ? void 0 : i.coalescing
	});
	const s = new EmbeddedBlockChunker(n ? {
		...i.chunking,
		minChars: 1
	} : i.chunking);
	const c = createVerifiedConversationContextStreamFilter(e.getConversationContext);
	const l = Math.max(i.coalescing.idleMs, ACP_LIVE_IDLE_FLUSH_FLOOR_MS);
	let u = 0;
	let d = false;
	let f;
	let p;
	let m;
	let h;
	let g = false;
	let _ = "";
	let v;
	const y = [];
	const b = /* @__PURE__ */ new Map();
	const clearLiveIdleTimer = () => {
		clearTimeout(v);
		v = void 0;
	};
	const drainChunker = () => {
		s.drain({
			force: true,
			emit: (e) => {
				o.enqueue({ text: e });
			}
		});
	};
	const flushLiveBuffer = (e = false) => {
		if (!_) return;
		if (e && !(_.length >= ACP_LIVE_IDLE_MIN_CHARS || /[.!?][)"'`]*$/.test(_.trimEnd()) || _.includes("\n"))) return;
		const t = _;
		_ = "";
		s.append(t);
		drainChunker();
	};
	const scheduleLiveIdleFlush = () => {
		if (!_) return;
		clearLiveIdleTimer();
		v = setTimeout(() => {
			flushLiveBuffer(true);
		}, l);
	};
	const flush = async () => {
		if (n) {
			clearLiveIdleTimer();
			flushLiveBuffer();
			drainChunker();
		} else {
			if (await e.shouldSendToolSummaries()) for (const t of y.splice(0)) await e.deliver("tool", t.payload, t.meta);
			else y.length = 0;
			if (_.trim().length > 0) {
				const t = _;
				_ = "";
				await e.deliver("final", { text: t });
			}
		}
		await o.flush({ force: true });
	};
	const deliverTool = async (t, r) => {
		if (!n) y.push({
			payload: { text: t },
			...r ? { meta: r } : {}
		});
		else {
			await flush();
			await e.deliver("tool", { text: t }, r);
		}
	};
	const emitSystemStatus = async (n, r) => {
		if (!await e.shouldSendToolSummaries()) return;
		const i = truncateUtf16WithEllipsis(n.trim(), ACP_MAX_SESSION_UPDATE_CHARS);
		if (!i) return;
		const a = prefixSystemMessage(i);
		const o = a.trim();
		if (t.repeatSuppression && r?.dedupe !== false && f === o) return;
		await deliverTool(a);
		f = o;
	};
	const markHiddenToolBoundary = (e) => {
		if (!e.tag || !HIDDEN_BOUNDARY_TAGS.has(e.tag)) return;
		const t = resolveAcpToolTerminalOutcome(e.status) !== void 0;
		g = g || e.tag === "tool_call" || t;
	};
	const emitToolSummary = async (r) => {
		if (!await e.shouldSendToolSummaries()) {
			markHiddenToolBoundary(r);
			return;
		}
		const i = await e.shouldSendFullToolDetails() || normalizeOptionalLowercaseString(r.kind) !== "execute";
		const a = i ? normalizeOptionalString(r.title) : void 0;
		const o = normalizeOptionalString(r.status);
		const s = i ? normalizeOptionalString(r.text) : void 0;
		const c = resolveToolDisplay({
			name: "tool_call",
			meta: [a, o && `status=${o}`].filter(Boolean).join(" · ") || s || "tool call"
		});
		const l = formatToolSummary(c);
		const u = truncateUtf16WithEllipsis(l, ACP_MAX_SESSION_UPDATE_CHARS);
		const d = l.trim();
		const f = normalizeOptionalString(r.toolCallId);
		const m = normalizeOptionalLowercaseString(r.status);
		const h = resolveAcpToolTerminalOutcome(m) !== void 0;
		const g = m === "in_progress" || r.tag === "tool_call";
		if (t.repeatSuppression) {
			if (f) {
				const e = b.get(f) ?? {
					started: false,
					terminal: false
				};
				if (h && e.terminal || g && e.started || e.lastRenderedHash === d) return;
				e.started ||= g;
				e.terminal ||= h;
				e.lastRenderedHash = d;
				b.set(f, e);
			} else if (p === d) return;
		}
		const _ = {
			...f ? { toolCallId: f } : {},
			allowEdit: Boolean(f && r.tag === "tool_call_update")
		};
		await deliverTool(u, _);
		if (!n) markHiddenToolBoundary(r);
		p = d;
	};
	const emitTruncationNotice = async () => {
		if (d) return;
		d = true;
		await emitSystemStatus("output truncated", { dedupe: false });
	};
	const onEvent = async (i) => {
		e.onProgress?.();
		if (i.type === "text_delta") {
			if (i.stream && i.stream !== "output") return;
			if (!isAcpTagVisible(t, i.tag)) return;
			let e = i.text;
			if (!e) return;
			if (g && h && !/^\s/.test(e) && (r === " " ? !/\s$/.test(h) : !h.endsWith("\n"))) e = `${r}${e}`;
			g = false;
			if (u >= ACP_MAX_OUTPUT_CHARS) {
				await emitTruncationNotice();
				return;
			}
			const a = ACP_MAX_OUTPUT_CHARS - u;
			const o = a < e.length ? truncateUtf16Safe(e, a) : e;
			if (o.length > 0) {
				u += o.length;
				const e = c(o);
				h = e.slice(-1) || h;
				_ += e;
				if (n) {
					if (_.length >= ACP_LIVE_HARD_FLUSH_CHARS || _.endsWith("\n\n") || /[.!?][)"'`]*\s$/.test(_) || _.length >= ACP_LIVE_SOFT_FLUSH_CHARS && /\s$/.test(_)) {
						clearLiveIdleTimer();
						flushLiveBuffer();
					} else scheduleLiveIdleFlush();
				}
			}
			if (o.length < e.length) {
				u = ACP_MAX_OUTPUT_CHARS;
				await emitTruncationNotice();
			}
			return;
		}
		if (i.type === "status") {
			if (!isAcpTagVisible(t, i.tag)) return;
			if (i.tag === "usage_update" && t.repeatSuppression) {
				const e = i.used !== void 0 && i.size !== void 0 ? `${i.used}/${i.size}` : i.text.trim();
				if (e === m) return;
				m = e;
			}
			await emitSystemStatus(i.text);
			return;
		}
		if (i.type === "tool_call") {
			if (!isAcpTagVisible(t, i.tag)) {
				markHiddenToolBoundary(i);
				return;
			}
			await emitToolSummary(i);
		}
	};
	return {
		onEvent,
		flush
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-acp-payload.ts
const dispatchAcpTtsRuntimeLoader = createLazyImportLoader(() => import("./tts.runtime.js"));
async function maybeApplyAcpTts(e) {
	if (e.skipTts || isReplyPayloadStatusNotice(e.payload)) return e.payload;
	const t = resolveStatusTtsSnapshot({
		cfg: e.cfg,
		preparedTtsPreferences: e.preparedTtsPreferences,
		sessionAuto: e.ttsAuto,
		agentId: e.agentId,
		channelId: e.channel,
		accountId: e.accountId
	});
	if (!t || t.autoMode === "inbound" && !e.inboundAudio) return e.payload;
	if (e.kind !== "final" && resolveConfiguredTtsMode(e.cfg, {
		agentId: e.agentId,
		channelId: e.channel,
		accountId: e.accountId
	}) === "final") return e.payload;
	const { maybeApplyTtsToPayload: n } = await dispatchAcpTtsRuntimeLoader.load();
	const r = await n(e);
	return copyReplyPayloadMetadata(e.payload, r);
}
const channelPluginRuntimeLoader$1 = createLazyImportLoader(() => import("./plugins-DrH1L0wJ.mjs"));
async function shouldTreatDeliveredTextAsVisible(e) {
	if (!normalizeOptionalString(e.text)) return false;
	if (e.kind === "final") return true;
	const t = normalizeOptionalLowercaseString(e.channel);
	if (!t) return false;
	const { getChannelPlugin: n } = await channelPluginRuntimeLoader$1.load();
	const r = n(t)?.outbound;
	return (r?.shouldTreatDeliveredTextAsVisible ?? r?.shouldTreatRoutedTextAsVisible)?.({
		kind: e.kind,
		text: e.text
	}) ?? false;
}
function getAcpBlockTranscriptText(e, t, n = false) {
	const r = new Set(e.filter((e) => e.delivered).map((e) => e.source));
	const i = new Set(e.filter((e) => e.delivered === "final").map((e) => e.source));
	i.delete(t);
	for (const t of e) if (t.payload.text && !t.delivered) i.delete(t.source);
	return e.flatMap((e) => {
		const t = e.source ? e.source.complete && r.has(e.source) || i.has(e.source) : e.delivered;
		const a = !n || t ? e.transcriptText : e.delivered ? e.payload.text : void 0;
		return a ? [a] : [];
	}).join("\n");
}
function joinAcpBlockText(e) {
	let t = "";
	let n;
	for (const r of e) if (r.payload.text) {
		if (t && (!r.source || r.source !== n)) t += "\n";
		t += r.payload.text;
		n = r.source;
	}
	return t;
}
async function recoverAcpBlockText(e, t) {
	if (e.deliveredAnswerFinalToUser || !t.shouldRouteToOriginating && e.untrackedVisibleText !== "none" && !t.suppressBlockUserDelivery && e.deliveredVisibleText && !e.failedVisibleTextDelivery) return false;
	const n = e.blockTexts.filter((e) => e.needsFinalDelivery && (!t.onlyUndelivered || !e.delivered));
	let r = false;
	for (const e of n) {
		if (t.abortSignal?.aborted) break;
		if (e.source && !t.suppressBlockUserDelivery && await shouldTreatDeliveredTextAsVisible({
			channel: t.channel,
			kind: "block",
			text: e.payload.text
		}) && hasBlockReplyDeliveryCustody(await e.source.settle())) continue;
		if (t.abortSignal?.aborted) break;
		r = await e.deliver("final", true) || r;
		if (e.delivered !== "final") break;
	}
	return r;
}
function buildAcpTextContinuation(e, t) {
	return copyReplyPayloadMetadata(e, {
		text: t,
		replyToId: e.replyToId,
		replyToTag: e.replyToTag,
		replyToCurrent: e.replyToCurrent,
		isCommentary: e.isCommentary,
		isReasoning: e.isReasoning
	});
}
//#endregion
//#region src/auto-reply/reply/dispatch-acp-delivery.ts
const routeReplyRuntimeLoader = createLazyImportLoader(() => import("./route-reply-BCwiheDN.mjs"));
const channelPluginRuntimeLoader = createLazyImportLoader(() => import("./plugins-DrH1L0wJ.mjs"));
const messageActionRuntimeLoader = createLazyImportLoader(() => import("./message-action-runner-DkLM2ujR.mjs"));
function createAcpDispatchDeliveryCoordinator(e) {
	const t = normalizeOptionalLowercaseString(e.ctx.Provider ?? e.ctx.Surface);
	const n = normalizeOptionalLowercaseString(e.originatingChannel);
	const r = normalizeOptionalString(e.sessionKey) ?? e.ctx.SessionKey;
	const i = normalizeOptionalString(e.originatingAccountId) ?? normalizeOptionalString(e.ctx.AccountId);
	const a = resolveReplyDeliveryAccountId(e.cfg, n ?? t, i);
	const o = e.originatingChannel ? createReplyDeliveryContext(resolveReplyToMode(e.cfg, e.originatingChannel, a, e.originatingChatType ?? e.ctx.ChatType), e.originatingChatType ?? e.ctx.ChatType) : void 0;
	const s = {
		startedReplyLifecycle: false,
		blockTexts: [],
		accumulatedBlockTtsText: "",
		accumulatedFinalText: "",
		accumulatedDeliveredFinalText: "",
		pendingTranscriptOutcomes: [],
		cleanBlockTtsDirectiveText: shouldCleanTtsDirectiveText({
			cfg: e.cfg,
			preparedTtsPreferences: e.preparedTtsPreferences,
			ttsAuto: e.sessionTtsAuto,
			agentId: e.agentId,
			channelId: e.ttsChannel,
			accountId: a
		}) ? createTtsDirectiveTextStreamCleaner() : void 0,
		deliveredFinalReply: false,
		pendingAnswerDelivery: false,
		pendingFinalTtsMedia: false,
		deliveredAnswerFinalToUser: false,
		deliveredFinalTtsMedia: false,
		deliveredVisibleText: false,
		failedVisibleTextDelivery: false,
		untrackedVisibleText: "none",
		routedCounts: {
			tool: 0,
			block: 0,
			final: 0
		},
		suppressionReason: void 0,
		toolMessageByCallId: /* @__PURE__ */ new Map()
	};
	let c = false;
	let l;
	let u;
	const settleDirectVisibleText = async () => {
		await waitForReplyDispatcherIdle({ waitForIdle: async () => {
			await Promise.all(s.pendingTranscriptOutcomes);
		} }, e.abortSignal);
		if (e.abortSignal?.aborted) return;
		c = false;
		if (s.untrackedVisibleText !== "pending") return;
		s.untrackedVisibleText = "settled";
		const t = await waitForReplyDispatcherIdle(e.dispatcher, e.abortSignal);
		if (!t) return;
		const n = [t.counts.block, t.counts.final];
		s.failedVisibleTextDelivery ||= n.some((e) => e.failedBeforeSend + e.failedAfterSend > 0);
		s.deliveredVisibleText ||= n.some((e) => e.delivered + e.failedAfterSend > 0);
	};
	const startReplyLifecycleOnce = async () => {
		if (s.startedReplyLifecycle) return;
		s.startedReplyLifecycle = true;
		if (e.suppressReplyLifecycle) return;
		Promise.resolve(e.onReplyStart?.()).catch((e) => {
			logVerbose(`dispatch-acp: reply lifecycle start failed: ${formatErrorMessage(e)}`);
		});
	};
	const tryEditToolMessage = async (t, n) => {
		const r = s.toolMessageByCallId.get(n);
		if (!r?.messageId) return false;
		const i = normalizeOptionalString(t.text);
		if (!i) return false;
		try {
			const { runMessageAction: t } = await messageActionRuntimeLoader.load();
			await t({
				cfg: e.cfg,
				action: "edit",
				params: {
					channel: r.channel,
					to: r.to,
					threadId: r.threadId,
					messageId: r.messageId,
					message: i
				},
				defaultAccountId: r.accountId,
				sessionKey: e.ctx.SessionKey,
				requesterAccountId: e.ctx.AccountId
			});
			s.routedCounts.tool += 1;
			return true;
		} catch (e) {
			logVerbose(`dispatch-acp: tool message edit failed for ${n}: ${formatErrorMessage(e)}`);
			return false;
		}
	};
	const deliver = async (i, d, f) => {
		if (i === "block") setBlockReplyDelivery(Promise.resolve({ outcome: "cancelled" }));
		const p = f?.transcriptSource;
		const m = i === "final" ? s.blockTexts.filter((e) => p?.kind === "blocks" || e.needsFinalDelivery) : [];
		const coverFinalBlockText = (e, t = m) => {
			if (!e.text?.trim() || e.isCommentary || e.isReasoning || isReplyPayloadStatusNotice(e)) return;
			for (const e of t) e.needsFinalDelivery = false;
		};
		let h = d;
		if (!e.suppressUserDelivery) {
			const t = e.shouldRouteToOriginating && n !== void 0;
			const r = t ? (await channelPluginRuntimeLoader.load()).getChannelPlugin(n)?.messaging : void 0;
			const o = t ? normalizeReplyPayloadOutcome(d, {
				preserveLeadingSourceBoundary: i === "block" && getReplyPayloadMetadata(d)?.streamedSourceBoundary === true,
				transformReplyPayload: createChannelReplyTransform({
					messaging: r,
					cfg: e.cfg,
					accountId: a
				})
			}) : prepareReplyPayloadForDispatcher(e.dispatcher, i, d);
			if (o.kind === "suppress") {
				if (o.reason === "channel_transform") {
					s.suppressionReason = o.reason;
					coverFinalBlockText(d);
					if (i === "block" && d.text?.trim()) setBlockReplyDelivery(Promise.resolve({ outcome: "channel-transform" }), d);
				}
				return false;
			}
			h = o.payload;
		}
		const g = isReplyPayloadStatusNotice(h);
		const _ = i === "block" ? normalizeOptionalString(h.text) : void 0;
		const v = g ? void 0 : _;
		let y;
		if (_) {
			const e = s.cleanBlockTtsDirectiveText?.hasBufferedDirectiveText() === true;
			if (v) {
				if (s.accumulatedBlockTtsText.length > 0 && !e) s.accumulatedBlockTtsText += "\n";
				s.accumulatedBlockTtsText += v;
			}
			if (s.cleanBlockTtsDirectiveText && v) {
				if (!h.isCommentary && !h.isReasoning) y = l ?? createBlockReplySource();
				const e = s.cleanBlockTtsDirectiveText.push(h.text?.replace(/^[^\S\r\n]+|[^\S\r\n]+$/g, "") ?? _);
				if (y) {
					const e = s.cleanBlockTtsDirectiveText.hasBufferedDirectiveText();
					y.setComplete(!e);
					l = e ? y : void 0;
				}
				h = copyReplyPayloadMetadata(h, {
					...h,
					text: e.trim() ? e : void 0
				});
			}
		}
		const b = i === "final" && !g ? normalizeOptionalString(h.text) : void 0;
		if (b && !p) {
			if (s.accumulatedFinalText.length > 0) s.accumulatedFinalText += "\n";
			s.accumulatedFinalText += b;
		}
		const x = !p ? b : p.kind === "final" ? p.text : void 0;
		const sendPrepared = async (l, u, d = f?.skipTts, h = i) => {
			const _ = h === "final" && i === "block";
			const v = _ && u ? [u] : m;
			let y = _ ? u?.delivered || e.suppressBlockUserDelivery ? buildAcpTextContinuation(l, l.text) : copyReplyPayloadMetadata(l, { ...l }) : l;
			if (!hasOutboundReplyContent(y, { trimText: true })) return false;
			await startReplyLifecycleOnce();
			if (e.suppressUserDelivery) return false;
			if (h === "block" && e.suppressBlockUserDelivery && !g && !y.isReasoning && !y.isCommentary) {
				if (!Boolean(y.mediaUrl || y.mediaUrls?.length || y.presentation || y.interactive || y.channelData)) return false;
				y = copyReplyPayloadMetadata(y, {
					...y,
					text: void 0
				});
			}
			const S = await maybeApplyAcpTts({
				preparedTtsPreferences: e.preparedTtsPreferences,
				payload: y,
				cfg: e.cfg,
				agentId: e.agentId,
				channel: e.ttsChannel,
				accountId: a,
				kind: h,
				inboundAudio: e.inboundAudio,
				ttsAuto: e.sessionTtsAuto,
				skipTts: d
			});
			const C = h === "final" && e.suppressBlockUserDelivery && s.cleanBlockTtsDirectiveText ? d || y.isError || isReplyPayloadTtsSupplement(y) ? y.text : mergeDeferredFinalText(s.accumulatedBlockTtsText, y.text) : void 0;
			const w = C !== void 0 ? copyReplyPayloadMetadata(S, {
				...S,
				text: cleanDeferredFinalText(C) || void 0
			}) : S;
			const T = h === "final" && isReplyPayloadTtsSupplement(w);
			const resolveVisibleText = (e) => shouldTreatDeliveredTextAsVisible({
				channel: e,
				kind: h,
				text: w.text
			});
			const E = h === "final" && (isReplyPayloadTerminalContent(y) || T && Boolean(w.text?.trim()));
			const recordVisibleBlock = (e, t) => {
				s.deliveredVisibleText ||= e && t;
				if (u && e) u.needsFinalDelivery = false;
			};
			const recordPendingDelivery = (e) => {
				recordVisibleBlock(e, false);
				const t = e && h !== "tool" && !g && !w.isCommentary && !w.isReasoning;
				s.pendingAnswerDelivery ||= t;
				coverFinalBlockText(w, v);
				s.pendingFinalTtsMedia ||= T;
			};
			const recordFinalReply = () => {
				if (h === "final") {
					s.deliveredFinalReply = true;
					s.deliveredAnswerFinalToUser ||= !_ && E && (!p || p.kind === "final");
					s.deliveredFinalTtsMedia ||= T;
					coverFinalBlockText(w, v);
				}
			};
			const recordDeliveredReply = (e) => {
				if (u) u.delivered = h === "final" ? "final" : "block";
				if ((b || T) && p?.kind === "blocks") for (const e of v) e.delivered = "final";
				else if (x) s.accumulatedDeliveredFinalText = s.accumulatedDeliveredFinalText ? `${s.accumulatedDeliveredFinalText}\n${x}` : x;
				recordFinalReply();
				recordVisibleBlock(e, true);
			};
			if (e.shouldRouteToOriginating && e.originatingChannel && e.originatingTo) {
				const t = normalizeOptionalString(f?.toolCallId);
				if (h === "tool" && f?.allowEdit === true && t) {
					if (await tryEditToolMessage(w, t)) return true;
				}
				const i = await resolveVisibleText(n);
				const { routeReply: c } = await routeReplyRuntimeLoader.load();
				const l = e.originatingThreadId ?? resolveRoutedDeliveryThreadId({
					ctx: e.ctx,
					sessionKey: r
				});
				const d = await c({
					payload: w,
					channel: e.originatingChannel,
					to: e.originatingTo,
					agentId: e.agentId,
					sessionKey: r,
					...r !== e.ctx.SessionKey ? { policySessionKey: e.ctx.SessionKey } : {},
					accountId: a,
					requesterSenderId: e.ctx.SenderId,
					requesterSenderName: e.ctx.SenderName,
					requesterSenderUsername: e.ctx.SenderUsername,
					requesterSenderE164: e.ctx.SenderE164,
					threadId: l,
					replyDelivery: o,
					cfg: e.cfg,
					abortSignal: e.abortSignal,
					mirror: false,
					replyKind: h,
					runId: e.runId
				});
				const m = resolveRoutedReplyDeliveryOutcome(d);
				const g = m === "recovery-owned" || m === "failed-deliver";
				if (h === "block") setBlockReplyDelivery(Promise.resolve({
					outcome: m,
					pending: g
				}), w);
				if (u && d.suppressed && (i || m === "channel-transform" && w.text?.trim())) u.needsFinalDelivery = false;
				if (g) {
					recordPendingDelivery(i);
					return true;
				}
				if (shouldRetryReplyDispatch(m) && T && w.text?.trim()) {
					if (!d.suppressed) logVerbose(`dispatch-acp: route-reply (acp/${h}) failed: ${d.error ?? "unknown error"}`);
					return await deliver("final", { text: w.text }, {
						skipTts: true,
						transcriptSource: p ?? {
							kind: "final",
							text: b ?? ""
						}
					});
				}
				if (!d.delivered && !d.suppressed) {
					if (i) s.failedVisibleTextDelivery = true;
					logVerbose(`dispatch-acp: route-reply (acp/${h}) failed: ${d.error ?? "unknown error"}`);
					return false;
				}
				if (d.suppressed) {
					if (m === "channel-transform") coverFinalBlockText(w, v);
					if (h === "final") s.deliveredFinalReply = true;
					if (i) s.deliveredVisibleText = true;
					return true;
				}
				if (!d.ok) logVerbose(`dispatch-acp: route-reply (acp/${h}) partially failed after delivery: ${d.error ?? "unknown error"}`);
				if (h === "tool" && f?.toolCallId && d.messageId) s.toolMessageByCallId.set(f.toolCallId, {
					channel: e.originatingChannel,
					accountId: a,
					to: e.originatingTo,
					...l != null ? { threadId: l } : {},
					messageId: d.messageId
				});
				recordDeliveredReply(i);
				s.routedCounts[h] += 1;
				return true;
			}
			if (h === "tool" && c) {
				c = false;
				await waitForReplyDispatcherIdle(e.dispatcher, e.abortSignal);
			}
			const D = await resolveVisibleText(t);
			const O = h !== "tool" ? captureReplyDispatchDeliveryOutcome(w) : void 0;
			if (T && w.text?.trim()) attachReplyDispatchUndeliveredFallback(w, buildCaptionedFinalTextFallback(w));
			const k = h === "tool" ? e.dispatcher.sendToolResult(w) : h === "block" ? e.dispatcher.sendBlockReply(w) : e.dispatcher.sendFinalReply(w);
			if (h === "block") setBlockReplyDelivery(k && O?.isTracked() ? O.promise.then((e) => ({
				outcome: e,
				pending: O.hasPendingDelivery()
			})) : Promise.resolve(k ? {
				outcome: "failed-deliver",
				pending: true
			} : { outcome: "cancelled" }), w);
			if (k && O?.isTracked()) {
				const e = O.promise.then((e) => {
					if (O.hasPendingDelivery()) recordPendingDelivery(D);
					else if (e === "delivered") recordDeliveredReply(D);
					else {
						if (!shouldRetryReplyDispatch(e)) {
							if (u && w.text?.trim()) u.needsFinalDelivery = false;
							coverFinalBlockText(w, v);
						}
						if (D) {
							s.failedVisibleTextDelivery ||= e === "failed-before-deliver" || e === "failed-deliver";
							s.deliveredVisibleText ||= e === "failed-deliver";
						}
					}
				});
				s.pendingTranscriptOutcomes.push(e);
				if (h === "final") await e;
			} else if (k) {
				recordFinalReply();
				if (D) s.untrackedVisibleText = "pending";
			} else if (D) s.failedVisibleTextDelivery = true;
			if (h === "block" && k) c = true;
			return k;
		};
		const recordBlock = (e, t) => {
			const n = {
				payload: e,
				transcriptText: t,
				source: y,
				needsFinalDelivery: Boolean(e.text),
				deliver: (e, t) => sendPrepared(n.payload, n, t, e)
			};
			s.blockTexts.push(n);
			return n;
		};
		const S = _ ? recordBlock(h, v) : void 0;
		if (s.cleanBlockTtsDirectiveText && v) u = s.cleanBlockTtsDirectiveText.hasBufferedDirectiveText() ? async (t) => {
			const n = buildAcpTextContinuation(h, t);
			const r = recordBlock(n);
			const sendTail = async () => {
				setBlockReplyDelivery(Promise.resolve({ outcome: "cancelled" }), n);
				return e.abortSignal?.aborted ? false : await r.deliver("block", true);
			};
			return y ? await y.run(sendTail) ?? false : await sendTail();
		} : void 0;
		const send = () => S ? S.deliver("block") : sendPrepared(h, void 0);
		return y ? await y.run(send) ?? false : await send();
	};
	return {
		startReplyLifecycle: startReplyLifecycleOnce,
		deliver,
		flushBlockText: async () => {
			if (e.abortSignal?.aborted) return;
			const t = s.cleanBlockTtsDirectiveText?.flush();
			const n = u;
			u = void 0;
			l?.setComplete(true);
			l = void 0;
			if (t?.trim() && n) await n(t);
		},
		getAccumulatedVisibleBlockText: () => joinAcpBlockText(s.blockTexts),
		getVisibleBlockDisplayText: () => combineNonStreamingReplyParts(s.blockTexts.map((e) => trimTextPreservingCode(e.payload.text ?? ""))),
		recoverBlockText: async (r) => {
			if (!e.suppressBlockUserDelivery) await settleDirectVisibleText();
			return await recoverAcpBlockText(s, {
				...e,
				channel: n ?? t,
				onlyUndelivered: r?.onlyUndelivered
			});
		},
		getAccumulatedBlockTtsText: () => s.accumulatedBlockTtsText,
		getAccumulatedTranscriptText: () => s.accumulatedFinalText || getAcpBlockTranscriptText(s.blockTexts, l),
		resolveAccumulatedDeliveredTranscriptText: async () => {
			await Promise.all(s.pendingTranscriptOutcomes);
			await Promise.all(s.blockTexts.flatMap((e) => e.source ? [e.source.settle()] : []));
			return s.accumulatedDeliveredFinalText || getAcpBlockTranscriptText(s.blockTexts, l, true);
		},
		settleVisibleText: settleDirectVisibleText,
		hasDeliveredFinalReply: () => s.deliveredFinalReply,
		hasPendingAnswerDelivery: () => s.pendingAnswerDelivery,
		hasPendingFinalTtsMedia: () => s.pendingFinalTtsMedia,
		hasDeliveredFinalTtsMedia: () => s.deliveredFinalTtsMedia,
		hasDeliveredVisibleText: () => s.deliveredVisibleText,
		hasFailedVisibleTextDelivery: () => s.failedVisibleTextDelivery,
		getDeliverySuppressionReason: () => s.suppressionReason,
		applyRoutedCounts: (e) => {
			e.tool += s.routedCounts.tool;
			e.block += s.routedCounts.block;
			e.final += s.routedCounts.final;
			return e;
		}
	};
}
//#endregion
//#region src/auto-reply/reply/dispatch-acp-finalize.ts
const loadDispatchAcpTtsRuntime = createLazyPromise(() => import("./tts.runtime.js"));
const loadDispatchAcpManagerRuntime$1 = createLazyPromise(() => import("./dispatch-acp-manager.runtime.js"));
async function finalizeAcpTurnOutput(e) {
	const t = resolveConfiguredTtsMode(e.cfg, {
		agentId: e.agentId,
		channelId: e.ttsChannel,
		accountId: e.ttsAccountId
	});
	const n = e.delivery.getAccumulatedBlockTtsText();
	const r = n.trim().length > 0;
	const i = resolveStatusTtsSnapshot({
		cfg: e.cfg,
		preparedTtsPreferences: e.preparedTtsPreferences,
		sessionAuto: e.sessionTtsAuto,
		agentId: e.agentId,
		channelId: e.ttsChannel,
		accountId: e.ttsAccountId
	});
	const a = t === "final" && r && i != null && !(i.autoMode === "inbound" && !e.inboundAudio);
	const o = e.shouldDeferVisibleTextForTts && a;
	const s = o ? cleanDeferredFinalText(n) : e.delivery.getAccumulatedVisibleBlockText();
	if (!o) await e.delivery.settleVisibleText();
	if (e.abortSignal?.aborted) return false;
	let c = e.delivery.hasPendingAnswerDelivery() || e.delivery.hasPendingFinalTtsMedia() || e.delivery.hasDeliveredVisibleText() && !e.delivery.hasFailedVisibleTextDelivery();
	if (a && !e.delivery.hasPendingFinalTtsMedia() && !e.delivery.hasDeliveredFinalTtsMedia()) try {
		const { maybeApplyTtsToPayload: t } = await loadDispatchAcpTtsRuntime();
		if (e.abortSignal?.aborted) return c;
		const r = await t({
			preparedTtsPreferences: e.preparedTtsPreferences,
			payload: { text: n },
			cfg: e.cfg,
			channel: e.ttsChannel,
			kind: "final",
			inboundAudio: e.inboundAudio,
			ttsAuto: e.sessionTtsAuto,
			agentId: e.agentId,
			accountId: e.ttsAccountId
		});
		if (r.mediaUrl) {
			const t = markReplyPayloadAsTtsSupplement({
				...r,
				text: o ? s || void 0 : void 0,
				trustedLocalMedia: true
			}, n, o ? void 0 : { visibleTextAlreadyDelivered: true });
			const i = await e.delivery.deliver("final", t, { transcriptSource: { kind: "blocks" } });
			c = c || i;
		} else if (o && r.text?.trim() || needsTtsFallback(true, s, r.text)) {
			const t = await e.delivery.deliver("final", { text: r.text }, {
				skipTts: true,
				transcriptSource: { kind: "blocks" }
			});
			c = c || t;
		}
	} catch (e) {
		logVerbose(`dispatch-acp: accumulated ACP block TTS failed: ${formatErrorMessage(e)}`);
	}
	c = await e.delivery.recoverBlockText({ onlyUndelivered: t === "all" }) || c;
	if (e.shouldEmitResolvedIdentityNotice) {
		const { readAcpSessionEntryAsync: t } = await loadDispatchAcpManagerRuntime$1();
		const n = await t({
			cfg: e.cfg,
			sessionKey: e.sessionKey,
			agentId: e.agentId
		});
		if (e.abortSignal?.aborted) return c;
		const r = n?.acp;
		const i = resolveSessionIdentityFromMeta(r);
		if (!isSessionIdentityPending(i)) {
			const t = resolveAcpThreadSessionDetailLines(r);
			if (t.length > 0) {
				const n = await e.delivery.deliver("final", {
					text: prefixSystemMessage(["Session ids resolved.", ...t].join("\n")),
					isStatusNotice: true
				});
				c = c || n;
			}
		}
	}
	return c;
}
//#endregion
//#region src/auto-reply/reply/dispatch-acp-prompt.ts
function resolveAcpTurnText(e) {
	if (e.sourceReplyDeliveryMode !== "message_tool_only") return e.promptText;
	const t = prefixSystemMessage([
		"Source channel delivery is private by default for this turn.",
		"Normal ACP final output will not be automatically posted to the source channel.",
		"To send visible output, use message(action=send). The target defaults to the current source channel."
	].join(" "));
	return e.promptText ? `${t}\n\n${e.promptText}` : t;
}
//#endregion
//#region src/auto-reply/reply/dispatch-acp.ts
const loadDispatchAcpManagerRuntime = createLazyPromise(() => import("./dispatch-acp-manager.runtime.js"));
const loadDispatchAcpAuditRuntime = createLazyPromise(() => import("./acp-lifecycle-rp4jCfAm.mjs"));
const loadDispatchAcpTranscriptRuntime = createLazyPromise(() => import("./dispatch-acp-transcript.runtime.js"));
function resolveAcpRequestId(e) {
	const t = e.MessageSidFull ?? e.MessageSid ?? e.MessageSidFirst ?? e.MessageSidLast;
	return normalizeOptionalString(t) ?? (typeof t === "number" || typeof t === "bigint" ? String(t) : generateSecureUuid());
}
async function tryDispatchAcpReplyCore(e) {
	const t = normalizeOptionalString(e.sessionKey);
	if (!t || e.bypassForCommand) return null;
	prepareChannelParticipantObservation(e.ctx);
	const n = e.userTurnTranscriptRecorder;
	const r = bindUserTurnInput(n, () => e.abortSignal?.throwIfAborted());
	const { getAcpSessionManager: i, maybeUnbindStaleBoundConversations: a, prepareAcpDispatchStart: o } = await loadDispatchAcpManagerRuntime();
	const s = i();
	const c = await s.resolveSessionAsync({
		cfg: e.cfg,
		sessionKey: t,
		agentId: resolveSessionAgentId({
			config: e.cfg,
			sessionKey: t,
			fallbackAgentId: e.ctx.AgentId
		}),
		assertCurrent: r.assertLifetimeCurrent
	});
	await r.withCurrent(() => {});
	if (c.kind === "none") return null;
	const l = c.sessionKey;
	const u = c.kind === "ready" ? c.entry?.sessionId : void 0;
	const d = c.agentId;
	const f = {
		agentId: d,
		sessionKey: l,
		storePath: resolveSessionStorePathCore(e.cfg.session?.store, { agentId: d }),
		onError: (e) => logVerbose(`dispatch-acp: participant persistence failed: ${formatErrorMessage(e)}`)
	};
	const p = isDiagnosticsEnabled(e.cfg) ? normalizeUniqueTrimmedStringList([
		e.ctx.SessionKey,
		t,
		l
	]) : [];
	const m = p.length > 0 ? () => {
		for (const e of p) markDiagnosticSessionProgress({ sessionKey: e });
	} : void 0;
	const h = isSessionIdentityPending(resolveSessionIdentityFromMeta(c.kind === "ready" ? c.meta : void 0));
	const g = normalizeOptionalLowercaseString(e.ctx.OriginatingChannel ?? e.ctx.Surface ?? e.ctx.Provider);
	const _ = normalizeOptionalString(e.ctx.AccountId);
	const v = e.cfg.channels;
	const y = g == null ? void 0 : v?.[g]?.defaultAccount;
	const b = _ ?? normalizeOptionalString(y);
	const hasBoundConversationForSession = async () => {
		const e = g;
		if (!e) return false;
		const t = normalizeOptionalLowercaseString(b) ?? "default";
		const { listSessionBindingsBySessionAsync: n } = await loadDispatchAcpManagerRuntime();
		return (await n(l)).some((n) => normalizeOptionalLowercaseString(n.conversation.channel) === e && (normalizeOptionalLowercaseString(n.conversation.accountId) || "default") === t && Boolean(normalizeOptionalString(n.conversation.conversationId)));
	};
	const x = !e.suppressUserDelivery && h && (e.ctx.MessageThreadId != null && String(e.ctx.MessageThreadId).trim() !== "" || await hasBoundConversationForSession());
	const S = c.kind === "ready" ? normalizeOptionalString(c.meta.agent) ?? normalizeOptionalString(e.cfg.acp?.defaultAgent) ?? resolveAgentIdFromSessionKey(l) : resolveAgentIdFromSessionKey(l);
	const C = e.preparedTtsPreferences ?? await prepareTtsPreferences();
	await r.withCurrent(() => {});
	const w = shouldDeferFinalTtsText({
		preparedTtsPreferences: C,
		cfg: e.cfg,
		ttsAuto: e.sessionTtsAuto,
		agentId: d,
		channelId: e.ttsChannel,
		accountId: b,
		inboundAudio: e.inboundAudio
	});
	let T = false;
	const E = createAcpDispatchDeliveryCoordinator({
		...e,
		preparedTtsPreferences: C,
		agentId: d,
		sessionKey: l,
		suppressBlockUserDelivery: w
	});
	const D = e.ctx.agentText.trim();
	const O = n ? async () => {
		await r.withCurrent(() => {});
		await n.persistApproved();
		await r.withCurrent(() => {});
		if (!n.hasPersisted()) throw new Error("ACP input must be durably committed before dispatch.");
	} : void 0;
	try {
		if (D && !e.images?.length && !e.extractedFileImages?.length && !hasInboundMediaForUnderstanding(e.ctx) && await claimPreparedPendingAgentQuestionAnswer({
			sessionKey: c.sessionKey,
			text: D,
			sourceRecorder: n,
			authority: {
				kind: "run",
				assertCurrent: r.assertNativeCurrent
			}
		}, () => assertPreparedConversationBindingRouteCurrent(e.ctx))) {
			recordAcceptedSessionParticipantInput(e.ctx, f);
			const t = e.dispatcher.getQueuedCounts();
			e.recordProcessed("completed", { reason: "acp_question_answer" });
			e.markIdle("message_completed");
			return {
				queuedFinal: false,
				counts: t
			};
		}
	} catch (t) {
		if (!(t instanceof QuestionAnswerUnconfirmedError) && !(t instanceof PreparedQuestionAnswerRefusedError)) throw t;
		e.recordProcessed("error", {
			reason: t instanceof QuestionAnswerUnconfirmedError ? "acp_question_answer_unconfirmed" : "acp_question_answer_refused",
			error: t.message
		});
		const n = await E.deliver("final", {
			text: t.message,
			isError: true
		}).catch((e) => {
			logVerbose(`dispatch-acp: question notice delivery failed: ${formatErrorMessage(e)}`);
			return false;
		});
		e.markIdle("message_error");
		return {
			queuedFinal: n,
			counts: E.applyRoutedCounts(e.dispatcher.getQueuedCounts())
		};
	}
	const deliverDeferredTextFallback = async () => w ? await E.recoverBlockText() : false;
	const k = resolveAcpProjectionSettings(e.cfg).deliveryMode === "live";
	let A = "";
	const j = createAcpReplyProjector({
		cfg: e.cfg,
		shouldSendToolSummaries: e.shouldSendToolSummaries,
		shouldSendFullToolDetails: e.shouldSendFullToolDetails,
		deliver: async (t, n, r) => {
			const i = await E.deliver(t, n, r);
			const a = k && t === "block" ? E.getVisibleBlockDisplayText() : "";
			const o = a.startsWith(A) ? a.slice(A.length) : a;
			if (o && !P && !e.suppressUserDelivery) {
				L.emitAcpAssistantDelta({
					runId: I,
					text: a,
					delta: o
				});
				A = a;
			}
			return i;
		},
		getConversationContext: () => e.ctx.agentText,
		onProgress: m,
		provider: e.ctx.Surface ?? e.ctx.Provider,
		accountId: b
	});
	const finishAttempt = (t, n) => {
		const r = E.applyRoutedCounts(e.dispatcher.getQueuedCounts());
		const i = r.tool + r.block + r.final > 0 || t ? void 0 : E.getDeliverySuppressionReason();
		e.recordProcessed("completed", { reason: n ? `acp_error:${normalizeLowercaseStringOrEmpty(n.code)}` : i ?? "acp_dispatch" });
		e.markIdle("message_completed");
		return {
			queuedFinal: t,
			counts: r
		};
	};
	const M = resolveAcpRequestId(e.ctx);
	const N = normalizeOptionalString(e.runId);
	const P = N === void 0;
	let F;
	const I = N ?? generateSecureUuid();
	const L = await loadDispatchAcpAuditRuntime();
	const R = L.createAcpToolLifecycleTracker();
	const z = {
		runId: I,
		sessionKey: l,
		agentId: d,
		auditOnly: P
	};
	let B = false;
	let V = false;
	let H;
	let U;
	let W;
	let G;
	let K;
	const q = await o({
		scope: f,
		sessionId: u,
		runId: I,
		onAgentRunStart: e.onAgentRunStart,
		onPreparedAgentRunStart: e.onPreparedAgentRunStart,
		getResult: () => ({
			assistantTranscript: G,
			terminalOutcome: K
		})
	});
	await r.withCurrent(() => {});
	let J;
	const resolveAuditEndFields = () => J ??= L.resolveAcpLifecycleEndFields(e.abortSignal, U, W);
	const emitAuditStart = () => {
		if (B) return;
		B = true;
		F = q();
		L.emitAcpLifecycleStart({
			...z,
			startedAt: Date.now(),
			completionSource: F
		});
	};
	const emitAuditTerminal = (t) => {
		if (V) return;
		emitAuditStart();
		V = true;
		const n = {
			...z,
			toolTracker: R,
			completionSource: F
		};
		K = t ? L.emitAcpLifecycleError({
			...n,
			...e.abortSignal ? { abortSignal: e.abortSignal } : {},
			...H ? { terminalOutcome: H } : {},
			error: t
		}) : L.emitAcpLifecycleEnd({
			...n,
			endFields: resolveAuditEndFields()
		});
	};
	let Y = "";
	let X = false;
	let Z = false;
	const persistTranscript = async (t) => {
		if (Z) return;
		Z = true;
		K ??= buildAgentRunTerminalOutcomeFromLifecycleEvent({
			phase: "end",
			data: resolveAuditEndFields()
		});
		const { persistAcpDispatchTranscript: n } = await loadDispatchAcpTranscriptRuntime();
		G = await n({
			cfg: e.cfg,
			sessionKey: l,
			agentId: d,
			expectedSessionId: u,
			promptText: Y,
			finalText: t,
			terminalOutcome: K,
			meta: c.kind === "ready" ? c.meta : void 0,
			threadId: e.ctx.MessageThreadId,
			userTurnTranscriptRecorder: e.userTurnTranscriptRecorder,
			prepareAssistantTranscriptMessage: e.prepareAssistantTranscriptMessage,
			assistantIdempotencyKey: N
		});
	};
	let Q;
	let $ = false;
	const recordUnsupportedNativeActionEvidence = () => {
		if ($) return;
		$ = true;
		recordRuntimeActionDecision({
			token: Q?.executionIdentityToken,
			family: "native-runtime",
			operation: "action-evidence",
			outcome: "not-applicable",
			coverageState: "unsupported",
			reasonCode: "native_action_callback_unsupported",
			owner: "acp-runtime",
			decisionBoundary: "acp-runtime.prompt-submitted",
			summary: "ACP runtime action evidence is unsupported because the adapter exposes no authoritative native-action callback.",
			missingEvidence: ["native.action_callback"],
			remediation: [{
				code: "instrument_native_action_callback",
				text: "Instrument an authoritative native-action callback in the ACP adapter before claiming action evidence."
			}]
		});
	};
	try {
		const n = resolveAcpDispatchPolicyError(e.cfg);
		if (n) {
			H = "blocked";
			throw n;
		}
		const { ctx: i, cfg: o } = e;
		if (e.toolsAllow !== void 0 && !e.toolsAllow.some((e) => normalizeLowercaseStringOrEmpty(e) === "*") || toolPolicyRestrictsTools(resolveInboundConversationToolPolicy({
			ctx: i,
			config: o,
			sessionKey: e.sessionKey
		}))) {
			H = "blocked";
			throw new AcpRuntimeError("ACP_DISPATCH_DISABLED", "This session's bound runtime cannot enforce its permission or tool policy; use an embedded runtime for this restricted conversation.");
		}
		if (c.kind === "stale") {
			emitAuditTerminal(c.error);
			await a({
				targetSessionKey: l,
				error: c.error
			});
			return finishAttempt(await E.deliver("final", {
				text: formatAcpRuntimeErrorText(c.error),
				isError: true
			}), c.error);
		}
		const u = resolveAcpAgentPolicyError(e.cfg, S);
		if (u) {
			H = "blocked";
			throw u;
		}
		const p = await resolveAgentTurnAttachments({
			ctx: e.ctx,
			cfg: e.cfg
		});
		let m = e.extractedFileImages ?? [];
		if (hasInboundMediaForUnderstanding(e.ctx) && !e.ctx.MediaUnderstanding?.length) try {
			const { applyMediaUnderstanding: t } = await loadAgentTurnMediaRuntime();
			const n = await t({
				ctx: e.ctx,
				cfg: e.cfg,
				deliveredImageIndexes: new Set(p.attachmentIndexes ?? []),
				agentId: d,
				agentDir: resolveAgentDir(e.cfg, d),
				workspaceDir: resolveAgentWorkspaceDir(e.cfg, d)
			});
			if (n.extractedFileImages.length > 0) m = [...m, ...n.extractedFileImages];
		} catch (e) {
			logVerbose(`dispatch-acp: media understanding failed, proceeding with raw content: ${formatErrorMessage(e)}`);
		}
		const h = e.ctx.agentText.trim();
		const g = collectDescribedImageAttachmentIndexes(e.ctx);
		const _ = p.attachments.length - p.recentHistoryImages.length;
		const v = p.attachments.flatMap((e, t) => {
			const n = p.attachmentIndexes?.[t];
			return n !== void 0 && !g.has(n) && (g.size === 0 || t < _) ? [{
				attachment: e,
				sourceIndex: n
			}] : [];
		});
		const y = g.size === 0 ? p.recentHistoryImages : [];
		const D = resolveInlineAgentImageAttachments(e.images);
		const k = resolveInlineAgentImageAttachments(m.map(stripExtractedFileImageMetadata));
		const A = v.length > 0 && !(v.length === y.length && (D.length > 0 || k.length > 0));
		const N = [...A ? v : D.map((e) => ({
			attachment: e,
			sourceIndex: void 0
		})), ...k.map((e, t) => ({
			attachment: e,
			sourceIndex: m[t]?.attachmentIndex
		}))].map(({ attachment: e, sourceIndex: t }, n) => ({
			attachment: e,
			sourceIndex: t,
			sequence: n
		})).toSorted((e, t) => {
			if (e.sourceIndex !== void 0 && t.sourceIndex !== void 0) return e.sourceIndex - t.sourceIndex || e.sequence - t.sequence;
			return e.sequence - t.sequence;
		}).map((e) => e.attachment);
		const P = A ? appendRecentHistoryImageContext({
			promptText: h,
			images: y
		}) : h;
		Y = P;
		if (!P && N.length === 0) {
			const t = E.applyRoutedCounts(e.dispatcher.getQueuedCounts());
			e.recordProcessed("completed", { reason: "acp_empty_prompt" });
			e.markIdle("message_completed");
			return {
				queuedFinal: false,
				counts: t
			};
		}
		Q = await prepareChannelRunAdmission({
			cfg: e.cfg,
			runId: M,
			agentId: d,
			ingressKind: "acp",
			boundary: "auto-reply.acp",
			evidence: readChannelContextAdmissionEvidence(e.ctx),
			gatewayLocalUserIngress: getGatewayLocalUserIngress(e.ctx)
		}).admit("acp");
		recordAcceptedSessionParticipantInput(e.ctx, f);
		const F = Q;
		const B = createLazyAcpElicitationHandler({
			sourceSessionKey: t,
			targetSessionKey: l,
			outerRequestId: M,
			agentId: d,
			runId: I,
			delivery: E,
			isActive: () => e.abortSignal?.aborted !== true && Q === F && getAdmittedRunDelegatedAuthority(F) !== void 0
		});
		await O?.();
		emitAuditStart();
		try {
			await E.startReplyLifecycle();
		} catch (e) {
			logVerbose(`dispatch-acp: start reply lifecycle failed: ${formatErrorMessage(e)}`);
		}
		await assertPreparedConversationBindingRouteCurrent(e.ctx);
		const V = {
			admittedRunContext: Q,
			cfg: e.cfg,
			sessionKey: l,
			agentId: d,
			provenance: classifySessionStateActor({
				inputProvenance: e.ctx.InputProvenance,
				sessionEffects: e.ctx.InboundEventKind === "room_event" ? "internal" : "visible"
			}).actorType,
			text: resolveAcpTurnText({
				promptText: P,
				sourceReplyDeliveryMode: e.sourceReplyDeliveryMode
			}),
			attachments: N.length > 0 ? N : void 0,
			mode: "prompt",
			requestId: M,
			...e.abortSignal ? { signal: e.abortSignal } : {},
			onBeforePrompt: async () => {
				await r.withCurrent(() => {});
				await e.turnAdoption?.adopt();
				await assertPreparedConversationBindingRouteCurrent(e.ctx);
				await r.withCurrent(() => {
					if (getAdmittedRunDelegatedAuthority(F) === void 0) throw new Error("ACP turn admission ended before input dispatch.");
				});
			},
			onElicitation: B,
			onLifecycle: recordUnsupportedNativeActionEvidence,
			onEvent: async (t) => {
				L.emitAcpRuntimeEvent({
					...z,
					toolTracker: R,
					...e.abortSignal ? { abortSignal: e.abortSignal } : {},
					event: t
				});
				if (t.type === "done") {
					U = t.stopReason;
					W = t.status;
				}
				await j.onEvent(t);
			}
		};
		await r.withCurrent(() => {
			if (getAdmittedRunDelegatedAuthority(F) === void 0) throw new Error("ACP turn admission ended before input dispatch.");
			X = true;
			return s.runTurn(V);
		});
		await j.flush();
		await E.flushBlockText();
		if (W !== "cancelled" && !e.abortSignal?.aborted) T = await finalizeAcpTurnOutput({
			preparedTtsPreferences: C,
			cfg: e.cfg,
			sessionKey: l,
			agentId: d,
			delivery: E,
			inboundAudio: e.inboundAudio,
			sessionTtsAuto: e.sessionTtsAuto,
			ttsChannel: e.ttsChannel,
			ttsAccountId: b,
			shouldDeferVisibleTextForTts: w,
			shouldEmitResolvedIdentityNotice: x,
			abortSignal: e.abortSignal
		}) || T;
		if (W === "cancelled" || e.abortSignal?.aborted) {
			T = await deliverDeferredTextFallback() || T;
			await persistTranscript(await E.resolveAccumulatedDeliveredTranscriptText());
			T = E.hasPendingAnswerDelivery() || E.hasPendingFinalTtsMedia() || E.hasDeliveredFinalReply() || T;
			const t = E.applyRoutedCounts(e.dispatcher.getQueuedCounts());
			e.recordProcessed("completed", { reason: "acp_aborted" });
			e.markIdle("message_aborted");
			emitAuditTerminal();
			return {
				queuedFinal: T,
				counts: t
			};
		}
		await persistTranscript(E.getAccumulatedTranscriptText());
		const G = finishAttempt(T);
		emitAuditTerminal();
		return G;
	} catch (t) {
		e.turnAdoption?.assertCurrent();
		const n = toAcpRuntimeError({
			error: t,
			fallbackCode: "ACP_TURN_FAILED",
			fallbackMessage: "ACP turn failed before completion."
		});
		emitAuditTerminal(n);
		await j.flush();
		await E.flushBlockText();
		T = await deliverDeferredTextFallback() || T;
		await a({
			targetSessionKey: l,
			error: n
		});
		const r = formatAcpRuntimeErrorText(n);
		const i = E.getAccumulatedTranscriptText();
		const o = await E.deliver("final", {
			text: r,
			isError: true
		});
		if (X) await persistTranscript(i ? `${i}\n\n${r}` : r);
		T = T || o;
		return finishAttempt(T, n);
	} finally {
		if (Q) closeAdmittedRunDelegatedAuthority(Q);
	}
}
//#endregion
export { tryDispatchAcpReplyCore };