openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4,142 lines • 154 kB
JavaScript
import { c as normalizeOptionalLowercaseString, g as readStringValue, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { i as consumeRootOptionToken } from "./cli-root-options-xlQx6o4R.mjs";
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { a as asOptionalRecord, i as asOptionalObjectRecord, o as asRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs";
import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs";
import { b as uniqueStrings, r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { g as extractErrorHttpStatus } from "./redact-Mj7pppxC.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { i as createAbortError } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as appendRegularFile } from "./fs-safe-BbWvmdVn.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { d as normalizeUsage, i as deriveSessionTotalTokens, l as makeZeroUsageSnapshot, o as hasNonzeroUsage, s as hasObservedModelUsage } from "./usage-CHLnzpJG.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import { l as getAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs";
import { _ as readAgentAssistantSource, a as emitAgentEvent, l as emitAgentEventWithAssistantSourceIfCurrent, n as bindAgentAssistantSource, s as emitAgentEventForRunContext, u as emitAgentRunOutputTokens } from "./agent-events-BdfWYmot.mjs";
import { r as splitShellArgs, t as hasTopLevelShellControlOperator } from "./shell-argv-CjhAXJXb.mjs";
import { n as extractTextFromChatContent } from "./chat-content-Dkam4EQe.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import { t as isDeliverableMessageChannel } from "./message-channel-normalize-CFHSufeo.mjs";
import { c as parseAssistantTextSignature, p as resolveAssistantMessagePhase, u as readAssistantTextBlocksForPhase } from "./chat-message-content-DNUdbbJ8.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { u as recordSessionCompacted } from "./session-state-events-ChAYnzQG.mjs";
import { t as isProviderRefusalAssistantError } from "./diagnostics-36a9D_mQ.mjs";
import "./tool-policy-BR4v75RA.mjs";
import { r as isAutomationsToolName } from "./automations-tool-name-DNRDs0aJ.mjs";
import { c as normalizeToolPolicyName } from "./tool-policy-shared-BHvBopvF.mjs";
import { n as createToolValidationErrorSummary, r as hasTerminalControlCharacter, s as summarizeToolValidationError } from "./tool-error-summary-BTwB17cj.mjs";
import { o as hasReplyPayloadContent } from "./payload-Cab4FCxl.mjs";
import { A as shouldKeepPayloadDuringSilentTurn, C as markReplyPayloadForSourceSuppressionDelivery, c as getReplyPayloadMetadata, k as setReplyPayloadMetadata, n as addReplyPayloadMediaFailures, o as copyReplyPayloadMetadata, r as appendReplyMediaFailures } from "./reply-payload-k5WsQWxi.mjs";
import { h as readAutomationDisplayState } from "./session-event-handoff-CC7Ui3SA.mjs";
import { T as setInternalToolTurnCompletion, x as getInternalToolTurnCompletion } from "./internal-hooks-Ch3rqxs-.mjs";
import { n as consumeToolExecutionNotStarted, r as markToolExecutionNotStarted } from "./tool-effect-receipt-BbbEwqBS.mjs";
import { i as isToolCallBlockType } from "./tool-block-contract-BsnlYLrK.mjs";
import { n as trimTextPreservingCode } from "./trim-code-text-Dr7f3RLr.mjs";
import { n as parseInlineDirectives } from "./directive-tags-batch-D0CxS-zY.mjs";
import { a as prepareAgentRunTerminalReply } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { n as canReuseMarkdownOwnershipForAppend, r as findCodeOwnership } from "./code-regions-CfNY0afj.mjs";
import { a as parseReasoningTagAt, n as findMarkdownCodeRegions, s as scanReasoningTags } from "./reasoning-tags-DL3sP_9k.mjs";
import { r as createTextProjection, s as trimTextFilter, t as applyTextFilters } from "./text-projection-DwmQz6_O.mjs";
import { t as toolCallXmlTextFilter } from "./tool-call-xml-DSl4fabj.mjs";
import { t as findNativeToolMarkerTextBlocks } from "./native-tool-marker-B7dSiPNn.mjs";
import { _ as downgradedToolCallTextFilter, g as findFinalTagMatches, n as assistantVisibleTextFilters, o as plainToolCallPreviewTextFilter, p as hasOrphanReasoningCloseBoundary, r as hasUnsettledPlainTextToolCall, v as stripDowngradedToolCallText } from "./assistant-visible-text-fPqh5m9O.mjs";
import { i as sanitizeUserFacingText } from "./user-facing-text-Dqp3fcZx.mjs";
import { A as parseExecApprovalResultText } from "./user-copy-DFvWpx47.mjs";
import { C as projectChatErrorDetail } from "./logs-chat-C8_2M86E.mjs";
import { t as findDirectiveCodePrefix } from "./directive-tags-C1p_t1Fd.mjs";
import { t as applyAssistantDeliveryDirectives } from "./transcript-assistant-delivery-Ddb-cbeg.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { c as consumeTrackedToolExecutionStarted, i as consumeAdjustedParamsForToolCall, l as peekAdjustedParamsForToolCall, o as consumePreExecutionBlockedToolCall, s as consumeStructuredReplaySafeToolCall } from "./agent-tools.before-tool-call.state-C5F7vnXY.mjs";
import "./reply-payload-CwASJYas.mjs";
import { a as resolveSendableOutboundReplyParts } from "./reply-payload-parts-0Tn7wkpR.mjs";
import { n as splitTrailingDirective, t as createStreamingDirectiveAccumulator } from "./streaming-directives-C1RBdaQG.mjs";
import { a as readToolResultDetails, n as isToolResultError } from "./tool-result-error-B2GHe83l.mjs";
import { a as isMessagingToolTargetEvidenceAction, i as isMessagingToolSendAction, n as isMessagingTool, o as isPluginNativeMessagingTool } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { t as parseReplyDirectives } from "./reply-directives-BMfUGuku.mjs";
import { o as detectToolCallShapedText } from "./src-C9d8oFHe.mjs";
import { n as createInlineCodeState, t as buildCodeSpanIndex } from "./code-spans-axVMwnI-.mjs";
import { n as classifyAssistantFailoverReason } from "./assistant-message-failures-Cv3Qnsh5.mjs";
import { r as classifyCompactionReason } from "./compact-reasons-DCGXQXOD.mjs";
import { n as cancelAskUserPromptDelivery } from "./ask-user-tool-C-rRerhD.mjs";
import { t as formatToolAggregate } from "./tool-meta-BPR-w7I7.mjs";
import { t as resolveFileMutationToolName } from "./tool-mutation-names-DGg7FEBx.mjs";
import { s as readMcpAppChannelView } from "./mcp-ui-resource-3UHFH-eE.mjs";
import { a as normalizeAcceptedSessionSpawnResult, n as hasCompletionMessageSessionSpawn, t as hasAcceptedSessionSpawn } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { t as updateLiveEditDiffProgress } from "./embedded-agent-live-edit-diff-CXQyk4M9.mjs";
import { r as projectAgentToolActivity } from "./agent-activity-events-BvMnPRzr.mjs";
import { o as markdownToIR } from "./ir-Ctdn8mF1.mjs";
import { t as stripStaleAssistantUsageBeforeLatestCompaction } from "./compaction-usage-DmR900jF.mjs";
import { a as resolveAgentAssistantTurnId, i as getAgentToolInputScope } from "./tool-execution-context-D0eUSg2-.mjs";
import { f as sessionManagerReadTranscriptStart } from "./session-manager-DuaaMI5O.mjs";
import { n as setSessionModelUsageSink } from "./session-model-usage-uTeV8br8.mjs";
import { a as extractAssistantCommentaryText, c as extractEmbeddedAssistantText, f as isAssistantMessage, i as createThinkingTagStreamState, l as extractThinkingFromTaggedStream, m as promoteThinkingTagsToBlocks, n as createAssistantThinkingStream, o as extractAssistantThinking, p as prepareAssistantVisibleText, r as createAssistantVisibleStreamText, s as extractAssistantVisibleText, t as createAssistantStreamBlockState, u as extractThinkingFromTaggedText } from "./embedded-agent-utils-CRYA6mcb.mjs";
import { n as createSourceReplyBatchCompletion } from "./tool-source-reply-completion-CusGAPIB.mjs";
import { t as EmbeddedBlockChunker } from "./embedded-agent-block-chunker-D13d7ur3.mjs";
import { n as collectAgentInternalEventMedia } from "./internal-events-BmV3sycH.mjs";
import { i as hasCommittedMessagingToolDeliveryEvidence } from "./delivery-evidence-CqR4m_Hg.mjs";
import { r as getCoreTtsToolResultMediaUrls } from "./tts-tool-result-provenance-DWw-9hLr.mjs";
import { i as toNormalizedUsage, r as mergeUsageIntoAccumulator, t as createUsageAccumulator } from "./usage-accumulator-CWIvkatR.mjs";
import { u as resolveFinalAssistantVisibleText } from "./helpers-W-meNuDY.mjs";
import { n as buildTextObservationFields, t as buildApiErrorObservationFields } from "./embedded-agent-error-observation-CgMe33_n.mjs";
import { c as readEmbeddedMessageDeliveryFact, r as isDeliveredCoreCurrentChannelWidgetResult } from "./embedded-agent-message-delivery-ClVuBxqZ.mjs";
import { i as resolveMessageToolSourceReplyFinal, n as isDeliveredMessagingToolResult, r as readMessageToolSourceReplyText, t as isDeliveredMessageToolOnlySourceReplyResult } from "./embedded-agent-message-tool-source-reply-BLgXJNuN.mjs";
import { n as mergeEmbeddedRunReplayState, t as createEmbeddedRunReplayState } from "./replay-state-Amo8jvsa.mjs";
import { t as projectProgressCardChannelUpdate } from "./progress-card-channel-summary-CkIMdtP9.mjs";
import { a as isDeliveredMessagingToolSendToCurrentSource, n as extractMessagingToolSendResult, r as extractMessagingToolSourceReplyPayload, t as extractMessagingToolSend } from "./embedded-agent-messaging-extraction-C5OCu-VM.mjs";
import { t as captureToolAuthoredSourceReply } from "./embedded-agent-tool-authored-source-reply-D2Px90_h.mjs";
import { a as extractToolResultText, c as prepareToolResult, d as truncateLiveExecOutput, i as extractToolErrorMessage, l as readAsyncStartedTaskIds, n as capLiveExecResult, o as isAsyncStartedToolResult, r as extractToolErrorCode, s as isToolResultTimedOut, t as buildToolLifecycleErrorResult, u as sanitizeToolResult } from "./embedded-agent-tool-results-DbtxSr9V.mjs";
import { i as filterToolResultMediaUrls, n as collectMessagingMediaUrlsFromToolResult, r as extractToolResultMediaArtifact, t as collectMessagingMediaUrlsFromRecord } from "./embedded-agent-tool-media-Bzv7p-IE.mjs";
import { n as isMidTurnMaintenanceAssistantSignal } from "./midturn-precheck-DByie_kO.mjs";
import { o as parseJsonMessageParam } from "./message-action-params-DnKd238O.mjs";
import { n as isResumingAlreadyPendingSessionsYieldResult } from "./sessions-yield-tool-DjKlbpxP.mjs";
import { t as isCronAddAction } from "./tool-result-facts-C9Xta0St.mjs";
import { t as runBestEffortCallback } from "./embedded-agent-subscribe.callback-DQMmolWU.mjs";
import { i as resolveCurrentSourceMessagingToolPartial, n as isMessagingToolDuplicateNormalized, r as normalizeTextForComparison } from "./messaging-dedupe-ChHNHfTw.mjs";
import { E as isIncompleteTerminalAssistantTurn, M as hasAsyncActivity, N as hasAttemptTerminalState, a as buildToolCallSummary, d as emitTrackedItemEvent, f as finalizeToolActivity, h as toolStartData, i as buildCommandItemTitle, k as sanitizeForConsole, l as emitAgentEventCallbackBestEffort, m as isExecToolName, o as buildToolStartKey, p as handleToolExecutionStart, r as buildCommandItemId, s as cleanupRunToolStartData, t as createToolTerminalObserver, u as emitToolActivityEvent } from "./tool-terminal-outcome-I8TmHIh2.mjs";
import { i as formatUserFacingAssistantErrorText, t as GENERIC_ASSISTANT_ERROR_TEXT } from "./error-text-mmb9Hrdz.mjs";
import { t as consumeEmbeddedToolReceipt } from "./tool-send-receipts-DPctyfdu.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import { OPENAI_RESPONSES_APIS } from "@openclaw/ai/internal/openai-responses-payload-policy";
//#region src/agents/embedded-agent-runner/run/message-tool-terminal.ts
function argsRecordForToolCall(e) {
return asOptionalRecord(e.args) ?? asOptionalRecord(e.toolCall.arguments) ?? {};
}
/**
* Admits a complete batch of direct tool-authored replies from the finalized
* message results, after message_end extensions and persistence have settled.
* Any failed or unhandled sibling leaves the entire batch with the model; no
* partial reply is queued that could hide the continuation or its failure.
*/
function installToolAuthoredSourceReplyTerminalHook(e) {
const t = e.sourceReplyCapableToolNames;
if (!t?.size) return () => {};
const n = getInternalToolTurnCompletion(e.agent);
const complete = (r) => {
const i = n?.(r) === true;
const a = [];
for (const n of r.toolResults) {
if (n.isError || isToolResultError(n)) return i;
if (!t.has(normalizeToolPolicyName(n.toolName))) {
if (r.terminalToolCallIds.has(n.toolCallId)) continue;
return i;
}
const o = captureToolAuthoredSourceReply({
result: n,
toolCallId: n.toolCallId,
idempotencyScope: resolveAgentAssistantTurnId(r.message) ?? e.idempotencyScope
});
if (!o) {
if (asOptionalRecord(readToolResultDetails(n)?.sourceReply)?.final !== false && r.terminalToolCallIds.has(n.toolCallId)) continue;
return i;
}
a.push({
...o,
toolAuthoredForTurnId: resolveAgentAssistantTurnId(r.message)
});
}
if (a.length === 0) return i;
e.onSourceReplies(a);
return true;
};
setInternalToolTurnCompletion(e.agent, complete);
return () => {
if (getInternalToolTurnCompletion(e.agent) === complete) setInternalToolTurnCompletion(e.agent, n);
};
}
function installMessageToolTerminalHook(e) {
const t = /* @__PURE__ */ new Set();
const n = /* @__PURE__ */ new WeakSet();
const r = createSourceReplyBatchCompletion();
const i = getInternalToolTurnCompletion(e.agent);
setInternalToolTurnCompletion(e.agent, (e) => {
const n = r.complete(e.toolResults, t.has(e.inputScope), e.inputScope);
t.clear();
return i?.(e) === true || n;
});
const a = e.agent.afterToolCall?.bind(e.agent);
e.agent.afterToolCall = async (i, o) => {
const s = getAgentToolInputScope(i);
r.observe(i.result);
const c = i.toolCall.name;
const l = argsRecordForToolCall(i);
const u = resolveMessageToolSourceReplyFinal(l, e.messageToolFinalByDefault);
const d = c === "message" && e.currentProvider && typeof l.provider !== "string" && typeof l.channel !== "string" ? {
...l,
provider: e.currentProvider
} : l;
const f = extractMessagingToolSend(c, d, e);
const p = f && extractMessagingToolSendResult(f, i.result);
const isDelivered = (t) => isDeliveredMessageToolOnlySourceReplyResult({
sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
toolName: c,
args: l,
result: t ?? i.result,
hookResult: i.result,
isError: t?.isError ?? i.isError,
allowExplicitSourceRoute: isDeliveredMessagingToolSendToCurrentSource({
...e,
send: p,
deliveredPayload: i.result
})
});
let m = isDelivered();
let h;
try {
h = await a?.(i, o);
} finally {
m ||= isDelivered(h);
if (m) {
if (s) n.add(s);
if (u && s) t.add(s);
e.onDeliveredSourceReply?.();
}
}
const g = s !== void 0 && n.has(s) && !i.isError && isResumingAlreadyPendingSessionsYieldResult(c, i.result);
if (g) t.add(s);
return m && u || g ? {
...h,
terminate: true
} : h;
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.messages.replies.ts
/**
* Owns pending assistant reply directives and tool-media handoff.
*/
function hasReplyDirectiveMetadata(e) {
return Boolean(e && (e.audioAsVoice || e.replyToId || e.replyToTag || e.replyToCurrent));
}
/** Moves queued tool media into a non-reasoning assistant reply payload. */
function consumePendingToolMediaIntoReply(e, t) {
if (t.isReasoning) return t;
const n = readPendingToolMediaReply(e);
if (!n) return t;
let r;
if ((t.mediaUrls ?? []).some((e) => e.trim().length > 0)) {
const i = new Map((n.mediaUrls ?? []).map((e, t) => [e, n.attachments?.[t] ?? {}]));
const a = (t.mediaUrls ?? []).map((e) => i.get(e.trim()) ?? {});
const o = (t.mediaUrls?.length ?? 0) > 0 && (t.mediaUrls ?? []).every((e) => i.has(e.trim()));
const s = t.attachments?.length || a.every((e) => Object.keys(e).length === 0) ? t : {
...t,
attachments: a
};
r = o && (t.mediaUrls ?? []).every((t) => e.pendingToolMediaTrustByUrl.get(t.trim()) === true) ? {
...s,
trustedLocalMedia: true
} : s;
} else r = {
...t,
...n,
audioAsVoice: t.audioAsVoice || n.audioAsVoice || void 0,
...t.trustedLocalMedia ? { trustedLocalMedia: true } : {}
};
e.pendingToolMediaUrls = [];
e.pendingToolMediaAttachments = [];
e.pendingToolMediaTrustByUrl.clear();
e.pendingToolAudioAsVoice = false;
return r;
}
/** Restores reserved tool media after its outbound delivery was rejected. */
function restorePendingToolMediaReply(e, t) {
const n = e.pendingToolMediaUrls;
const r = e.pendingToolMediaAttachments ?? [];
const i = t.mediaUrls ?? [];
const a = t.attachments ?? [];
const o = new Set(i);
e.pendingToolMediaUrls = [...i, ...n.filter((e) => !o.has(e))];
e.pendingToolMediaAttachments = [...i.map((e, t) => a[t] ?? {}), ...n.flatMap((e, t) => o.has(e) ? [] : [r[t] ?? {}])];
for (const [n, r] of i.entries()) if (t.trustedLocalMedia || a[n]?.trustedLocalMedia) e.pendingToolMediaTrustByUrl.set(r, true);
else if (!e.pendingToolMediaTrustByUrl.has(r)) e.pendingToolMediaTrustByUrl.set(r, false);
e.pendingToolAudioAsVoice ||= t.audioAsVoice === true;
e.pendingToolMediaDeliveryFailed = true;
}
/** Reads queued tool media without clearing it. */
function readPendingToolMediaReply(e) {
if (e.pendingToolMediaUrls.length === 0 && !e.pendingToolAudioAsVoice) return null;
const t = /* @__PURE__ */ new Set();
const n = [];
const r = [];
for (const [i, a] of e.pendingToolMediaUrls.entries()) {
if (t.has(a)) continue;
t.add(a);
n.push(a);
const { trustedLocalMedia: o, ...s } = e.pendingToolMediaAttachments?.[i] ?? {};
r.push({
...s,
...e.pendingToolMediaTrustByUrl.get(a) === true ? { trustedLocalMedia: true } : {}
});
}
const i = r.some((e) => Object.keys(e).length > 0) ? r : void 0;
const a = n.length > 0 && n.every((t) => e.pendingToolMediaTrustByUrl.get(t) === true);
return {
mediaUrls: n.length ? n : void 0,
attachments: i,
audioAsVoice: e.pendingToolAudioAsVoice || void 0,
...a ? { trustedLocalMedia: true } : {}
};
}
function recordPendingAssistantReplyDirectives(e, t, n) {
if (!t) return;
const r = e.pendingAssistantReplyDirectives;
const i = Boolean(t.audioAsVoice || r?.audioAsVoice && n && n.current > (r.audioDirectiveStart ?? 0));
if (!i && !hasReplyDirectiveMetadata(t)) {
e.pendingAssistantReplyDirectives = void 0;
return;
}
e.pendingAssistantReplyDirectives = {
audioAsVoice: i || void 0,
...i && n ? { audioDirectiveStart: r?.audioDirectiveStart ?? n.previous } : {},
replyToId: t.replyToId,
replyToTag: t.replyToTag || void 0,
replyToCurrent: t.replyToCurrent || void 0
};
}
/** Merges pending reply directives into one reply payload and clears them. */
function consumePendingAssistantReplyDirectivesIntoReply(e, t) {
if (t.isReasoning || !e.pendingAssistantReplyDirectives) return t;
const n = e.pendingAssistantReplyDirectives;
e.pendingAssistantReplyDirectives = void 0;
return {
...t,
audioAsVoice: t.audioAsVoice || n.audioAsVoice || void 0,
replyToId: t.replyToId ?? n.replyToId,
replyToTag: Boolean(t.replyToTag || n.replyToTag) || void 0,
replyToCurrent: Boolean(t.replyToCurrent || n.replyToCurrent) || void 0
};
}
function hasAssistantVisibleReply(e) {
return resolveSendableOutboundReplyParts(e).hasContent || Boolean(e.audioAsVoice);
}
/** Exact tool-owned media that the managed WebChat pipeline may hide from display text. */
function resolveManagedStreamMediaUrls(e, t) {
return uniqueStrings(t.filter((t) => e.pendingToolMediaTrustByUrl.get(t.trim()) === true));
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.lifecycle.ts
function emitCompactionAgentEvent(e, t) {
const n = {
stream: "compaction",
data: t
};
emitAgentEvent({
runId: e.params.runId,
...n
});
runBestEffortCallback({
label: "compaction agent event",
log: e.log,
callback: () => e.params.onAgentEvent?.(n)
});
}
function runBestEffortCompactionHook(e, t) {
if (e.state.unsubscribed || e.params.isTerminalAborted?.()) return;
const n = getGlobalHookRunner();
const r = t === "before" ? "before_compaction" : "after_compaction";
if (!n?.hasHooks(r)) return;
const i = {
messageCount: e.params.session.messages?.length ?? 0,
sessionFile: e.params.session.sessionFile
};
const a = { sessionKey: e.params.sessionKey };
(t === "before" ? n.runBeforeCompaction({
...i,
messages: e.params.session.messages
}, a) : n.runAfterCompaction({
...i,
compactedCount: e.getCompactionCount()
}, a)).catch((t) => {
e.log.warn(`${r} hook failed: ${String(t)}`);
});
}
function handleCompactionStart(e, t) {
const n = t.reason;
const r = n === "manual" || n === "threshold" || n === "overflow" ? n : "threshold";
const i = r === "manual" ? "manual compaction" : "auto-compaction";
e.state.compactionInFlight = true;
e.state.livenessState = "paused";
e.ensureCompactionPromise();
e.log.info(`embedded run ${i} start`, {
event: "embedded_run_compaction_start",
runId: e.params.runId,
reason: r,
consoleMessage: `embedded run ${i} start: runId=${e.params.runId} reason=${r}`
});
emitCompactionAgentEvent(e, {
phase: "start",
...t.itemId ? { itemId: t.itemId } : {}
});
if (!t.hooksHandled) runBestEffortCompactionHook(e, "before");
}
function handleCompactionEnd(e, t) {
const n = t.reason;
const r = n === "manual" ? "manual compaction" : "auto-compaction";
const i = t.outcome;
e.state.compactionInFlight = false;
const a = i.status === "completed";
const o = a && i.willRetry;
let s;
if (a) {
e.incrementCompactionCount();
e.noteCompactionTokensAfter(i.tokensAfter);
const t = e.getCompactionCount();
if (e.params.sessionPersistence !== "detached") s = recordSessionCompacted({
sessionKey: e.params.sessionKey,
operationId: `${e.params.runId}:${t}`,
agentId: e.params.agentId,
runId: e.params.runId
});
e.log.info(`embedded run ${r} complete`, {
event: "embedded_run_compaction_end",
runId: e.params.runId,
reason: n,
completed: true,
willRetry: o,
compactionCount: t,
consoleMessage: `embedded run ${r} complete: runId=${e.params.runId} reason=${n} compactionCount=${t} willRetry=${o}`
});
if (e.params.compactionCountOwner !== "caller" && e.params.sessionPersistence !== "detached") import("./embedded-agent-subscribe.handlers.compaction.runtime.js").then(({ default: n }) => n({
sessionKey: e.params.sessionKey,
agentId: e.params.agentId,
configStore: e.params.config?.session?.store,
observedCompactionCount: t
})).catch((t) => {
e.log.warn(`late compaction count reconcile failed: ${String(t)}`);
});
}
if (o) {
e.noteCompactionRetry();
e.resetForCompactionRetry();
} else {
if (i.status !== "aborted") e.state.livenessState = "working";
e.maybeResolveCompactionWait();
const t = e.params.session.messages;
if (a) stripStaleAssistantUsageBeforeLatestCompaction(t, {
mutate: true,
whenMissingCompactionSummary: "zeroAssistantUsage"
});
}
const c = i.status === "skipped" || i.status === "failed" ? i.reason : void 0;
if (!a) {
const t = c ? classifyCompactionReason(c) : "aborted";
const a = {
event: "embedded_run_compaction_end",
runId: e.params.runId,
reason: n,
outcome: i.status,
completed: false,
willRetry: false,
reasonClass: t,
consoleMessage: `embedded run ${r} ${i.status}: runId=${e.params.runId} reason=${t}`
};
const o = i.status === "aborted" || i.status === "skipped" && (t === "no_compactable_entries" || t === "below_threshold" || t === "already_compacted");
e.log[o ? "info" : "warn"](`embedded run ${r} ${i.status}`, a);
}
emitCompactionAgentEvent(e, {
phase: "end",
...t.itemId ? { itemId: t.itemId } : {},
completed: a,
willRetry: o,
outcome: i.status,
...a && i.qualityDegraded ? { qualityDegraded: true } : {},
...c ? { reason: c } : {}
});
if (a && !o && !t.hooksHandled) runBestEffortCompactionHook(e, "after");
return s;
}
function runTerminalHook(e, t) {
let n;
try {
n = e();
} catch (e) {
t(e);
return;
}
return isPromiseLike(n) ? Promise.resolve(n).catch((e) => {
t(e);
}) : n;
}
function emitLifecycleAgentEvent(e, t, n = t) {
emitAgentEvent({
runId: e.params.runId,
...e.params.sessionKey ? { sessionKey: e.params.sessionKey } : {},
...e.params.sessionId ? { sessionId: e.params.sessionId } : {},
...e.params.agentId ? { agentId: e.params.agentId } : {},
...e.params.lifecycleGeneration ? { lifecycleGeneration: e.params.lifecycleGeneration } : {},
stream: "lifecycle",
data: n
});
runBestEffortCallback({
label: "lifecycle agent event",
log: e.log,
callback: () => e.params.onAgentEvent?.({
stream: "lifecycle",
data: t
})
});
}
function handleAgentStart(e) {
e.state.deferBlockReplyDelivery = typeof e.params.onBeforeTerminalDelivery === "function" && e.params.deferTerminalDelivery !== false;
emitLifecycleAgentEvent(e, {
phase: "start",
startedAt: Date.now()
});
}
function handleAgentEnd(e, t) {
e.state.liveEditDiffStateById.clear();
const n = e.state.lastAssistant;
const r = isMidTurnMaintenanceAssistantSignal(n);
const i = isAssistantMessage(n) && n.stopReason === "error" && !r;
let a;
let o;
const s = e.state.assistantTexts.some((e) => hasAssistantVisibleReply({ text: e }));
const c = isAssistantMessage(n) && n.stopReason !== "error" && n.stopReason !== "aborted" ? resolveFinalAssistantVisibleText(n) : void 0;
const l = s || hasAssistantVisibleReply({ text: c ?? "" });
const u = e.state.hadDeterministicSideEffect === true || hasCommittedMessagingToolDeliveryEvidence(e.state) || hasAcceptedSessionSpawn(e.state.acceptedSessionSpawns) || (e.state.successfulCronAdds ?? 0) > 0;
const d = e.state.deferredBlockReplies.flatMap((e) => e.mediaUrls ?? []);
const f = hasAttemptTerminalState({
yieldDetected: e.state.yielded,
didSendDeterministicApprovalPrompt: e.state.deterministicApprovalPromptSent,
toolMediaUrls: [...e.state.pendingToolMediaUrls, ...d],
toolAudioAsVoice: e.state.pendingToolAudioAsVoice || e.state.deferredBlockReplies.some((e) => e.audioAsVoice),
hasToolMediaBlockReply: e.state.hasToolMediaBlockReply,
didDeliverSourceReplyViaMessageTool: e.state.messageToolOnlySourceReplyDelivered || e.params.hasDeliveredMessageToolOnlySourceReply?.() === true,
messagingToolSourceReplyPayloads: e.state.messagingToolSourceReplyPayloads,
messagingToolSentTexts: e.state.messagingToolSentTexts,
messagingToolSentMediaUrls: e.state.messagingToolSentMediaUrls,
messagingToolSentTargets: e.state.messagingToolSentTargets,
successfulCronAdds: e.state.successfulCronAdds,
acceptedSessionSpawns: e.state.acceptedSessionSpawns,
toolMetas: e.state.toolMetas
});
const p = u || e.state.replayState.hadPotentialSideEffects;
const m = isIncompleteTerminalAssistantTurn({
hasAssistantVisibleText: l,
hasTerminalOutput: f,
lastAssistant: isAssistantMessage(n) ? n : null
});
const h = e.state.replayState.replayInvalid || m ? true : void 0;
const g = r ? e.state.livenessState : i ? "blocked" : h && !u && (!l || m) ? "abandoned" : e.state.livenessState;
const _ = e.state.livenessState === "working" ? g : e.state.livenessState;
if (i && n) {
const t = n.errorMessage?.trim();
const r = classifyAssistantFailoverReason(n, { providerOwner: e.params.providerOwner ?? null });
const i = formatUserFacingAssistantErrorText(n, {
cfg: e.params.config,
sessionKey: e.params.sessionKey,
agentId: e.params.agentId,
provider: n.provider,
model: n.model,
providerOwner: e.params.providerOwner
});
const s = buildApiErrorObservationFields(t, {
provider: n.provider,
providerOwner: e.params.providerOwner,
code: n.errorCode
});
a = buildTextObservationFields(i, { provider: n.provider }).textPreview ?? "LLM request failed.";
o = projectChatErrorDetail({
provider: n.provider,
model: n.model,
failoverReason: r,
...s,
httpStatus: extractErrorHttpStatus(t ?? "")?.code
});
const c = sanitizeForConsole(e.params.runId) ?? "-";
const l = sanitizeForConsole(n.model) ?? "unknown";
const u = sanitizeForConsole(n.provider) ?? "unknown";
e.log.warn("embedded run agent end", {
event: "embedded_run_agent_end",
tags: [
"error_handling",
"lifecycle",
"agent_end",
"assistant_error"
],
runId: e.params.runId,
isError: true,
failoverReason: r,
model: n.model,
provider: n.provider,
rawErrorHash: s.rawErrorHash,
rawErrorFingerprint: s.rawErrorFingerprint,
httpCode: s.httpCode,
providerRuntimeFailureKind: s.providerRuntimeFailureKind,
providerErrorType: s.providerErrorType,
requestIdHash: s.requestIdHash,
consoleMessage: `embedded run agent end: runId=${c} isError=true model=${l} provider=${u} failoverReason=${r ?? "unknown"}`
});
}
const emitLifecycleTerminal = () => {
finalizeToolActivity(e);
const t = e.params.resolveTerminalStopReason?.() ?? e.state.terminalStopReason ?? (!i && !r && isAssistantMessage(n) ? n.stopReason : void 0);
const s = e.state.terminalAborted ?? e.params.isTerminalAborted?.();
const c = s === true && e.state.lastToolError ? summarizeToolValidationError(e.state.lastToolError) : void 0;
const l = {
phase: e.params.terminalLifecyclePhase === "finishing" ? "finishing" : i ? "error" : "end",
...i ? { error: a ?? "LLM request failed." } : {},
...o ? { errorObservation: o } : {},
...t ? { stopReason: t } : {},
...e.state.yielded === true ? { yielded: true } : {},
...e.state.timeoutPhase ? { timeoutPhase: e.state.timeoutPhase } : {},
...e.state.providerStarted !== void 0 ? { providerStarted: e.state.providerStarted } : {},
...s !== void 0 ? { aborted: s } : {},
...c ? { toolErrorSummary: c } : {},
..._ ? { livenessState: _ } : {},
...h ? { replayInvalid: h } : {}
};
emitLifecycleAgentEvent(e, l, {
...l,
endedAt: Date.now()
});
};
const finalizeAgentEnd = () => {
if (e.state.pendingCompactionRetry > 0) e.resolveCompactionRetry();
else e.maybeResolveCompactionWait();
};
const flushPendingMediaAndChannel = () => {
if (e.params.onBlockReply && !e.state.pendingToolMediaDeliveryFailed) {
const t = readPendingToolMediaReply(e.state);
if (t && hasAssistantVisibleReply(t)) e.emitBlockReply(t);
}
const flushChannel = () => {
const t = e.params.onBlockReplyFlush?.({ reason: "terminal" });
return isPromiseLike(t) ? t : void 0;
};
const t = e.flushBlockReplyBuffer();
return isPromiseLike(t) ? t.then(flushChannel) : flushChannel();
};
const rethrowAfterLifecycleTerminal = (e) => {
const t = emitLifecycleTerminalOnce();
if (isPromiseLike(t)) return Promise.resolve(t).then(() => {
throw e;
});
throw e;
};
let v = false;
const emitLifecycleTerminalOnce = () => {
if (v) return;
v = true;
const t = runTerminalHook(() => e.params.onBeforeLifecycleTerminal?.(), (t) => e.log.debug(`before lifecycle terminal failed: ${String(t)}`));
if (isPromiseLike(t)) return Promise.resolve(t).then(emitLifecycleTerminal);
emitLifecycleTerminal();
};
const applyBeforeTerminalDecision = (t) => {
if (t?.suppressTerminalDelivery === true) {
e.clearAssistantStream();
e.clearDeferredBlockReplies();
finalizeAgentEnd();
return;
}
if (t?.continueCurrentTurn === true) {
e.releaseDeferredReplies();
finalizeAgentEnd();
return e.flushBlockReplyBuffer();
}
try {
e.releaseDeferredReplies();
const t = e.flushBlockReplyBuffer({ final: true });
finalizeAgentEnd();
const n = isPromiseLike(t) ? Promise.resolve(t).then(flushPendingMediaAndChannel) : flushPendingMediaAndChannel();
if (isPromiseLike(n)) return Promise.resolve(n).then(emitLifecycleTerminalOnce, rethrowAfterLifecycleTerminal);
return emitLifecycleTerminalOnce();
} catch (e) {
return rethrowAfterLifecycleTerminal(e);
}
};
const y = runTerminalHook(() => {
const r = e.state.keptAnswer?.assistant ?? n;
return e.params.onBeforeTerminalDelivery?.({
messages: t?.messages ?? [],
willRetry: t?.willRetry === true,
...t?.assistantEntryId ? { assistantEntryId: t.assistantEntryId } : {},
...r ? { lastAssistant: r } : {},
assistantTexts: e.state.assistantTexts,
hasAssistantVisibleText: l,
isError: i,
incompleteTerminalAssistant: m,
hadDeterministicSideEffect: p,
hasPendingContinuation: e.state.yielded || e.state.deterministicApprovalPromptPending || e.state.deterministicApprovalPromptSent || hasCompletionMessageSessionSpawn(e.state.acceptedSessionSpawns) || hasAsyncActivity(e.state.toolMetas)
});
}, (t) => e.log.warn(`before terminal delivery failed: ${String(t)}`));
if (isPromiseLike(y)) return Promise.resolve(y).then(applyBeforeTerminalDecision);
return applyBeforeTerminalDecision(y);
}
//#endregion
//#region src/agents/embedded-agent-subscribe.assistant-snapshot.ts
/** Preserve native clone semantics and share only previously detached reasoning. */
function snapshotAssistantMessage(e, t) {
const n = structuredClone(e);
return {
snapshot: n,
reasoning: {
source: e,
thinking: Array.isArray(n.content) ? n.content.map((n, r) => {
if (n?.type !== "thinking" || typeof n.thinking !== "string") return;
const i = t?.source === e ? t.thinking[r] : void 0;
if (i !== void 0 && i === n.thinking) n.thinking = i;
return n.thinking;
}) : []
}
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.messages.stream.ts
function isSubscribeTranscriptOnlyOpenClawAssistantMessage(e) {
if (!e || e.role !== "assistant") return false;
const t = normalizeOptionalString(e.provider) ?? "";
const n = normalizeOptionalString(e.model) ?? "";
return t === "openclaw" && (n === "delivery-mirror" || n === "gateway-injected");
}
function readAssistantMessageApi(e) {
return e?.role === "assistant" ? normalizeOptionalString(e.api) : void 0;
}
function isResponsesApiAssistantMessage(e) {
return OPENAI_RESPONSES_APIS.has(readAssistantMessageApi(e) ?? "");
}
function isOpenAiCompletionsAssistantMessage(e) {
const t = readAssistantMessageApi(e);
return t === "openai-completions" || t === "openclaw-openai-completions-transport";
}
function extractStandaloneMessageToolText(e, t = {}) {
if (!t.allowCurrentSourceReply && !t.allowRoutedReply) return;
const n = safeParseJsonRecord(e.trim());
const r = asOptionalRecord(n?.arguments);
const i = Boolean(normalizeOptionalString(r?.target) || normalizeOptionalString(r?.to) || normalizeOptionalString(r?.channel) || normalizeOptionalString(r?.accountId) || Array.isArray(r?.targets));
if (normalizeOptionalString(n?.name) !== "message" || normalizeOptionalString(r?.action) !== "send" || (i ? !t.allowRoutedReply : !t.allowCurrentSourceReply)) return;
return normalizeOptionalString(r?.message);
}
function isAssistantTextBlock(e) {
return asOptionalObjectRecord(e)?.type === "text";
}
function resolveAssistantStreamItemId(e) {
const t = e.message?.content;
if (!Array.isArray(t)) return;
const n = resolveAssistantStreamContentIndex(e.contentIndex);
const r = isAssistantTextBlock(n !== void 0 ? t[n] : void 0);
const i = r && n !== void 0 ? n : t.length - 1;
const a = r ? i : 0;
for (let e = i; e >= a; e -= 1) {
const n = t[e];
if (!isAssistantTextBlock(n)) continue;
const r = parseAssistantTextSignature(n);
if (r?.id) return r.id;
}
}
function resolveAssistantStreamContentIndex(e) {
return typeof e === "number" && Number.isInteger(e) && e >= 0 ? e : void 0;
}
function resolveAssistantStreamBlockIndex(e, t, n) {
if (!Array.isArray(e.content)) return;
if (isAssistantTextBlock(t === void 0 ? void 0 : e.content[t])) return t;
const r = n ? e.content.findLastIndex((e) => isAssistantTextBlock(e) && parseAssistantTextSignature(e)?.id === n) : -1;
return r >= 0 ? r : void 0;
}
function scopeAssistantMessageToStreamBlock(e, t, n) {
const r = resolveAssistantStreamBlockIndex(e, t, n);
if (r === void 0 || !Array.isArray(e.content)) return e;
const i = e.content[r];
if (!i) return e;
return {
...e,
content: [i]
};
}
function emitAssistantCommentaryStreamData(e, t, n = false) {
const r = isResponsesApiAssistantMessage(t);
const { lastAssistantStreamContentIndex: i, lastAssistantStreamItemId: a } = e.state;
let o = [scopeAssistantMessageToStreamBlock(t, i, a)];
if (!r) {
const e = readAssistantTextBlocksForPhase(t, "commentary");
o = [t];
if (Array.isArray(t.content)) {
o = [];
for (const n of new Set(e.map((e) => parseAssistantTextSignature(e)?.id))) {
const r = t.content.filter((t) => t.type === "text" && e.some((e) => e === t) && parseAssistantTextSignature(t)?.id === n);
o.push({
...t,
content: r
});
}
}
}
for (const t of o) {
const i = createStreamingDirectiveAccumulator();
const o = extractAssistantCommentaryText(t, (e, t) => {
const r = i.sourceText.length;
i.consume(e, { final: n && t });
return i.sourceText.slice(r);
});
if (!o || !n && r && e.state.deltaBuffer === o) continue;
const s = r ? a : resolveAssistantStreamItemId({ message: t });
e.emitAssistantStreamData({
text: o,
delta: "",
replace: true,
phase: "commentary",
itemId: s
}, { finalMessage: n });
}
}
function emitReasoningEnd(e) {
if (!e.state.reasoningStreamOpen) return;
e.flushAssistantStream();
e.state.reasoningStreamOpen = false;
runBestEffortCallback({
label: "reasoning end",
log: e.log,
callback: () => e.params.onReasoningEnd?.()
});
}
function emitPersistentReasoning(e, t) {
if (!e.state.includeReasoning || !t || !e.params.onBlockReply || e.params.silentExpected || shouldSuppressDeterministicApprovalOutput(e.state) || shouldSuppressSourceReplyOutput(e) || t === e.state.lastReasoningSent) return;
const n = e.state.lastReasoningSent;
const r = n && t.startsWith(n) ? t.slice(n.length).trimStart() : t;
e.state.lastReasoningSent = t;
if (r) e.emitBlockReply({
text: r,
isReasoning: true
});
}
function emitAssistantMessageStart(e) {
e.flushAssistantStream();
runBestEffortCallback({
label: "assistant message start",
log: e.log,
callback: () => e.params.onAssistantMessageStart?.()
});
}
function openReasoningStream(e) {
if (!e.state.reasoningStreamOpen) e.flushAssistantStream();
e.state.reasoningStreamOpen = true;
}
function shouldSuppressDeterministicApprovalOutput(e) {
return e.deterministicApprovalPromptPending || e.deterministicApprovalPromptSent;
}
function shouldSuppressSourceReplyOutput(e, t = e.state.lastAssistant) {
return readAutomationDisplayState(e.params.runId) !== "ordinary" && t?.stopReason !== "error" && t?.stopReason !== "aborted" || e.state.sourceReplyDeliveryState === "delivered" || e.params.sourceReplyDeliveryMode === "message_tool_only" && (e.state.messageToolOnlySourceReplyDelivered || e.params.hasDeliveredMessageToolOnlySourceReply?.() === true || (e.state.messagingToolSourceReplyPayloads?.length ?? 0) > 0);
}
function resolveAssistantTextChunk(e) {
const { evtType: t, delta: n, content: r, accumulatedText: i } = e;
if (t === "text_delta" || n) return n;
if (!r) return "";
if (r.startsWith(i)) return r.slice(i.length);
return "";
}
function createStreamingReplyResolver() {
const e = createTextProjection([downgradedToolCallTextFilter(), toolCallXmlTextFilter({ stripFunctionCallsXmlPayloads: true }, true)]);
let t;
let n = false;
let r = "";
let i;
let a = "";
let o = false;
let s = false;
let c = false;
let l;
let u;
return (d) => {
let f = d.next;
let p = d.appendDelta;
if (d.rawDirectiveSource !== void 0) {
const t = d.rawDirectiveDelta === void 0 ? e.replace(d.rawDirectiveSource) : e.append(d.rawDirectiveDelta, d.rawDirectiveSource);
f = t.text;
p = t.delta;
i = void 0;
}
if (p === null) {
n = false;
r = "";
}
const m = p ?? f;
if ((r + m).includes("[[")) {
n = true;
l = void 0;
t = void 0;
}
if (m) r = m.slice(-1);
if (d.appendDelta === null || p === null) {
t = void 0;
i = void 0;
l = void 0;
}
if (l !== void 0) l = p !== null && canReuseMarkdownOwnershipForAppend(l, p, u ??= findCodeOwnership(l)) ? f : void 0;
if (!d.parsedStreamDirectives && d.evtType === "text_delta") {
if (d.rawDirectiveSource?.length !== t?.checkedRawLength) t = void 0;
const e = d.previousCleaned;
return {
text: e,
delta: "",
replace: false,
hasText: Boolean(e.trim()),
replyDirectives: null,
audioDirectiveCount: d.previousAudioDirectiveCount
};
}
let h;
let g;
let _ = false;
let v = d.parsedStreamDirectives;
let y = d.previousAudioDirectiveCount;
if (d.evtType !== "text_end" && d.parsedStreamDirectives && !hasReplyDirectiveMetadata(d.parsedStreamDirectives) && !/(?:^|\n)[^\S\n]*MEDIA:\s*\S[^\n]*(?:\n|$)/i.test(d.visibleDelta) && d.parsedStreamDirectives.text === d.visibleDelta && d.appendDelta !== null && d.previousText === d.previousCleaned && (t || !n || l !== void 0)) {
h = d.next;
g = d.appendDelta;
_ = true;
if (t && d.rawDirectiveSource !== void 0) t = {
...t,
checkedRawLength: d.rawDirectiveSource.length
};
}
if (h === void 0 && d.evtType !== "text_end" && d.parsedStreamDirectives && d.parsedStreamDirectives.text === d.visibleDelta && d.appendDelta !== null && d.previousCleaned && d.previousText.length > d.previousCleaned.length && !/(?:^|\n)[^\S\n]*MEDIA:\s*\S[^\n]*(?:\n|$)/i.test(d.visibleDelta)) {
const e = d.previousText.lastIndexOf("[[");
const t = d.previousText.indexOf("]]", e + 2) + 2;
const n = d.previousText.slice(t);
const r = d.rawDirectiveSource ?? d.next;
if (e >= 0 && t > e + 2 && n.trim() && d.previousCleaned.endsWith(n.trimStart()) && !/[`~\t]| {4}/u.test(d.previousText.slice(0, e)) && !r.includes("[[", d.previousText.length - 1) && !r.includes("]:")) {
h = d.previousCleaned + d.appendDelta;
g = d.appendDelta;
_ = true;
}
}
if (h === void 0 && d.rawDirectiveSource === void 0 && d.evtType !== "text_end" && d.appendDelta !== null && d.parsedStreamDirectives && !hasReplyDirectiveMetadata(d.parsedStreamDirectives) && i !== void 0 && !o && (!s || l !== void 0) && !c && d.next.length === i.length + d.appendDelta.length && d.next.endsWith(d.appendDelta) && !d.appendDelta.includes("[[") && !d.appendDelta.endsWith("[") && !/(?:^|[\r\n])[^\S\r\n]*MEDIA:/iu.test(i.slice(-1) + d.appendDelta) && !/(?:^|[\r\n])[\t ]*(?:M|ME|MED|MEDI|MEDIA)$/iu.test(i.slice(-1) + d.appendDelta)) {
h = a + d.appendDelta;
g = d.appendDelta;
_ = true;
}
if (h === void 0) {
t = void 0;
y = 0;
const e = d.rawDirectiveSource === void 0 || d.evtType !== "text_end" ? f : toolCallXmlTextFilter({ stripFunctionCallsXmlPayloads: true }, d.evtType !== "text_end").transform(stripDowngradedToolCallText(d.rawDirectiveSource));
const n = d.evtType === "text_end" ? void 0 : splitTrailingDirective(e);
const r = parseReplyDirectives(n ? n.text : e, { onAudioDirective: () => {
y += 1;
} });
h = d.rawDirectiveSource === void 0 ? r.text : trimTextPreservingCode(r.text);
i = d.rawDirectiveSource === void 0 && d.evtType !== "text_end" ? f : void 0;
a = h;
o = Boolean(n?.tail);
s = i !== void 0 && f.includes("[[");
c = Boolean(r.mediaFailures?.length);
u = void 0;
l = e.includes("[[") && r.text === e && !n?.tail && !r.mediaFailures?.length && !r.mediaUrls?.length && !hasReplyDirectiveMetadata(r) ? e : void 0;
if (d.evtType !== "text_end" && d.appendDelta !== null && e === d.rawDirectiveSource && h === d.next && !hasReplyDirectiveMetadata(r) && !r.mediaUrls?.length) {
const n = findDirectiveCodePrefix(e, d.visibleDelta);
if (n && d.next.startsWith(e.slice(0, n.end))) t = n;
}
if (v) v = {
...v,
replyToId: r.replyToId,
replyToCurrent: r.replyToCurrent,
replyToTag: r.replyToTag,
audioAsVoice: y > d.previousAudioDirectiveCount
};
} else if (d.rawDirectiveSource === void 0 && d.evtType !== "text_end") {
i = d.next;
a = h;
o = false;
}
const b = Boolean(!_ && d.previousCleaned && !h.startsWith(d.previousCleaned));
return {
text: h,
delta: b ? "" : g ?? h.slice(d.previousCleaned.length),
replace: b,
hasText: Boolean(_ ? h : h.trim()),
replyDirectives: v,
audioDirectiveCount: y
};
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.messages.snapshot.ts
function extractAssistantStreamSnapshot(e, t, n) {
const r = n?.nativeToolMarkerBlocks ?? findNativeToolMarkerTextBlocks(t);
let i = t;
if (n?.throughIndex !== void 0 && Array.isArray(t.content)) {
const e = t.content.slice(0, n.throughIndex + 1);
if (n.observedText !== void 0) {
const t = e[n.throughIndex];
if (t?.type === "text") e[n.throughIndex] = {
type: "text",
text: n.observedText,
textSignature: t.textSignature
};
else if (e.length === 0) e.push({
type: "text",
text: n.observedText
});
}
i = {
...t,
content: e
};
} else if (n?.observedText !== void 0) i = {
...t,
content: [{
type: "text",
text: n.observedText
}]
};
const a = createAssistantStreamBlockState();
let o = "";
const s = createStreamingDirectiveAccumulator();
const c = [];
const l = [];
const u = prepareAssistantVisibleText(i, (t, i, u, d) => {
const f = s.sourceText && !a.pendingTagFragment && !a.pendingFenceFragment ? "\n" : "";
const p = l.at(-1)?.index;
l.push({
separator: f,
index: d
});
o += t;
const m = s.sourceText.length;
s.consume(t, { final: i && n?.final !== false });
const h = s.sourceText.slice(m);
const g = u === "final_answer" && !e.params.enforceFinalTag;
const _ = d !== void 0 && r.has(d);
const v = _ ? "" : g ? `${f}${h}` : e.stripBlockTags(`${f}${h}`, a, { final: i && n?.final !== false });
const y = c.at(-1);
if (y && p !== void 0 && d === p + 1 && y.finalAnswer === g) y.text += v;
else c.push({
text: v.startsWith(f) ? v.slice(f.length) : v,
separator: f,
finalAnswer: g
});
return _ ? "" : g ? h : v;
});
const d = c.map(({ text: e, separator: t, finalAnswer: r }) => ({
separator: t,
text: r ? sanitizeUserFacingText(applyTextFilters(e, assistantVisibleTextFilters("final-answer-delivery", n?.final === false, { preserveTrailingWhitespace: true })), { streaming: n?.final === false }) : toolCallXmlTextFilter({ stripFunctionCallsXmlPayloads: true }, n?.final === false).transform(stripDowngradedToolCallText(e, { preserveTrailingWhitespace: true }))
})).filter(({ text: e }, t) => e.trim() || n?.observedText === "" && t === c.length - 1).map(({ text: e, separator: t }, n) => `${n > 0 ? t : ""}${e}`).join("");
const f = parseReplyDirectives(n?.final === false ? splitTrailingDirective(d, { preserveTrailingWhitespace: true }).text : d, { preserveTrailingWhitespace: true });
let p;
return {
get text() {
return p ??= u();
},
rawText: o,
state: a,
parts: l,
blockText: f.text,
message: i,
nativeToolMarkerBlocks: r
};
}
/** Reconcile one prepared source frame without translating raw or rendered offsets. */
function reconcileBlockReplySnapshot(e, t, n) {
const prefixAt = (t, n) => {
if (n === 0) return "";
if (n > (t.parts.at(-1)?.index ?? 0)) return t.blockText;
return extractAssistantStreamSnapshot(e, t.message, {
throughIndex: n - 1,
final: false,
nativeToolMarkerBlocks: t.nativeToolMarkerBlocks
}).blockText + (t.parts.find((e) => e.index === n)?.separator ?? "");
};
const r = e.state.blockReplyScopeStart;
const scopePosition = (e) => {
if (!r) return {
index: 0,
valid: true
};
const t = resolveAssistantStreamBlockIndex(e.message, r.contentIndex, void 0);
const n = t !== void 0 && (!r.itemId || resolveAssistantStreamItemId({
contentIndex: t,
message: e.message
}) === r.itemId) ? t : resolveAssistantStreamBlockIndex(e.message, void 0, r.itemId) ?? t;
return {
index: (n ?? r.contentIndex) + (r.after ? 1 : 0),
valid: n !== void 0
};
};
const i = scopePosition(t);
const a = scopePosition(n);
const o = i.index;
const s = prefixAt(t, o);
const c = prefixAt(n, a.index);
const l = t.blockText.slice(s.length);
const u = n.blockText.slice(c.length);
const d = e.blockChunker.consumedLength;
let f;
let p;
const crossesCode = (e, r) => {
if (r <= 0 || r >= e.blockText.length) return false;
return (e === t ? f ??= findMarkdownCodeRegions(t.blockText) : p ??= findMarkdownCodeRegions(n.blockText)).some((e) => e.start < r && r < e.end);
};
const m = i.valid && a.valid && !crossesCode(t, s.length) && !crossesCode(n, c.length);
if (m && o > 0 && d === 0 && !e.blockChunker.hasBuffered()) {
if (n.blockText.startsWith(c)) {
e.blockChunker.append(u);
return;
}
}
const h = Math.min(d, u.length);
const g = m && s === c && t.blockText.startsWith(s) && n.blockText.startsWith(c) && l.slice(0, h) === u.slice(0, h);
if (g && (u.length >= d || !l.slice(h, d).trim())) {
if (d === l.length && !e.blockChunker.hasBuffered()) for (const r of n.parts) {
const i = r.index ?? 0;
if (!i || !r.separator) continue;
const a = prefixAt(n, i);
const o = a.slice(t.blockText.length);
if (a.startsWith(t.blockText) && o && !o.trim() && !crossesCode(n, a.length)) {
e.blockChunker.append(o);
e.blockChunker.drain({
force: true,
emit: () => {}
});
break;
}
}
e.blockChunker.replace(u, 0, g);
return;
}
let _ = n.parts[0]?.index ?? 0;
let v = "";
for (const e of n.parts) {
const r = e.index ?? 0;
if (!r || !e.separator) continue;
const i = prefixAt(t, r);
const a = prefixAt(n, r);
if (i === a && t.blockText.startsWith(i) && n.blockText.startsWith(a) && i.length <= s.length + d && !crossesCode(t, i.length) && !crossesCode(n, a.length)) {
_ = r;
v = a;
}
}
if (g && u.length < d && v !== n.blockText) {
e.blockChunker.replace(u, 0, g);
return;
}
e.state.blockReplyScopeStart = {
contentIndex: _,
itemId: resolveAssistantStreamItemId({
contentIndex: _,
message: n.message
})
};
e.blockChunker.reset([], v.length);
e.blockChunker.append(n.blockText.slice(v.length));
}
//#endregion
//#region src/agents/embedded-agent-subscribe.raw-stream.ts
function appendRawStream(e, t) {
if (!isTruthyEnvValue(process.env.OPENCLAW_RAW_STREAM) || isIncognitoSessionKey(t)) return;
const n = process.env.OPENCLAW_RAW_STREAM_PATH?.trim() || path.join(resolveStateDir(), "logs", "raw-stream.jsonl");
try {
const t = `${JSON.stringify(e())}\n`;
fs.mkdir(path.dirname(n), { recursive: true }).then(() => appendRegularFile({
filePath: n,
content: t,
rejectSymlinkParents: true
})).catch(() => {});
} catch {}
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts
function isRegisteredToolName(e, t) {
if (!e || !t) return;
const n = normalizeToolPolicyName(e);
for (const e of t) if (normalizeToolPolicyName(e) === n) return true;
return false;
}
function handleMessageStart(e, t) {
const n = t.message;
if (n?.role !== "assistant" || isSubscribeTranscriptOnlyOpenClawAssistantMessage(n)) return;
e.state.lastReasoningSent = void 0;
e.resetAssistantMessageState(e.state.assistantTexts.length);
e.state.assistantMessageStartIndex = e.state.assistantMessageIndex;
emitAssistantMessageStart(e);
}
function handleMessageEnd(e, t, n) {
const r = t.message;
if (r.role === "user" && e.state.lastAssistant) {
e.state.answerSegments.push({
textEnd: e.state.assistantTexts.length,
messageEnd: e.state.assistantMessageIndex,
finalMessageStart: e.state.assistantMessageStartIndex,
lastAssistant: e.state.lastAssistant,
keptAnswer: e.state.keptAnswer,
sourceReplyDeliveryState: e.state.sourceReplyDeliveryState
});
e.state.inputAnswer = void 0;
e.state.keptAnswer = void 0;
e.state.sourceReplyDeliveryState = "missing";
e.state.messageToolOnlySourceReplyDelivered = false;
e.state.deterministicApprovalPromptPending = false;
e.state.deterministicApprovalPromptSent = false;
e.state.currentSourceMessagingToolSentTextsNormalized.length = 0;
e.state.lastToolTurnOnlySourceProgress = void 0;
e.state.lastAssistant = void 0;
return;
}
if (r?.role !== "assistant" || isSubscribeTranscriptOnlyOpenClawAssistantMessage(r)) return;
e.state.assistantTurnCount += 1;
const i = r;
const a = resolveAssistantMessagePhase(i);
const o = a === "commentary";
const s = shouldSuppressDeterministicApprovalOutput(e.state);
const c = shouldSuppressSourceReplyOutput(e, i);
const canEmitReply = () => !e.params.silentExpected && !s && !c;
const l = e.params.session.id;
const appendRawMessage = (t) => appendRawStream(() => ({
ts: Date.now(),
event: "assistant_message_end",
runId: e.params.runId,
sessionId: l,
rawText: t(),
rawThinking: extractAssistantThinking(i)
}), e.params.sessionKey);
if (!c) emitReasoningEnd(e);
e.noteLastAssistant(i);
e.state.keptAnswer = void 0;
if (o) {
appendRawMessage(() => extractEmbeddedAssistantText(i));
emitAssistantCommentaryStreamData(e, i, true);
const t = e.state.includeReasoning ? extractAssistantThinking(i) : "";
emitPersistentReasoning(e, t);
return;
}
const u = i.content;
promoteThinkingTagsToBlocks(i);
let d;
const getRawText = () => d ??= extractEmbeddedAssistantText(i);
const f = extractAssistantStreamSnapshot(e, i);
const p = prepareAgentRunTerminalReply({ rawText: f.rawText });
const m = f.text;
appendRawMessage(getRawText);
{
const t = i.content.some((e) => isToolCallBlockType(e.type));
const n = extractTextFromChatContent(i.content, {
joinWith: "\n",
normalizeText: (e) => e.trim()
}) ?? "";
const r = t ? null : detectToolCallShapedText(n);
if (r) {
const t = normalizeOptionalString(i.provider);
const n = normalizeOptionalString(i.model);
const a = isRegisteredToolName(r.toolName, e.builtinToolNames);
const o = normalizeOptionalString(l);
e.log.warn("Assistant reply looks like a tool call, but no structured tool invocation was emitted; treating it as text.", {
runId: e.params.runId,
...o ? { sessionId: o } : {},
...t ? { provider: t } : {},
...n ? { model: n } : {},
pattern: r.kind,
...r.toolName ? { toolName: r.toolName } : {},
...a !== void 0 ? { registeredTool: a } : {}
});
}
const a = n.includes("[") || n.includes("<") || n.includes("&") ? markdownToIR(n, {
assistantTranscriptRoleHeaders: true,
enableSpoilers: true,
linkify: false,
tableMode: "off"
}).annotations?.[0] : void 0;
if (a?.type === "assistant_transcript_role") {
const t = normalizeOptionalString(i.provider);
const n = normalizeOptionalString(i.model);
const r = normalizeOptionalString(l);
e.log.warn("Assistant reply contains transcript-role-looking text; treating it as inert assistant text.", {
runId: e.params.runId,
...r ? { sessionId: r } : {},
...t ? { provider: t } : {},
...n ? { model: n } : {},
pattern: a.kind,
role: a.role
});
}
}
const h = extractStandaloneMessageToolText(m, {
allowRoutedReply: isOpenAiCompletionsAssistantMessage(i),
allowCurrentSourceReply: e.params.sourceReplyDeliveryMode === "message_tool_only" && e.builtinToolNames?.has("message") === true
});
const g = h === void 0 ? m : extractAssistantVisibleText(scopeAssistantMessageToStreamBlock(i, f.parts[0]?.index, void 0), () => h);
const _ = e.state.includeReasoning || e.state.streamReasoning ? extractAssistantThinking(i) || extractThinkingFromTaggedText(getRawText()) : "";
e.resetPartialReplyDirectives();
const v = parseReplyDirectives(g);
recordPendingAssistantReplyDirectives(e.state, v);
const y = v.text;
const { mediaUrls: b } = resolveSendableOutboundReplyParts(v, { text: "" });
const x = resolveManagedStreamMediaUrls(e.state, b);
const S = {
...i,
content: u
};
const C = u === i.content ? f : extractAssistantStreamSnapshot(e, S);
const resolveSourceIndex = (e, t) => resolveAssistantStreamBlockIndex(S, e, t) ?? -1;
const w = resolveSourceIndex(e.state.lastAssistantStreamContentIndex, e.state.lastAssistantStreamItemId);
if (e.state.lastBlockReplyText == null) {
e.blockChunker.reset();
e.state.blockReplyScopeStart = void 0;
}
if (e.blockChunker.consumedLength === 0 && !e.blockChunker.hasBuffered()) {
const t = e.state.lastAssistantTextMessageIndex >= e.state.assistantMessageStartIndex ? resolveSourceIndex(e.state.lastAssistantTextContentIndex, e.state.lastAssistantTextItemId) : -1;
if (t >= 0) e.state.blockReplyScopeStart = {
contentIndex: t,
itemId: resolveAssistantStreamItemId({
contentIndex: t,
message: S
}),
after: true
};
}
const T = extractAssistantStreamSnapshot(e, S, {
throughIndex: w >= 0 ? w : void 0,
observedText: e.state.streamBlockText,
final: e.state.streamBlockFinal
});
reconcileBlockReplySnapshot(e, T, g === m ? C : {
...f,
blockText: y
});
const E = C.parts.at(-1)?.index;
if (w >= 0 && E !== void 0 && E > w) e.state.lastAssistantStreamContentIndex = E;
const finalizeMessageEnd = () => {
e.state.deltaBuffer = "";
e.state.streamBlockText = "";
e.state.streamBlockFinal = false;
e.state.blockReplyScopeStart = void 0;
e.state.thinkingTagStream = createThinkingTagStreamState();
e.state.deltaBufferIsCommentary = false;
e.state.hasFlushedPartialText = false;
e.blockChunker.reset();
const { reasoningDepth: t, final: n, inlineCode: r } = e.state.partialBlockState;
e.state.partialBlockState = {
reasoningDepth: t,
final: n,
inlineCode: r
};
e.state.assistantStream = void 0;
e.state.reasoningStreamOpen = false;
};
if (canEmitReply()) e.emitAssistantStreamData({
text: y,
delta: "",
mediaUrls: b.length ? b : void 0,
managedMediaUrls: x.length ? x : void 0,
phase: a
}, { finalMessage: true });
const D = e.params.silentExpected ? "" : y;
const O = E !== void 0 && e.state.lastAssistantTextMessageIndex >= e.state.assistantMessageStartIndex && resolveSourceIndex(e.state.lastAssistantTextContentIndex, e.state.lastAssistantTextItemId) === E;
const k = e.state.assistantTexts.length > e.state.assistantTextBaseline || O;
const A = Boolean(e.params.onBlockReply) && e.blockChunker.hasBuffered();
e.finalizeAssistantTexts({
text: D,
addedDuringMessage: k,
chunkerHasBuffered: A
});
const j = !e.params.silentExpected && i.stopReason === "stop" && i.endTurn !== false && p.terminalReply.disposition === "visible" && Boolean(y.trim() || b.length > 0);
const M = i.stopReason === "stop" && (p.terminalReply.disposition !== "visible" || !y.trim()) && b.length === 0 && !v.audioAsVoice && !i.openclawDelivery?.audioAsVoice && !i.openclawDelivery?.tts?.text?.trim();
e.state.keptAnswer = M ? e.state.inputAnswer : void 0;
if (!M && i.stopReason !== "toolUse" && i.endTurn !== false) e.state.inputAnswer = void 0;
const N = e.params.onBlockReply;
emitPersistentReasoning(e, _);
if (canEmitReply() && N) {
const t = e.flushBlockReplyBuffer({
assistantMessageIndex: e.state.assistantMessageIndex,
final: true,
finalReply: {
...v,
text: y
}
});
if (t) t.catch((t) => {
e.log.debug(`message_end block reply flush failed: ${String(t)}`);
});
}
if (j) {
e.state.inputAnswer = {
assistant: applyAssistantDeliveryDirectives(snapshotAssistantMessage(i, n).snapshot),
messageIndex: e.state.lastAssistantTextMessageIndex
};
const t = readAgentAssistantSource(i);
if (t) bindAgentAssistantSource(e.state.inputAnswer.assistant, t);
}
if (!e.params.silentExpected && _) e.emitReasoningStream(_);
if (!e.params.silentExpected && e.state.blockReplyBreak === "message_end" && e.params.onBlockReplyFlush) {
const t = e.flushBlockReplyBuffer();
if (isPromiseLike(t)) return t.then(() => e.params.onBlockReplyFlush?.({ reason: "message_end" })).finally(finalizeMessageEnd);
const n = e.params.onBlockReplyFlush({ reason: "message_end" });
if (isPromiseLike(n)) return n.finally(finalizeMessageEnd);
}
finalizeMessageEnd();
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.messages.update.ts
function handleMessageUpdate(e, t) {
const n = t.message;
if (n?.role !== "assistant" || isSubscribeTranscriptOnlyOpenClawAssistantMessage(n)) return;
e.noteLastAssistant(n);
const r = asOptionalObjectRecord(t.assistantMessageEvent);
const i = typeof r?.type === "string" ? r.type : "";
if (i !== "text_delta") e.flushAssistantStream();
const a = updateLiveEditDiffProgress(e.state.liveEditDiffStateById, r);
if (a) {
const t = {
phase: "input_delta",
...a
};
emitAgentEvent({
runId: e.params.runId,
stream: "tool",
data: t
});
runBestEffortCallback({
label: "live edit diff agent event",
log: e.log,
callback: () => e.params.onAgentEvent?.({
stream: "tool",
data: t
})
});
}
const o = r?.partial && typeof r.partial === "object" ? r.partial : n;
const s = isResponsesApiAssistantMessage(o) && (i === "text_start" || i === "text_delta" || i === "text_end");
const recordRawStream = (t, n, r, i) => appendRawStream(() => ({
ts: Date.now(),
event: t,
runId: e.params.runId,
sessionId: e.params.session.id,
evtType: n,
delta: r,
content: i
}), e.params.sessionKey);
if (resolveAssistantMessagePhase(n) === "commentary" && !s) {
e.flushAssistantStream();
if (i === "text_delta" && Date.now() < (e.state.nextCommentaryAt ?? 0)) return;
const t = extractAssistantCommentaryText(n);
if (t) {
e.state.nextCommentaryAt = Date.now() + 75;
recordRawStream("assistant_text_stream", "commentary_update", "", t);
emitAssistantCommentaryStreamData(e, n);
}
return;
}
const c = shouldSuppressDeterministicApprovalOutput(e.state);
const l = shouldSuppressSourceReplyOutput(e);
if (i === "thinking_start" || i === "thinking_delta" || i === "thinking_end") {
if (!l && (i === "thinking_start" || i === "thinking_delta")) openReasoningStream(e);
const t = typeof r?.delta === "string" ? r.delta : "";
const a = typeof r?.content === "string" ? r.content : "";
recordRawStream("assistant_thinking_stream", i, t, a);
e.emitReasoningStream(Array.isArray(n.content) ? n.content : [], a || t);
if (i === "thinking_end" && !l) {
if (!e.state.reasoningStreamOpen) openReasoningStream(e);
emitReasoningEnd(e);
if (e.state.includeReasoning && e.state.blockReplyBreak === "text_end") emitPersistentReasoning(e, extractAssistantThinking(n) || a);
}
return;
}
if (i !== "text_delta" && i !== "text_start" && i !== "text_end") return;
const u = typeof r?.delta === "string" ? r.delta : "";
const d = typeof r?.content === "string" ? r.content : "";
recordRawStream("assistant_text_stream", i, u, d);
const f = o;
const p = e.state.streamBlockText;
const m = e.state.streamBlockFinal;
const h = e.state.lastAssistantStreamContentIndex;
const g = resolveAssistantStreamContentIndex(r?.contentIndex);
if (s && h !== void 0 && g !== void 0 && g < h) return;
const _ = resolveAssistantStreamItemId({
contentIndex: g,
message: f
});
const v = resolveAssistantStreamBlockIndex(f, g, _) ?? g;
const y = resolveAssistantStreamBlockIndex(f, h, e.state.lastAssistantStreamItemId) ?? h;
const b = scopeAssistantMessageToStreamBlock(f, g, _);
const x = resolveAssistantMessagePhase(b);
const S = i !== "text_end" && !x && Boolean(_) && isResponsesApiAssistantMessage(f);
const C = g !== void 0 && isResponsesApiAssistantMessage(f);
let w = false;
let T = _;
if ((x || S || C) && (g !== void 0 || _)) {
const t = e.state.lastAssistantStreamContentIndex;
const n = e.state.lastAssistantStreamItemId;
if (t !== void 0 && g !== void 0 && t !== g || (t === void 0 || g === void 0) && Boolean(n && _ && n !== _)) {
w = true;
e.flushBlockReplyBuffer({ assistantMessageIndex: e.state.assistantMessageIndex });
e.resetAssistantMessageState(e.state.assistantTexts.length);
e.state.blockReplyScopeStart = {
contentIndex: g ?? v ?? 0,
itemId: _
};
emitAssistantMessageStart(e);
} else if (t !== void 0 && g === t && n) T = n;
e.state.lastAssistantStreamItemId = T;
}
if (g !== void 0) {
if (g !== e.state.lastAssistantStreamContentIndex) {
e.flushAssistantStream();
e.state.streamBlockText = "";
e.state.streamBlockFinal = false;
}
e.state.lastAssistantStreamContentIndex = g;
}
let E = resolveAssistantTextChunk({
evtType: i,
delta: u,
content: d,
accumulatedText: e.state.streamBlockText
});
e.state.streamBlockText += E;
e.state.streamBlockFinal = i === "text_end";
if (i === "text_start" && isResponsesApiAssistantMessage(f)) return;
if (x === "commentary") {
if (e.state.assistantStream?.projection) e.state.assistantStream.projection = void 0;
const t = isResponsesApiAssistantMessage(f);
const n = t && Boolean(e.state.deltaBuffer);
if (t && E) {
e.state.deltaBuffer += E;
e.state.deltaBufferIsCommentary = true;
}
if (i === "text_delta" && Date.now() < (e.state.nextCommentaryAt ?? 0)) return;
e.state.nextCommentaryAt = Date.now() + 75;
const r = t ? e.state.deltaBuffer : readAssistantTextBlocksForPhase(b, "commentary").map((e) => e.text).join("");
const a = e.getPartialReplySourceText();
e.resetPartialReplyDirectives();
e.consumePartialReplyDirectives(r, { final: i === "text_end" });
const o = e.getPartialReplySourceText();
const s = extractAssistantCommentaryText(b, (e, t) => t ? o : "");
if ((s || a) && (E || !n || i === "text_end")) e.emitAssistantStreamData({
text: s,
delta: "",
replace: true,
phase: "commentary",
itemId: T
}, { finalMessage: i === "text_end" });
return;
}
if (S) return;
const D = e.params.suppressLiveStreamOutput === true;
const O = Boolean(x);
const k = O && !e.params.enforceFinalTag && e.state.assistantStream?.projection?.kind !== "final" && e.blockChunker.consumedLength === 0;
const A = i === "text_end";
if (E) {
e.state.deltaBuffer += E;
e.state.deltaBufferIsCommentary = false;
}
if (D) return;
e.emitReasoningStream(extractThinkingFromTaggedStream(e.state.deltaBuffer, e.state.thinkingTagStream, E));
const j = e.state.partialBlockState.reasoningDepth > 0;
let M = "";
let N = false;
let P = null;
let F = e.state.assistantStream?.raw ?? "";
const I = w || i === "text_end" && r?.partial !== void 0 || O && (i === "text_end" || !E);
const L = i === "text_end" && I;
let R = O || s ? b : f;
const z = L ? findNativeToolMarkerTextBlocks(R) : void 0;
if (L && R === f && g !== void 0 && Array.isArray(f.content) && g + 1 < f.content.length) R = {
...f,
content: f.content.slice(0, g + 1)
};
const B = I ? extractAssistantStreamSnapshot(e, R, {
final: A,
nativeToolMarkerBlocks: z
}) : void 0;
const V = e.getPartialReplySourceText();
if (B) e.resetPartialReplyDirectives();
const H = e.consumePartialReplyDirectives(B?.rawText ?? E, { final: A });
const U = e.getPartialReplySourceText();
E = B || !V ? U : E;
let W = I ? (B?.text ?? extractAssistantVisibleText(R)).trimEnd() : void 0;
if (B) {
e.state.deltaBuffer = B.rawText;
e.state.thinkingTagStream = createThinkingTagStreamState();
e.state.partialBlockState = B.state;
}
if (!W && i !== "text_end") W = void 0;
const G = W !== void 0;
let K = W ?? "";
let q;
let J;
let Y;
if (W === void 0 && x === "final_answer" && (k || E)) {
M = k ? U : e.params.enforceFinalTag ? e.stripBlockTags(E, e.state.partialBlockState, { final: A }) : E;
W = M;
N = true;
} else if (W === void 0 && x !== "final_answer") {
const t = e.state.partialBlockState.pendingTagFragment;
const n = scanReasoningTags(E, false);
if (Boolean(t) || n.tags.length > 0 || n.pendingStart !== void 0) {
const t = createAssistantStreamBlockState();
const n = e.stripBlockTags(U, t, { final: A });
const r = !n.startsWith(F);
N = !r;
W = n;
M = r ? n : n.slice(F.length);
K = n;
e.state.partialBlockState = t;
} else {
M = E || i === "text_end" ? e.stripBlockTags(E, e.state.partialBlockState, { final: A }) : "";
if (e.state.partialBlockState.pendingTagFragment) {
M = "";
W = e.state.assistantStream?.text ?? "";
K = e.state.assistantStream?.raw ?? "";
} else {
W = M;
N = true;
}
}
} else if (!L && W !== void 0 && (E || i === "text_end")) M = e.stripBlockTags(E, e.state.partialBlockState, { final: A });
if (W !== void 0) {
const t = N && M === E && e.state.assistantStream?.projection?.projector.matchesTrimmedSource !== false;
if (!G) {
const n = x !== "final_answer" ? "raw" : e.params.enforceFinalTag ? "delivery" : "final";
const r = k ? void 0 : e.state.assistantStream;
q = r?.projection;
const i = q?.kind === n;
if (!q || q.kind !== n) {
q = {
kind: n,
resolveReply: createStreamingReplyResolver(),
projector: n === "raw" ? createTextProjection([
downgradedToolCallTextFilter(),
toolCallXmlTextFilter({ stripFunctionCallsXmlPayloads: true }, true),
trimTextFilter("both", { preserveCodeIndentation: true })
]) : createAssistantVisibleStreamText(n === "final" ? "final_answer" : void 0)
};
q.projector.replace(r?.raw ?? "");
}
F = q.projector.text;
Y = i && N ? M : void 0;
const a = N ? q.projector.append(M, t && q.projector.source === V ? U : void 0) : q.projector.replace(K);
K = q.projector.source;
J = N ? q.blockProjector?.append(M, K) : q.blockProjector?.replace(K);
W = a.text;
P = a.delta;
if (n !== "raw" || !q.projector.matchesTrimmedSource) M = a.delta ?? (F.startsWith(W) ? "" : W);
}
if (!l) {
if (!j && e.state.partialBlockState.reasoningDepth > 0) openReasoningStream(e);
else if (j && e.state.partialBlockState.reasoningDepth === 0) emitReasoningEnd(e);
}
const n = e.state.assistantStream?.text ?? "";
const { text: r, delta: a, replace: o, hasText: s, replyDirectives: u, audioDirectiveCount: _ } = (q?.resolveReply ?? createStreamingReplyResolver())({
evtType: i,
next: W,
previousText: F,
previousCleaned: n,
visibleDelta: M,
appendDelta: P,
parsedStreamDirectives: H,
previousAudioDirectiveCount: e.state.lastAssistantAudioDirectiveCount,
rawDirectiveSource: q?.kind === "raw" ? K : void 0,
rawDirectiveDelta: Y
});
recordPendingAssistantReplyDirectives(e.state, u, {
previous: e.state.lastAssistantAudioDirectiveCount,
current: _
});
e.state.lastAssistantAudioDirectiveCount = _;
const b = Boolean(u?.audioAsVoice);
const S = s || b;
const C = S ? a : "";
let T = (S || o) && (o ? r !== n || b : Boolean(C || b));
const D = i === "text_delta" && !B && !k && !o && !e.params.enforceFinalTag && (h === g || h === void 0 && !p);
const O = D && t && q?.projector.matchesTrimmedSource && (F.length > 0 || P === E) && (F === n && W === r || P !== null && a === P);
if (e.params.onBlockReply && O) {
if (q) {
q.blockProjector = void 0;
q.blockSourceLength = void 0;
}
e.blockChunker.append(E);
} else if (e.params.onBlockReply && D && !w && N && q?.kind === "final" && q.blockSourceLength !== void 0 && e.blockChunker.sourceLength === q.blockSourceLength && F === n && W === r && P !== null && a === P && J && J.delta !== null) {
e.blockChunker.append(J.delta);
q.blockSourceLength = J.text.length;
} else if (e.params.onBlockReply) {
if (q) q.blockSourceLength = void 0;
const t = extractAssistantStreamSnapshot(e, f, {
throughIndex: w ? v : y,
observedText: w ? "" : p,
final: w ? false : m
});
const n = extractAssistantStreamSnapshot(e, f, {
throughIndex: v,
...B ? {} : { observedText: e.state.streamBlockText },
final: A
});
reconcileBlockReplySnapshot(e, t, n);
if (q?.kind === "final" && !q.projector.matchesTrimmedSource) {
if (!q.blockProjector) {
q.blockProjector = createAssistantVisibleStreamText("final_answer", { preserveTrailingWhitespace: true });
q.blockProjector.replace(K);
}
}
if (q?.kind === "final" && n.blockText === q.blockProjector?.text && e.blockChunker.sourceLength === n.blockText.length) q.blockSourceLength = n.blockText.length;
}
if (L) e.state.streamBlockText = d;
e.state.assistantStream = {
raw: K,
text: r,
projection: q
};
if (e.params.silentExpected || c || l) T = false;
if (T) {
const t = e.params.sourceReplyDeliveryMode !== "message_tool_only" ? resolveCurrentSourceMessagingToolPartial(e.state, {
evtType: i,
text: r,
visibleDelta: M
}) : {
hold: false,
text: r
};
const n = t.text !== r;
e.emitAssistantStreamData({
text: t.text,
delta: n ? t.text : C,
replace: n || o || void 0,
phase: x
}, { emitPartialReply: !t.hold });
}
}
if (e.params.silentExpected || c || l || e.state.blockReplyBreak !== "text_end") return;
if (e.params.onBlockReply && e.blockChunking) {
const t = q?.projector;
const n = x === "final_answer" && !A && ((t ? t.settledLength < t.text.length : e.state.blockReplyTextUnsettled) || hasUnsettledPlainTextToolCall(e.blockChunker.bufferedText));
e.state.blockReplyTextUnsettled = n;
if (!n) e.blockChunker.drain({
force: false,
emit: e.emitBlockChunk
});
}
if (i === "text_end") {
const t = e.state.assistantMessageIndex;
const onFlushError = (t) => {
e.log.debug(`text_end block reply flush failed: ${String(t)}`);
};
try {
const n = e.flushBlockReplyBuffer({
assistantMessageIndex: t,
final: A
});
if (n) return n.catch(onFlushError);
} catch (e) {
onFlushError(e);
}
}
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.tools.results.ts
const execApprovalReplyModuleLoader = createLazyImportLoader(() => import("./exec-approval-reply-C1ORN_og.mjs"));
const hookRunnerGlobalModuleLoader = createLazyImportLoader(() => import("./plugins/hook-runner-global.js"));
const fallbackToolTerminalObservers = /* @__PURE__ */ new WeakMap();
function resolveFallbackToolTerminalObserver(e) {
const t = fallbackToolTerminalObservers.get(e.state);
if (t) return t;
const n = createToolTerminalObserver(e.params.runId);
fallbackToolTerminalObservers.set(e.state, n);
return n;
}
function isMiddlewareToolResultError(e) {
return asOptionalRecord(asOptionalObjectRecord(e)?.details)?.middlewareError === true;
}
const PROCESS_TERMINATION_REASONS = /* @__PURE__ */ new Set([
"manual-cancel",
"overall-timeout",
"no-output-timeout",
"spawn-error",
"signal",
"exit"
]);
function readSafeProcessSessionId(e) {
const t = readStringValue(e)?.trim();
if (!t || t.length > 160 || hasTerminalControlCharacter(t)) return;
return t;
}
function buildProcessTerminalDiagnostic(e, t, n) {
if (e !== "process") return;
const r = normalizeOptionalLowercaseString(t.action);
if (r !== "poll" && r !== "log") return;
const i = readToolResultDetails(n);
const a = readSafeProcessSessionId(i?.sessionId);
if (!a) return;
const o = normalizeOptionalLowercaseString(i?.exitReason);
const s = PROCESS_TERMINATION_REASONS.has(o ?? "");
if (r === "log" && !s) return;
const c = o === "overall-timeout" || o === "no-output-timeout" ? o : void 0;
let l;
if (i?.timedOut === true || c) l = {
kind: "timeout",
...c ? { timeoutKind: c } : {}
};
else if (typeof i?.exitSignal === "string" && i.exitSignal.trim().length > 0 && i.exitSignal.trim().length <= 32 || typeof i?.exitSignal === "number" && Number.isFinite(i.exitSignal)) {
const e = typeof i.exitSignal === "string" ? i.exitSignal.trim() : i.exitSignal;
if (!hasTerminalControlCharacter(String(e))) l = {
kind: "signal",
signal: e
};
} else if (typeof i?.exitCode === "number" && Number.isSafeInteger(i.exitCode) && i.exitCode !== 0) l = {
kind: "exit",
exitCode: i.exitCode
};
if (!l) return;
return {
kind: "process",
sessionId: a,
reason: l
};
}
function loadHookRunnerGlobal() {
return hookRunnerGlobalModuleLoader.load();
}
function applyCurrentMessageProvider(e, t, n) {
if (e !== "message" || readStringValue(t.provider) || readStringValue(t.channel) || !n) return t;
return {
...t,
provider: n
};
}
function applyToolSendReceiptForExtraction(e, t) {
const n = readToolResultDetails(t)?.toolSend;
if (n === void 0) return e;
return {
...asOptionalRecord(e),
details: {
...readToolResultDetails(e),
toolSend: n
}
};
}
function readExecToolDetails(e) {
const t = readToolResultDetails(e);
if (!t || typeof t.status !== "string") return null;
return t;
}
function extractExecOutput(e) {
const t = readExecToolDetails(e);
const n = t && "aggregated" in t ? t.aggregated : extractToolResultText(e);
return typeof n === "string" ? n : void 0;
}
function extractLiveExecOutput(e) {
const t = extractExecOutput(e);
return t !== void 0 ? truncateLiveExecOutput(t) : void 0;
}
function isOpenClawExecutable(e) {
return normalizeOptionalLowercaseString(e)?.split(/[\\/]/).at(-1) === "openclaw";
}
function isOpenClawPackageSpec(e) {
const t = normalizeOptionalLowercaseString(e);
return t?.startsWith("openclaw@") === true && t.length > 9;
}
function skipOpenClawPackageRunner(e, t) {
let n = t;
let r = false;
let i = normalizeOptionalLowercaseString(e[n]);
if (i === "corepack" && normalizeOptionalLowercaseString(e[n + 1]) === "pnpm") {
n += 1;
i = "pnpm";
}
if (i === "pnpm") {
const i = normalizeOptionalLowercaseString(e[n + 1]);
if (i === "exec" || i === "dlx") {
n += 2;
r = i === "dlx";
} else n = t;
} else if (i === "npx" || i === "bunx") {
n += 1;
r = true;
while (true) {
const t = normalizeOptionalLowercaseString(e[n]);
if (t === "-y" || t === "--yes" || t === "--no-install" || t === "--bun" || t?.startsWith("--package=") || t?.startsWith("--yes=")) {
n += 1;
continue;
}
if (t === "-p" || t === "--package") {
n += 2;
continue;
}
break;
}
}
if (e[n] === "--") n += 1;
return {
commandIndex: n,
acceptsPackageSpec: r
};
}
function isOpenClawCronAddShellCommand(e) {
const t = asOptionalObjectRecord(e);
const n = readStringValue(t?.command) ?? readStringValue(t?.cmd);
if (!n || hasTopLevelShellControlOperator(n)) return false;
const r = splitShellArgs(n);
if (!r || r.length < 3) return false;
let i = 0;
if (normalizeOptionalLowercaseString(r[i]) === "env") i += 1;
while (/^[A-Za-z_][A-Za-z0-9_]*=/u.test(r[i] ?? "")) i += 1;
const a = skipOpenClawPackageRunner(r, i);
i = a.commandIndex;
let o = i + 1;
for (let e = consumeRootOptionToken(r, o); e > 0; e = consumeRootOptionToken(r, o)) o += e;
const s = normalizeOptionalLowercaseString(r[o + 1]);
const c = r.slice(o + 2);
return (isOpenClawExecutable(r[i]) || a.acceptsPackageSpec && isOpenClawPackageSpec(r[i])) && (normalizeOptionalLowercaseString(r[o]) === "cron" || normalizeOptionalLowercaseString(r[o]) === "automations") && (s === "add" || s === "create") && !c.some((e) => e === "-h" || e === "--help");
}
function didShellCronAddSucceed(e, t) {
if (!isOpenClawCronAddShellCommand(e)) return false;
const n = readExecToolDetails(t);
return n?.status === "completed" && n.exitCode === 0;
}
function readApplyPatchSummary(e) {
const t = readToolResultDetails(e);
const n = asOptionalRecord(t?.summary);
if (!n) return null;
return {
added: filterStringEntries(n.added),
modified: filterStringEntries(n.modified),
deleted: filterStringEntries(n.deleted)
};
}
function buildPatchSummaryText(e) {
const t = [
"added",
"modified",
"deleted"
].flatMap((t) => e[t].length > 0 ? [`${e[t].length} ${t}`] : []);
return t.length > 0 ? t.join(", ") : "no file changes recorded";
}
function readMessagingText(e) {
for (const t of [
"content",
"message",
"text",
"body"
]) {
const n = readStringValue(e[t]);
if (n) return n;
}
}
function hasMessagingRichContent(e) {
const t = {
presentation: e.presentation,
interactive: e.interactive,
channelData: e.channelData
};
try {
parseJsonMessageParam(t, "presentation");
parseJsonMessageParam(t, "interactive");
} catch {
return false;
}
return hasReplyPayloadContent(t);
}
function queuePendingToolMedia(e, t, n, r) {
const i = new Map(e.state.pendingToolMediaUrls.map((e, t) => [e.trim(), t]));
const a = e.state.pendingToolMediaAttachments ??= e.state.pendingToolMediaUrls.map(() => ({}));
const o = new Map(t.mediaUrls.map((e, n) => [e.trim(), t.attachments?.[n]]));
for (const s of n) {
const n = s.trim();
if (!n) continue;
if (t.trustedLocalMedia) e.state.pendingToolMediaTrustByUrl.set(n, true);
else if (!e.state.pendingToolMediaTrustByUrl.has(n)) e.state.pendingToolMediaTrustByUrl.set(n, false);
if (r.has(n)) e.state.toolAutoDeliveryMediaUrls.add(n);
else e.state.toolAutoDeliveryMediaUrls.delete(n);
const c = o.get(n);
const l = i.get(n);
if (l !== void 0) {
if (c && Object.keys(a[l] ?? {}).length === 0) a[l] = c;
continue;
}
i.set(n, e.state.pendingToolMediaUrls.length);
e.state.pendingToolMediaUrls.push(n);
a.push(c ?? {});
}
if (t.audioAsVoice) e.state.pendingToolAudioAsVoice = true;
}
function readExecApprovalPendingDetails(e) {
const t = asOptionalObjectRecord(e);
const n = asOptionalRecord(t?.details) ?? t;
if (n?.status !== "approval-pending") return null;
const r = readStringValue(n.approvalId) ?? "";
const i = readStringValue(n.approvalSlug) ?? "";
const a = typeof n.command === "string" ? n.command : "";
const o = n.host === "node" ? "node" : n.host === "gateway" ? "gateway" : null;
if (!r || !i || !a || !o) return null;
return {
approvalId: r,
approvalSlug: i,
expiresAtMs: typeof n.expiresAtMs === "number" ? n.expiresAtMs : void 0,
allowedDecisions: Array.isArray(n.allowedDecisions) ? n.allowedDecisions.filter((e) => e === "allow-once" || e === "allow-always" || e === "deny") : void 0,
host: o,
command: a,
cwd: readStringValue(n.cwd),
nodeId: readStringValue(n.nodeId),
warningText: readStringValue(n.warningText)
};
}
function readExecApprovalUnavailableDetails(e) {
const t = asOptionalObjectRecord(e);
const n = asOptionalRecord(t?.details) ?? t;
if (n?.status !== "approval-unavailable") return null;
const r = n.reason === "initiating-platform-disabled" || n.reason === "initiating-platform-unsupported" || n.reason === "no-approval-route" ? n.reason : null;
if (!r) return null;
return {
reason: r,
warningText: readStringValue(n.warningText),
channel: readStringValue(n.channel),
channelLabel: readStringValue(n.channelLabel),
accountId: readStringValue(n.accountId),
sentApproverDms: n.sentApproverDms === true,
host: n.host === "gateway" || n.host === "node" ? n.host : void 0,
nodeId: readStringValue(n.nodeId)
};
}
async function emitToolResultOutput(e) {
const { ctx: t, toolName: n, rawToolName: r, meta: i, isToolError: a, result: o, sanitizedResult: s } = e;
const c = asOptionalRecord(asOptionalObjectRecord(o)?.details);
const l = asOptionalRecord(c?.media) !== void 0;
const u = readExecApprovalPendingDetails(o);
const d = !a && u ? null : readExecApprovalUnavailableDetails(o);
if (!a && (u || d)) {
if (!t.params.onToolResult) return;
if (u) t.state.deterministicApprovalPromptPending = true;
try {
const e = await execApprovalReplyModuleLoader.load();
if (u) {
await t.params.onToolResult(e.buildTypedExecApprovalPendingReplyPayload(u));
t.state.deterministicApprovalPromptSent = true;
} else if (d) await t.params.onToolResult?.(e.buildExecApprovalUnavailableReplyPayload(d));
} catch (e) {
const r = e instanceof Error ? e.message : String(e);
t.log.warn(`failed to deliver exec approval prompt: ${r}`);
const a = i ? `${i} · approval prompt delivery` : "approval prompt delivery";
const o = (t.params.observeToolTerminal ?? resolveFallbackToolTerminalObserver(t))({
toolName: n,
meta: a,
executionStarted: false,
outcome: "failure",
failure: { error: `Approval prompt delivery failed: ${r}` }
});
t.state.lastToolError = o.lastToolError;
} finally {
if (u) t.state.deterministicApprovalPromptPending = false;
}
return;
}
const f = a ? void 0 : extractToolResultMediaArtifact(o);
const p = f ? filterToolResultMediaUrls(r, f.mediaUrls, o, t.trustedLocalMediaToolNames) : [];
if (!(n === "tts" && r.trim() === "tts" && t.builtinToolNames?.has("tts") === true && !a && l && p.length > 0) && (a || readAutomationDisplayState(t.params.runId) === "ordinary") && t.shouldEmitToolOutput()) {
const e = extractToolResultText(s);
if (e) t.emitToolOutput(r, i, e, l ? void 0 : o);
if (!l) return;
}
if (a || !f || p.length === 0) return;
queuePendingToolMedia(t, f, p, new Set(f.trustedLocalMedia === true ? getCoreTtsToolResultMediaUrls(o) : []));
}
//#endregion
//#region src/agents/mcp-connect-action.ts
function readMcpConnectAction(e) {
const t = asOptionalRecord(asOptionalRecord(asOptionalRecord(e)?.details)?.mcpConnect);
const n = typeof t?.serverName === "string" ? t.serverName.trim() : "";
const r = typeof t?.authorizationUrl === "string" ? t.authorizationUrl.trim() : "";
const i = URL.parse(r);
if (!n || i?.protocol !== "http:" && i?.protocol !== "https:") return;
return {
serverName: n,
authorizationUrl: r
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.tools.completion.ts
/** Capture semantic outcome immediately; nested callers publish after activity acceptance. */
async function prepareToolExecutionEnd(e, t, n) {
const r = normalizeToolPolicyName(t.toolName);
const i = t.toolCallId;
e.state.liveEditDiffStateById.delete(i);
if (r === "ask_user") cancelAskUserPromptDelivery(i, e.params.sessionKey, e.params.runId);
const a = e.params.runId;
const o = t.result;
const s = e.consumeToolSendReceipt?.(i);
const c = t.isError || isToolResultError(o);
const l = n();
const u = isExecToolName(r) && readExecToolDetails(l)?.status === "approval-unavailable";
const d = c && !u;
if (!d) {
const t = readMcpAppChannelView(o);
if (t) e.state.latestMcpAppChannelView = t;
const n = readMcpConnectAction(o);
if (n) e.state.latestMcpConnectAction = n;
}
try {
e.params.onAgentToolResult?.({
toolName: r,
result: l,
isError: c
});
} catch (t) {
e.log.warn(`onAgentToolResult handler failed: tool=${r} error=${String(t)}`);
}
const f = isExecToolName(r) ? capLiveExecResult(l) : l;
const p = buildToolStartKey(a, i);
const m = toolStartData.get(p);
toolStartData.delete(p);
e.state.execLiveUpdateStateById?.delete(i);
const h = e.state.toolMetaById.get(i);
const g = asRecord(m?.args);
const _ = consumeAdjustedParamsForToolCall(i, a);
const v = consumeTrackedToolExecutionStarted(i, a);
const y = consumePreExecutionBlockedToolCall(i, a);
const b = consumeStructuredReplaySafeToolCall(i, a);
const x = asOptionalObjectRecord(_) ?? g;
const S = t.hideFromChannelProgress === true || m?.hideFromChannelProgress === true;
const C = buildToolCallSummary(r, x, h?.meta, h?.instanceReplaySafe === true, h?.ownerKey, b);
const w = (v ?? t.executionStarted ?? true) && !y;
const T = C.meta;
const E = !d && isAsyncStartedToolResult(l);
const D = E ? readAsyncStartedTaskIds(l) : {};
const O = !d && e.params.codeModeExecToolNames?.has(r) === true && readToolResultDetails(l)?.status === "waiting";
const k = asOptionalObjectRecord(o);
const A = k !== void 0 && "terminate" in k && k.terminate === true;
const j = {
toolName: r,
toolCallId: i,
...m?.parentToolCallId ? { parentToolCallId: m.parentToolCallId } : {},
meta: T,
replaySafe: !w || C.replaySafe,
isError: c,
...A ? { terminate: true } : {},
...E ? {
asyncStarted: true,
...D
} : {},
...O ? { codeModeSuspended: true } : {}
};
e.state.toolMetas.push(j);
const M = r === "sessions_spawn" && !d ? normalizeAcceptedSessionSpawnResult(l) : null;
if (M) e.state.acceptedSessionSpawns.push(M);
e.state.toolMetaById.delete(i);
e.state.toolSummaryById.delete(i);
const N = d ? extractToolErrorMessage(l) : void 0;
const P = d ? extractToolErrorCode(l) : void 0;
const F = d ? buildProcessTerminalDiagnostic(r, x, l) : void 0;
const I = F && N && hasTerminalControlCharacter(N) ? void 0 : N;
const L = d && t.executionStarted === false && t.errorKind === "argument-validation" ? createToolValidationErrorSummary(r) : void 0;
const R = (e.params.observeToolTerminal ?? resolveFallbackToolTerminalObserver(e))({
toolCallId: i,
toolName: r,
arguments: x,
result: o,
...T ? { meta: T } : {},
executionStarted: w,
replaySafe: C.replaySafe,
outcome: d ? "failure" : "success",
...C.ownerKey ? { ownerMutation: { ownerKey: C.ownerKey } } : {},
...d ? { failure: {
...P ? { errorCode: P } : {},
...I ? { error: I } : {},
...F ? { terminalDiagnostic: F } : {},
...L ? { validationErrorSummary: L } : {},
...t.executionStarted === false && t.errorKind === "unknown-tool" ? { unknownTool: true } : {},
timedOut: isToolResultTimedOut(l) || void 0,
middlewareError: isMiddlewareToolResultError(l) || void 0
} } : {}
});
e.state.lastToolError = R.lastToolError;
const z = R.executionStarted ? "failed" : "blocked";
const B = e.state.lastToolError ? summarizeToolValidationError(e.state.lastToolError) : void 0;
if (E) e.state.hadDeterministicSideEffect = true;
if (R.sideEffectEvidence || M || E) e.state.replayState = mergeEmbeddedRunReplayState(e.state.replayState, {
replayInvalid: true,
hadPotentialSideEffects: true
});
const V = applyCurrentMessageProvider(r, x, e.params.messageChannel);
const H = isMessagingTool(r);
const U = H && isMessagingToolSendAction(r, x);
const W = H && isMessagingToolTargetEvidenceAction(r, x);
const G = readEmbeddedMessageDeliveryFact(readToolResultDetails(s)?.messageDelivery);
const K = H && (G ? G.status === "settled" && (!d || G.partialDelivery) : isPluginNativeMessagingTool(r) && isDeliveredMessagingToolResult({
toolName: r,
args: x,
result: o,
hookResult: s,
isError: d
}));
const q = U ? readMessagingText(x) : void 0;
const J = U ? collectMessagingMediaUrlsFromRecord(x) : [];
const Y = U && hasMessagingRichContent(x);
const ee = W ? extractMessagingToolSend(r, V, {
config: e.params.config,
currentChannelId: e.params.currentChannelId,
currentMessagingTarget: e.params.currentMessagingTarget,
currentThreadId: e.params.currentThreadId,
currentMessageId: e.params.currentMessageId,
replyToMode: e.params.replyToMode,
hasRepliedRef: m?.hasRepliedRef
}) : void 0;
const X = K && U ? [...J, ...collectMessagingMediaUrlsFromToolResult(o)] : [];
const te = applyToolSendReceiptForExtraction(o, s);
const Z = ee && extractMessagingToolSendResult(ee, te);
const ne = K && isDeliveredMessageToolOnlySourceReplyResult({
sourceReplyDeliveryMode: e.params.sourceReplyDeliveryMode,
toolName: r,
args: x,
result: o,
hookResult: s,
isError: d,
allowExplicitSourceRoute: isDeliveredMessagingToolSendToCurrentSource({
send: Z,
config: e.params.config,
currentProvider: e.params.messageChannel,
currentAccountId: e.params.currentAccountId,
currentChannelId: e.params.currentChannelId,
currentMessagingTarget: e.params.currentMessagingTarget,
currentThreadId: e.params.currentThreadId,
sessionKey: e.params.sessionKey,
deliveredPayload: te
}),
deliveryConfirmed: K
});
const re = ne || isDeliveredCoreCurrentChannelWidgetResult({
coreBuiltinToolNames: e.params.coreBuiltinToolNames,
sourceReplyDeliveryMode: e.params.sourceReplyDeliveryMode,
toolName: r,
result: o,
isToolError: d
});
const Q = ne || G?.sourceReplyDelivered ? resolveMessageToolSourceReplyFinal(x, e.params.messageToolFinalByDefault) : void 0;
e.state.sourceReplyDelivered ||= G?.sourceReplyDelivered;
if (Q !== false && (G?.sourceReplyDelivered || re)) e.state.sourceReplyDeliveryState = "delivered";
if (K && q) {
e.state.messagingToolSentTexts.push(q);
e.state.messagingToolSentTextsNormalized.push(normalizeTextForComparison(q));
e.trimMessagingToolSent();
}
if (K && Z) {
e.state.messagingToolSentTargets.push({
...Z,
...q ? { text: q } : {},
...X.length > 0 ? { mediaUrls: X.slice() } : {},
...Y ? { hasRichContent: true } : {},
...Q !== void 0 ? { sourceReplyFinal: Q } : {}
});
e.trimMessagingToolSent();
}
if (re) {
e.state.messageToolOnlySourceReplyDelivered = true;
if (ne) {
const t = readMessageToolSourceReplyText(x);
const n = t ? normalizeTextForComparison(t) : "";
if (n) {
e.state.currentSourceMessagingToolSentTextsNormalized.push(n);
e.trimMessagingToolSent();
}
}
e.params.onDeliveredMessageToolOnlySourceReply?.();
}
if (K && U) {
if (X.length > 0) {
e.state.messagingToolSentMediaUrls.push(...X);
e.trimMessagingToolSent();
}
const t = extractMessagingToolSourceReplyPayload(o);
if (t) {
e.state.messagingToolSourceReplyPayloads.push({
...t,
...Q !== void 0 ? { sourceReplyFinal: Q } : {}
});
e.trimMessagingToolSent();
}
}
e.state.turnToolsOnlySourceProgress = (e.state.turnToolsOnlySourceProgress ?? true) && Q === false && U && !d && !G?.partialDelivery;
e.state.lastToolTurnOnlySourceProgress = e.state.turnToolsOnlySourceProgress;
if (!d && (isAutomationsToolName(r) && isCronAddAction(x) || isExecToolName(r) && didShellCronAddSucceed(x, o))) e.state.successfulCronAdds += 1;
const ie = !d && r === "progress_card" ? projectProgressCardChannelUpdate(x) : void 0;
const ae = Date.now();
const $ = readExecToolDetails(l);
const oe = S || readAutomationDisplayState(a) !== "ordinary" && !d && $?.status !== "approval-pending" && $?.status !== "approval-unavailable";
const se = {
...projectAgentToolActivity({
toolCallId: i,
name: r,
phase: "result",
args: x,
meta: T,
result: l,
status: d ? z : "completed",
hideFromChannelProgress: oe
}),
startedAt: m?.startTime,
endedAt: ae,
...N ? { error: N } : {}
};
e.state.itemActiveIds.delete(se.itemId);
e.state.itemCompletedCount += 1;
const createResultData = () => ({
phase: "result",
name: r,
toolCallId: i,
...m?.parentToolCallId ? { parentToolCallId: m.parentToolCallId } : {},
meta: T,
isError: d,
commandBearing: C.commandBearing,
...B ? { toolErrorSummary: B } : {},
...oe ? { hideFromChannelProgress: true } : {}
});
const ce = e.hookRunner ?? (await loadHookRunnerGlobal()).getGlobalHookRunner();
if (ce?.hasHooks("after_tool_call")) {
const t = m?.startTime != null ? Date.now() - m.startTime : void 0;
const n = {
toolName: r,
params: _ === void 0 ? x : structuredClone(x),
runId: a,
toolCallId: i,
result: l,
error: d ? extractToolErrorMessage(l) : void 0,
durationMs: t
};
ce.runAfterToolCall(n, {
toolName: r,
agentId: e.params.agentId,
sessionKey: e.params.sessionKey,
sessionId: e.params.sessionId,
runId: a,
toolCallId: i
}).catch((t) => {
e.log.warn(`after_tool_call hook failed: tool=${r} error=${String(t)}`);
});
}
R.executedArguments ??= x;
let le;
const publishPresentation = () => le ??= publish();
return Object.assign(R, {
isError: c,
publishPresentation
});
async function publish() {
if (ie) {
const t = {
stream: "plan",
data: {
phase: "update",
title: "Plan updated",
source: "openclaw",
...ie
}
};
emitAgentEvent({
runId: e.params.runId,
...t
});
emitAgentEventCallbackBestEffort(e, t);
}
j.activity = se;
emitAgentEvent({
runId: e.params.runId,
stream: "tool",
data: {
...createResultData(),
result: f
}
});
emitToolActivityEvent(e, {
stream: "item",
data: se
});
emitAgentEventCallbackBestEffort(e, {
stream: "tool",
data: createResultData()
});
if (isExecToolName(r)) {
const t = buildCommandItemId(i);
if ($?.status === "approval-pending" || $?.status === "approval-unavailable") {
const n = $.status === "approval-pending" ? "pending" : "unavailable";
emitToolActivityEvent(e, {
stream: "approval",
data: {
phase: "requested",
kind: "exec",
status: n,
title: n === "pending" ? "Command approval requested" : "Command approval unavailable",
itemId: t,
toolCallId: i,
...$.status === "approval-pending" ? {
approvalId: $.approvalId,
approvalSlug: $.approvalSlug
} : {},
command: $.command,
host: $.host,
...$.status === "approval-unavailable" ? { reason: $.reason } : {},
message: $.warningText
}
});
} else {
const n = extractLiveExecOutput(l);
const a = extractExecOutput(l);
const o = $?.status === "failed" || d ? z : "completed";
emitToolActivityEvent(e, {
stream: "command_output",
data: {
itemId: t,
phase: "end",
title: buildCommandItemTitle(r, T),
toolCallId: i,
name: r,
...n ? { output: n } : {},
status: o,
...$ && "exitCode" in $ ? { exitCode: $.exitCode } : {},
...$ && "durationMs" in $ && typeof $.durationMs === "number" && Number.isFinite($.durationMs) && $.durationMs >= 0 ? { durationMs: $.durationMs } : {},
...$ && "cwd" in $ && typeof $.cwd === "string" ? { cwd: $.cwd } : {}
}
});
if (typeof a === "string") {
const n = parseExecApprovalResultText(a);
if (n.kind === "denied") emitToolActivityEvent(e, {
stream: "approval",
data: {
phase: "resolved",
kind: "exec",
status: normalizeOptionalLowercaseString(n.metadata)?.includes("approval-request-failed") ? "failed" : "denied",
title: "Command approval resolved",
itemId: t,
toolCallId: i,
message: n.body || n.raw
}
});
}
}
}
if (resolveFileMutationToolName(r) === "apply_patch") {
const t = readApplyPatchSummary(l);
const n = `patch:${i}`;
if (t) emitToolActivityEvent(e, {
stream: "patch",
data: {
itemId: n,
phase: "end",
title: T ? `patch ${T}` : "apply patch",
toolCallId: i,
name: r,
added: t.added,
modified: t.modified,
deleted: t.deleted,
summary: buildPatchSummaryText(t)
}
});
}
if (!ie) await emitToolResultOutput({
ctx: e,
toolName: r,
rawToolName: t.toolName,
meta: T,
isToolError: d,
result: o,
sanitizedResult: l
});
await Promise.resolve(e.params.onToolStreamBoundary?.()).catch((t) => {
e.log.debug(`embedded run tool stream boundary callback failed: ${String(t)}`);
});
}
}
/** Ordinary provider tool results have no separate nested-activity commit boundary. */
async function handleToolExecutionEnd(e, t, n) {
const r = await prepareToolExecutionEnd(e, t, n);
await r.publishPresentation();
return r;
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.tools.progress.ts
const LIVE_EXEC_UPDATE_MIN_INTERVAL_MS = 250;
function readChannelToolProgress(e) {
const t = asOptionalRecord(asOptionalObjectRecord(e)?.progress);
if (t?.visibility !== "channel" || t.privacy !== "public") return;
const n = readStringValue(t.text)?.trim();
return n ? truncateLiveExecOutput(n) : void 0;
}
function prepareLiveExecUpdate(e, t, n, r) {
const i = Date.now();
const a = e.state.execLiveUpdateStateById ??= /* @__PURE__ */ new Map();
const o = a.get(t);
if (o && i - o.lastEmittedAtMs < LIVE_EXEC_UPDATE_MIN_INTERVAL_MS) {
const e = o.itemMetadata.name !== r.name || o.itemMetadata.meta !== r.meta || o.itemMetadata.commandBearing !== r.commandBearing || o.itemMetadata.hideFromChannelProgress !== r.hideFromChannelProgress;
if (e) o.itemMetadata = r;
return { emitItems: e };
}
const s = sanitizeToolResult(n);
const c = extractLiveExecOutput(s);
const l = capLiveExecResult(s);
a.set(t, {
lastEmittedAtMs: Date.now(),
itemMetadata: r
});
return {
update: {
result: l,
output: c
},
emitItems: true
};
}
/** Handles partial tool output and emits throttled live UI updates. */
function handleToolExecutionUpdate(e, t) {
const n = normalizeToolPolicyName(t.toolName);
const r = t.toolCallId;
const i = toolStartData.get(buildToolStartKey(e.params.runId, r));
const a = i?.parentToolCallId;
const o = peekAdjustedParamsForToolCall(r, e.params.runId) ?? i?.args;
if (i && t.hideFromChannelProgress === true) i.hideFromChannelProgress = true;
const s = t.hideFromChannelProgress === true || i?.hideFromChannelProgress === true;
const c = readAutomationDisplayState(e.params.runId) !== "ordinary";
const l = t.partialResult;
const u = isExecToolName(n);
const d = e.state.toolMetaById.get(r);
const f = u ? prepareLiveExecUpdate(e, r, l, {
name: n,
meta: d?.meta,
commandBearing: d?.commandBearing,
hideFromChannelProgress: s || c
}) : void 0;
const p = f?.update;
const m = u ? p?.result : sanitizeToolResult(l);
const h = u ? void 0 : readChannelToolProgress(m);
const g = s || c && !h;
const _ = {
...projectAgentToolActivity({
toolCallId: r,
name: n,
phase: "update",
args: o,
meta: d?.meta,
hideFromChannelProgress: g
}),
commandBearing: d?.commandBearing,
...h ? {
progressText: h,
meta: void 0
} : {}
};
const updateData = (e) => ({
phase: "update",
name: n,
toolCallId: r,
...a ? { parentToolCallId: a } : {},
...e ? { partialResult: m } : {},
...g ? { hideFromChannelProgress: true } : {}
});
const v = !h && (!u || p !== void 0);
if (v) emitAgentEvent({
runId: e.params.runId,
stream: "tool",
data: updateData(true)
});
emitTrackedItemEvent(e, _, f?.emitItems);
if (!h) emitAgentEventCallbackBestEffort(e, {
stream: "tool",
data: updateData(false)
});
if (u) {
const t = p?.output;
if (v && t) {
const i = {
itemId: buildCommandItemId(r),
phase: "delta",
title: buildCommandItemTitle(n, d?.meta),
toolCallId: r,
name: n,
output: t,
status: "running"
};
emitToolActivityEvent(e, {
stream: "command_output",
data: i
});
}
}
}
//#endregion
//#region src/agents/embedded-agent-subscribe.trajectory.ts
function recordEmbeddedToolTrajectoryEvent(e, t, n) {
const r = e.params.trajectoryRecorder;
if (!r) return;
try {
if (t.type === "tool_execution_start") r.recordEvent("tool.call", {
toolCallId: t.toolCallId,
name: normalizeToolPolicyName(t.toolName),
args: t.args
});
else if (t.type === "tool_execution_end") {
const e = normalizeToolPolicyName(t.toolName);
const i = n();
r.recordEvent("tool.result", {
toolCallId: t.toolCallId,
name: e,
success: !(t.isError || isToolResultError(t.result)),
result: isExecToolName(e) ? capLiveExecResult(i) : i
});
}
} catch (t) {
e.log.debug(`tool trajectory capture failed: ${String(t)}`);
}
}
//#endregion
//#region src/agents/embedded-agent-subscribe.handlers.ts
/**
* Dispatches serialized embedded-agent subscription events to specific handlers.
*/
/** Create the serialized event dispatcher for subscribed embedded-agent sessions. */
function createEmbeddedAgentSessionEventHandler(e) {
let t;
const scheduleEvent = (t, n) => {
const run = () => {
try {
if (t.type !== "message_update") e.flushAssistantStream();
return n();
} catch (n) {
e.log.debug(`${t.type} handler failed: ${String(n)}`);
return;
}
};
const r = e.state.pendingEventChain ? e.state.pendingEventChain.then(run) : run();
if (!isPromiseLike(r)) return;
const settle = async () => {
try {
await r;
} catch (n) {
e.log.debug(`${t.type} handler failed: ${String(n)}`);
} finally {
if (e.state.pendingEventChain === i) e.state.pendingEventChain = null;
}
};
const i = settle();
e.state.pendingEventChain = i;
return i;
};
return (n) => {
if ((n.type === "message_start" || n.type === "message_update" || n.type === "message_end") && n.message.role === "assistant" && !isSubscribeTranscriptOnlyOpenClawAssistantMessage(n.message)) {
if (n.type === "message_start" || !t) t = {};
bindAgentAssistantSource(n.message, t);
}
const r = e.captureModelEvent(n);
const i = n.type === "tool_execution_end" ? prepareToolResult(n.result) : void 0;
recordEmbeddedToolTrajectoryEvent(e, n, i);
switch (n.type) {
case "message_start":
scheduleEvent(n, () => handleMessageStart(e, n));
return;
case "message_update":
scheduleEvent(n, () => handleMessageUpdate(e, n));
return;
case "message_end":
scheduleEvent(n, () => handleMessageEnd(e, n, r));
return;
case "turn_start":
scheduleEvent(n, () => {
e.state.turnToolsOnlySourceProgress = void 0;
});
return;
case "turn_end":
scheduleEvent(n, () => e.noteLastAssistant(n.message));
return;
case "tool_execution_start":
scheduleEvent(n, () => handleToolExecutionStart(e, n));
return;
case "tool_execution_update":
scheduleEvent(n, () => handleToolExecutionUpdate(e, n));
return;
case "tool_execution_end":
scheduleEvent(n, () => handleToolExecutionEnd(e, n, i));
return;
case "agent_start":
scheduleEvent(n, () => handleAgentStart(e));
return;
case "compaction_start":
scheduleEvent(n, () => handleCompactionStart(e, n));
return;
case "compaction_end":
scheduleEvent(n, () => handleCompactionEnd(e, n));
return;
case "agent_end": return scheduleEvent(n, () => handleAgentEnd(e, n));
}
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.model-state.ts
function preserveAssistantUsage(e, t) {
if (!t || e.usage.usageReport?.state === "unavailable") return;
const n = normalizeUsage(e.usage);
if (hasNonzeroUsage(n)) {
if (t.cost?.totalOrigin === "provider-billed" && n.cost?.totalOrigin !== "provider-billed") e.usage.cost = {
...makeZeroUsageSnapshot().cost,
...e.usage.cost,
...t.cost
};
return;
}
const r = t.input ?? 0;
const i = t.output ?? 0;
const a = t.cacheRead ?? 0;
const o = t.cacheWrite ?? 0;
const s = {
...makeZeroUsageSnapshot(),
input: r,
output: i,
cacheRead: a,
cacheWrite: o,
...t.cacheWrite1h !== void 0 ? { cacheWrite1h: t.cacheWrite1h } : {},
...t.cacheWrite5m !== void 0 ? { cacheWrite5m: t.cacheWrite5m } : {},
...t.contextUsage ? { contextUsage: { ...t.contextUsage } } : {},
...t.usageReport ? { usageReport: { ...t.usageReport } } : {},
totalTokens: t.total ?? r + i + a + o,
...t.reasoningTokens !== void 0 ? { reasoningTokens: t.reasoningTokens } : {}
};
e.usage = s;
Object.assign(s.cost, t.cost);
}
/** Owns model facts at event ingress, independently of queued reply delivery. */
function createEmbeddedModelState(e, t) {
const n = createUsageAccumulator();
let r;
let i;
let a;
let o;
let s = false;
let c;
const l = getAgentRunContext(e.runId);
const publishMessageModel = (t, n) => {
if (n) c = void 0;
const r = t.provider?.trim();
const i = t.responseModel?.trim() || t.model?.trim();
const a = r && i ? `${r}\0${i}` : void 0;
if (!a || a === c) return;
const o = {
runId: e.runId,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
agentId: e.agentId,
lifecycleGeneration: e.lifecycleGeneration,
stream: "lifecycle",
data: {
phase: "model",
provider: r,
model: i
}
};
if (l) emitAgentEventForRunContext(o, l);
else emitAgentEvent(o);
c = a;
};
const recordPendingUsage = (e) => {
const t = normalizeUsage(e);
if (!hasObservedModelUsage(t)) return;
const n = t.cost;
const i = !t.usageReport && r && !hasNonzeroUsage(t) ? {
...r,
cost: n
} : t;
if (t.usageReport?.state !== "unavailable" && r?.cost?.totalOrigin === "provider-billed" && n?.totalOrigin !== "provider-billed") i.cost = r.cost;
r = i;
};
const recordModelUsage = (r) => {
if (!hasObservedModelUsage(r)) return;
mergeUsageIntoAccumulator(n, r);
if (!r.usageReport && !hasNonzeroUsage(r) || !e.lifecycleGeneration) return;
const i = emitAgentRunOutputTokens({
runId: e.runId,
lifecycleGeneration: e.lifecycleGeneration,
outputTokens: r.output ?? 0,
usageReport: r.usageReport
});
if (i && e.onAgentEvent) runBestEffortCallback({
label: "usage agent event",
log: t,
callback: () => e.onAgentEvent?.({
stream: "usage",
data: i
})
});
};
const recordContextAccounting = (t, n) => e.onContextAccountingEvent?.({
kind: "model",
contextTokens: deriveSessionTotalTokens({ lastCallUsage: normalizeUsage(t.usage) }),
successful: n
});
return {
captureModelEvent: (n) => {
if (n.type === "compaction_end") {
if (n.outcome.status === "completed" && n.outcome.willRetry) {
o = void 0;
a = i ?? a;
i = void 0;
}
return;
}
if (n.type !== "message_start" && n.type !== "message_update" && n.type !== "message_end" && n.type !== "turn_end") return;
const c = n.message;
if (c.role !== "assistant" || isSubscribeTranscriptOnlyOpenClawAssistantMessage(c)) return;
publishMessageModel(c, n.type === "message_start");
switch (n.type) {
case "turn_end":
if (!s && (c.stopReason === "stop" || c.stopReason === "toolUse") && !isProviderRefusalAssistantError(c)) {
s = true;
recordContextAccounting(c, true);
}
return;
case "message_start":
r = void 0;
return;
case "message_update":
if (n.assistantMessageEvent.type === "text_end") recordPendingUsage(c.usage);
return;
case "message_end": {
recordPendingUsage(c.usage);
preserveAssistantUsage(c, r);
if (r?.usageReport || hasNonzeroUsage(r)) i = { ...r };
recordModelUsage(r);
runBestEffortCallback({
label: "model usage observation",
log: t,
callback: () => e.onModelUsage?.(r, {
responseId: c.responseId,
turnId: c.turnId
})
});
r = void 0;
const { snapshot: n, reasoning: s } = snapshotAssistantMessage(c);
o = applyAssistantDeliveryDirectives(n);
const l = readAgentAssistantSource(c);
if (l) bindAgentAssistantSource(o, l);
for (let e = 0; e < c.content.length; e += 1) {
const t = c.content[e];
const n = o.content[e];
if (t?.type === "text" && n?.type === "text") n.text = t.text;
}
i ??= c.stopReason === "error" ? a : void 0;
a = void 0;
recordContextAccounting(c, false);
return s;
}
}
},
recordAuxiliaryUsage: (e) => recordModelUsage(normalizeUsage(e)),
getUsageTotals: () => toNormalizedUsage(n),
getLastAssistantUsage: () => normalizeUsage(i),
getCurrentAttemptAssistant: () => o,
hasSuccessfulModelResponse: () => s
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.reply-delivery.ts
const isStreamAppend = ({ data: e, finalMessage: t }) => !t && !e.replace && !e.mediaUrls?.length && !e.managedMediaUrls?.length;
const mergeStreamAppend = (e, t) => ({
...t,
delta: e.delta + t.delta
});
function createReplyDelivery({ params: e, state: t, log: n }) {
const r = t.assistantTexts;
const i = [];
const a = /* @__PURE__ */ new Map();
const o = /* @__PURE__ */ new Set();
const s = /* @__PURE__ */ new Set();
let c = {};
const drainPartialReply = (r, i = false) => {
if (!r.delivery || !r.pending || t.unsubscribed || r === c && r.active) return;
const a = Date.now();
if (!i && r === c && isStreamAppend(r.delivery) && a < (r.nextPartialReplyAt ?? 0)) return;
r.nextPartialReplyAt = a + 75;
let o = r.delivery.data;
const l = r.preview ??= createTextProjection([plainToolCallPreviewTextFilter, trimTextFilter("both", { preserveCodeIndentation: true })]);
const u = l.source !== l.text;
const d = !o.replace && o.text.length === l.source.length + o.delta.length ? l.append(o.delta, o.text) : l.replace(o.text);
if (u || d.text !== o.text) o = {
...o,
text: d.text,
delta: d.text,
replace: true
};
r.pending = false;
r.active = true;
const settled = () => {
if (r === c) {
r.active = false;
drainPartialReply(r);
}
};
runBestEffortCallback({
callback: () => e.onPartialReply?.(o),
label: "assistant partial reply",
log: n,
pending: s,
onSuccess: settled,
onError: settled
});
};
const l = randomUUID();
let u = -1;
let d = "";
const f = {
text: "",
prefix: "",
blockIndex: -1
};
const p = { ...f };
let m = "";
let h = false;
const advanceStream = (e, n, r) => {
if (e.blockIndex !== t.assistantMessageIndex) {
e.prefix = e.text;
e.blockIndex = t.assistantMessageIndex;
}
const i = r ? n.text : e.prefix && n.text ? `${e.prefix}\n${n.text}` : e.prefix || n.text;
const a = r ? !i.startsWith(e.text) : n.replace === true;
const o = r ? a ? "" : i.slice(e.text.length) : e.prefix && e.text.length === e.prefix.length && n.delta ? `\n${n.delta}` : n.delta;
const s = i !== e.text || n.mediaUrls?.length || n.managedMediaUrls?.length ? {
...n,
text: i,
delta: o,
replace: a || void 0,
itemId: d
} : void 0;
e.text = i;
return s;
};
const publishAgentEvent = (t, r, i) => {
const a = {
runId: e.runId,
lifecycleGeneration: e.lifecycleGeneration,
...t
};
if (!emitAgentEventWithAssistantSourceIfCurrent(a, r, i)) return;
if (e.onAgentEvent) runBestEffortCallback({
label: "assistant agent event",
log: n,
callback: () => e.onAgentEvent?.(t)
});
};
const emitAssistantStreamDataSafely = (n) => {
if (!n.delivery || n.emitted || t.unsubscribed) return;
const r = n.delivery;
const { eventData: i } = r;
n.emitted = true;
n.pending ||= r.emitPartialReply && Boolean(e.onPartialReply) && t.shouldEmitPartialReplies;
const o = i?.itemId ?? "";
const s = i?.phase === "commentary" ? i.text.trimEnd() : "";
const c = r.finalMessage ? "end" : "update";
const l = `${c}\0${s}`;
const u = s.trim() ? {
stream: "item",
data: {
kind: "preamble",
title: "Preamble",
phase: c,
progressText: s,
...o ? { itemId: o } : {}
}
} : !i || i.phase === "commentary" ? void 0 : {
stream: "assistant",
data: i
};
if (u && (u.stream !== "item" || a.get(o) !== l)) {
if (u.stream === "item") a.set(o, l);
publishAgentEvent(u, r.assistantSource, r.assistantProjection);
}
drainPartialReply(n);
};
const emitAssistantStreamData = (n, r) => {
if (t.unsubscribed) return;
const a = readAgentAssistantSource(t.lastAssistant);
let o;
let s;
if (n.phase === "commentary") {
if (u === t.assistantMessageStartIndex && p.text !== m) {
p.prefix = p.text = m;
s = {
itemId: d,
text: m,
replace: true
};
for (const e of [c, ...i]) {
const t = e.delivery;
if (t && t.blockIndex >= u && t.data.phase !== "final_answer") t.assistantProjection = s;
}
}
o = n;
} else {
if (u !== t.assistantMessageStartIndex) {
u = t.assistantMessageStartIndex;
d = `${l}:${u}`;
for (const e of [f, p]) {
e.prefix = e.text = "";
e.blockIndex = t.assistantMessageIndex;
}
m = "";
h = false;
}
if (!h || r?.finalMessage) {
o = advanceStream(f, n, r?.finalMessage === true);
const e = advanceStream(p, n, r?.finalMessage === true);
s = r?.finalMessage || e?.replace ? {
itemId: d,
text: p.text,
replace: e?.replace === true
} : {
itemId: d,
delta: e?.delta ?? "",
replace: false
};
if (o && !o.replace) s.rawDelta = o.delta;
m = n.phase === "final_answer" ? p.text : !e?.replace || p.text.startsWith(m) ? m : "";
h = r?.finalMessage === true;
}
if (r?.finalMessage && t.lastAssistant?.stopReason === "error") {
const n = d;
const r = f.text;
const i = p.text;
e.assistantErrorTranscript?.bindStream(t.lastAssistant, (e) => {
clearAssistantStream();
publishAgentEvent({
stream: "assistant",
data: {
itemId: n,
text: e ? r : "",
delta: "",
replace: true
}
}, a, {
itemId: n,
text: e ? i : "",
replace: true
});
});
}
}
const g = {
assistantSource: a,
assistantProjection: s,
data: n,
eventData: o,
emitPartialReply: r?.emitPartialReply === true,
finalMessage: r?.finalMessage === true,
blockIndex: t.assistantMessageIndex
};
if (!o && !g.emitPartialReply) return;
const _ = c.delivery;
const v = t.deferBlockReplyDelivery && n.phase !== "commentary";
const y = _ && isStreamAppend(_) && isStreamAppend(g) && _.blockIndex === g.blockIndex && _.assistantSource === g.assistantSource && _.data.phase === n.phase && _.data.itemId === n.itemId && _.emitPartialReply === g.emitPartialReply && Boolean(_.eventData) === Boolean(o);
const b = y ? c : flushAssistantStream(g);
if (y) {
if (!b.emitted || b.pending) g.data = mergeStreamAppend(_.data, n);
if (!b.emitted && _.eventData && o) {
g.eventData = mergeStreamAppend(_.eventData, o);
if (_.assistantProjection?.rawDelta !== void 0 && g.assistantProjection?.rawDelta !== void 0) g.assistantProjection.rawDelta = _.assistantProjection.rawDelta + g.assistantProjection.rawDelta;
if (_.assistantProjection?.delta !== void 0 && g.assistantProjection?.delta !== void 0) g.assistantProjection = {
...g.assistantProjection,
delta: _.assistantProjection.delta + g.assistantProjection.delta
};
}
b.delivery = g;
b.emitted = false;
}
if (!v) emitAssistantStreamDataSafely(b);
};
const flushAssistantStream = (e) => {
const n = c;
const r = { delivery: e };
c = r;
if (e && t.deferBlockReplyDelivery && e.data.phase !== "commentary") i.push(r);
if (!t.deferBlockReplyDelivery) for (const e of i.splice(0)) {
emitAssistantStreamDataSafely(e);
e.delivery = void 0;
}
if (!t.deferBlockReplyDelivery || n.delivery?.data.phase === "commentary") {
emitAssistantStreamDataSafely(n);
drainPartialReply(n);
n.delivery = void 0;
}
return r;
};
const clearAssistantStream = () => {
c.delivery = void 0;
c = {};
i.length = 0;
};
const noteLastAssistant = (e) => {
if (e.role === "assistant") t.lastAssistant = e;
};
const g = /* @__PURE__ */ new WeakMap();
const emitBlockReplySafely = (r, i) => {
if (!e.onBlockReply) return;
const a = getReplyPayloadMetadata(r)?.assistantMessageIndex;
runBestEffortCallback({
callback: () => a === void 0 ? e.onBlockReply?.(r) : e.onBlockReply?.(r, { assistantMessageIndex: a }),
label: "block reply",
log: n,
pending: o,
onSuccess: () => {
if (!r.isReasoning && hasAssistantVisibleReply(r)) {
t.visibleBlockReplyCount += 1;
if (i?.pendingToolMedia) {
t.pendingToolMediaDeliveryFailed = false;
t.hasToolMediaBlockReply = true;
}
for (const e of i?.autoDeliveryMediaUrls ?? []) t.toolAutoDeliveryMediaUrls.delete(e);
}
},
onError: () => {
if (i?.pendingToolMedia) restorePendingToolMediaReply(t, i.pendingToolMedia);
}
});
};
const emitBlockReply = (n, r) => {
flushAssistantStream();
const i = consumePendingAssistantReplyDirectivesIntoReply(t, n);
const a = n.isReasoning || r?.consumePendingToolMedia === false ? null : readPendingToolMediaReply(t);
const o = r?.consumePendingToolMedia === false ? i : consumePendingToolMediaIntoReply(t, i);
const s = new Set(t.messagingToolSentMediaUrls.map((e) => e.trim()));
const c = e.sourceReplyDeliveryMode === "message_tool_only" ? (a?.mediaUrls ?? []).filter((e) => t.toolAutoDeliveryMediaUrls.has(e.trim()) && !s.has(e.trim())) : [];
const l = new Map((a?.mediaUrls ?? []).map((e, t) => [e.trim(), a?.attachments?.[t] ?? {}]));
const u = c.length === 0 ? o : markReplyPayloadForSourceSuppressionDelivery({
mediaUrls: c,
mediaUrl: c[0],
attachments: c.map((e) => l.get(e.trim()) ?? {}),
audioAsVoice: a?.audioAsVoice || void 0,
trustedLocalMedia: true
});
const d = Array.from(new Set(n.mediaUrls ?? []));
copyReplyPayloadMetadata(n, u);
if (e.silentExpected && !shouldKeepPayloadDuringSilentTurn(u)) return;
if (d.length > 0 || getReplyPayloadMetadata(n)?.assistantMediaFailures?.length) setReplyPayloadMetadata(u, { assistantTranscriptSource: readAgentAssistantSource(t.lastAssistant) });
const f = r?.assistantMessageIndex !== void 0 ? setReplyPayloadMetadata(u, {
assistantMessageIndex: r.assistantMessageIndex,
assistantMessageStartIndex: t.assistantMessageStartIndex,
...d.length > 0 ? { assistantTranscriptMediaUrls: d } : {}
}) : u;
if (u.text && r?.blockSourceText !== void 0) setReplyPayloadMetadata(f, {
blockSourceText: r.blockSourceText,
blockSourceRange: r.blockSourceRange
});
if (t.deferBlockReplyDelivery) {
if (a) g.set(f, {
pendingToolMedia: a,
autoDeliveryMediaUrls: c
});
t.deferredBlockReplies.push(f);
return;
}
emitBlockReplySafely(f, {
pendingToolMedia: a,
autoDeliveryMediaUrls: c
});
};
const releaseDeferredReplies = () => {
const isSuperseded = (e) => {
if (e === void 0) return false;
return e < (t.answerSegments.find((t) => e <= t.messageEnd)?.finalMessageStart ?? t.assistantMessageStartIndex);
};
for (const e of i) {
const t = e.delivery;
if (t && isSuperseded(t.blockIndex)) {
if (!t.data.mediaUrls?.length) e.delivery = void 0;
else {
t.data = {
...t.data,
text: "",
delta: ""
};
if (t.eventData) t.eventData = {
...t.eventData,
text: "",
delta: ""
};
if (t.assistantProjection) t.assistantProjection = {
itemId: t.assistantProjection.itemId,
replace: t.assistantProjection.replace,
text: ""
};
}
}
}
const e = t.deferredBlockReplies.splice(0);
for (const t of e) {
const e = getReplyPayloadMetadata(t)?.assistantMessageIndex;
if (!t.isReasoning && isSuperseded(e)) {
t.text = void 0;
setReplyPayloadMetadata(t, { blockSourceText: void 0 });
}
}
t.deferBlockReplyDelivery = false;
flushAssistantStream();
for (const t of e) {
if (!hasAssistantVisibleReply(t)) continue;
const e = g.get(t);
emitBlockReplySafely(t, e);
}
};
const clearDeferredBlockReplies = () => {
t.deferredBlockReplies.length = 0;
};
const rememberAssistantText = (e, n) => {
t.lastAssistantTextMessageIndex = t.assistantMessageIndex;
t.lastAssistantTextContentIndex = t.lastAssistantStreamContentIndex;
t.lastAssistantTextItemId = t.lastAssistantStreamItemId;
t.lastAssistantTextTrimmed = e.trimEnd();
const r = n ?? normalizeTextForComparison(e);
t.lastAssistantTextNormalized = r.length > 0 ? r : void 0;
};
const shouldSkipAssistantText = (e, n) => {
if (t.lastAssistantTextMessageIndex !== t.assistantMessageIndex || t.lastAssistantTextContentIndex !== t.lastAssistantStreamContentIndex) return false;
const r = e.trimEnd();
if (r && r === t.lastAssistantTextTrimmed) return true;
const i = n ?? normalizeTextForComparison(e);
return i.length > 0 && i === t.lastAssistantTextNormalized;
};
const pushAssistantText = (t, n) => {
if (!t || e.silentExpected || shouldSkipAssistantText(t, n)) return;
r.push(t);
rememberAssistantText(t, n);
};
const replaceCurrentAssistantText = (e) => {
const n = r.length - t.assistantTextBaseline;
if (!e) r.splice(t.assistantTextBaseline, n);
else if (n > 0) {
r.splice(t.assistantTextBaseline, n, e);
rememberAssistantText(e);
} else pushAssistantText(e);
};
const finalizeAssistantTexts = (n) => {
const { text: i, addedDuringMessage: a, chunkerHasBuffered: o } = n;
if (t.hasFlushedPartialText) {
replaceCurrentAssistantText(i);
t.hasFlushedPartialText = false;
} else if (t.includeReasoning && i && !e.onBlockReply) {
replaceCurrentAssistantText(i);
t.suppressBlockChunks = true;
} else if (!a && i && !o) pushAssistantText(i);
t.assistantTextBaseline = r.length;
};
const waitForPendingEvents = async (e) => {
const n = e?.includePartialReplies !== false;
while (true) {
const e = t.pendingEventChain;
if (!e && n) drainPartialReply(c, true);
const r = n ? [...s] : [];
if (!e && r.length === 0) return;
await Promise.allSettled([...e ? [e] : [], ...r]);
}
};
return {
assistantTexts: r,
clearAssistantStream,
clearDeferredBlockReplies,
emitAssistantStreamData,
emitBlockReply,
finalizeAssistantTexts,
flushAssistantStream,
noteLastAssistant,
releaseDeferredReplies,
pendingBlockReplyTasks: o,
pushAssistantText,
replaceCurrentAssistantText,
shouldSkipAssistantText,
waitForPendingEvents
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.run-state.ts
/** Mutable subscription state shared by embedded-agent event handlers. */
var EmbeddedAgentSubscribeState = class {
setTerminalLifecycleMeta(e) {
if (e.replayInvalid !== void 0) this.replayState = {
...this.replayState,
replayInvalid: e.replayInvalid
};
if (e.livenessState) this.livenessState = e.livenessState;
if (e.stopReason !== void 0) this.terminalStopReason = e.stopReason;
if (e.yielded !== void 0) this.yielded = e.yielded;
if (e.timeoutPhase) this.timeoutPhase = e.timeoutPhase;
if (e.providerStarted !== void 0) this.providerStarted = e.providerStarted;
if (e.aborted !== void 0) this.terminalAborted = e.aborted;
}
constructor(e) {
this.assistantTexts = [];
this.answerSegments = [];
this.toolMetas = [];
this.acceptedSessionSpawns = [];
this.toolMetaById = /* @__PURE__ */ new Map();
this.toolSummaryById = /* @__PURE__ */ new Set();
this.liveEditDiffStateById = /* @__PURE__ */ new Map();
this.itemActiveIds = /* @__PURE__ */ new Set();
this.itemStartedCount = 0;
this.itemCompletedCount = 0;
this.assistantTurnCount = 0;
this.lastToolError = void 0;
this.deltaBuffer = "";
this.streamBlockText = "";
this.streamBlockFinal = false;
this.blockReplyScopeStart = void 0;
this.blockReplyTextUnsettled = false;
this.thinkingTagStream = createThinkingTagStreamState();
this.deltaBufferIsCommentary = false;
this.hasFlushedPartialText = false;
this.partialBlockState = createAssistantStreamBlockState();
this.lastAssistantAudioDirectiveCount = 0;
this.assistantStream = void 0;
this.lastStreamedReasoning = void 0;
this.lastBlockReplyText = void 0;
this.lastDeliveredBlockReplyText = void 0;
this.deferredBlockReplies = [];
this.toolExecutionSinceLastBlockReply = false;
this.reasoningStreamOpen = false;
this.assistantMessageIndex = 0;
this.assistantMessageStartIndex = 0;
this.lastAssistantStreamContentIndex = void 0;
this.lastAssistantStreamItemId = void 0;
this.lastAssistantTextMessageIndex = -1;
this.lastAssistantTextContentIndex = void 0;
this.lastAssistantTextItemId = void 0;
this.lastAssistantTextNormalized = void 0;
this.lastAssistantTextTrimmed = void 0;
this.assistantTextBaseline = 0;
this.suppressBlockChunks = false;
this.lastReasoningSent = void 0;
this.compactionInFlight = false;
this.lastCompactionTokensAfter = void 0;
this.pendingCompactionRetry = 0;
this.unsubscribed = false;
this.livenessState = "working";
this.hadDeterministicSideEffect = false;
this.pendingEventChain = null;
this.messagingToolSentTexts = [];
this.messagingToolSentTextsNormalized = [];
this.currentSourceMessagingToolSentTextsNormalized = [];
this.currentSourceMessagingToolHeldPartial = void 0;
this.messagingToolSentTargets = [];
this.messagingToolSentMediaUrls = [];
this.messagingToolSourceReplyPayloads = [];
this.messageToolOnlySourceReplyDelivered = false;
this.sourceReplyDeliveryState = "missing";
this.successfulCronAdds = 0;
this.toolAutoDeliveryMediaUrls = /* @__PURE__ */ new Set();
this.pendingToolAudioAsVoice = false;
this.pendingToolMediaDeliveryFailed = false;
this.hasToolMediaBlockReply = false;
this.visibleBlockReplyCount = 0;
this.pendingAssistantReplyDirectives = void 0;
this.deterministicApprovalPromptPending = false;
this.deterministicApprovalPromptSent = false;
const t = e.reasoningMode ?? "off";
const n = e.thinkingLevel !== "off";
const r = collectAgentInternalEventMedia(e.internalEvents);
this.blockReplyBreak = e.blockReplyBreak ?? "text_end";
this.reasoningMode = t;
this.includeReasoning = t === "on" && n;
this.shouldEmitPartialReplies = !(t === "on" && !e.onBlockReply);
this.streamReasoning = (e.streamReasoningInNonStreamModes === true ? t !== "on" : t === "stream") && n && typeof e.onReasoningStream === "function";
this.deferBlockReplyDelivery = typeof e.onBeforeTerminalDelivery === "function" && e.deferTerminalDelivery !== false;
this.replayState = createEmbeddedRunReplayState(e.initialReplayState);
this.pendingToolMediaUrls = r.mediaUrls;
this.pendingToolMediaAttachments = r.attachments;
this.pendingToolMediaTrustByUrl = r.trustByUrl;
}
};
//#endregion
//#region src/agents/embedded-agent-subscribe.stream-rendering.ts
function isPotentialTrailingFinalTagFragment(e) {
if (!e.startsWith("<") || e.includes(">")) return false;
const t = e.toLowerCase().slice(1).trimStart().replace(/^\//, "").trimStart();
if (!t) return true;
const n = t.split(/[\s/>]/, 1)[0] ?? "";
if (!n) return true;
return "final".startsWith(n);
}
function splitTrailingBlockTagFragment(e, t) {
for (let n = 0; n < e.length;) {
const r = e.indexOf("<", n);
if (r === -1) break;
n = r + 1;
if (t(r)) continue;
const i = parseReasoningTagAt(e, r, false);
if (i.kind === "pending") return {
text: e.slice(0, r),
pendingTagFragment: e.slice(r)
};
if (i.kind === "tag") n = r + i.tag.text.length;
}
const n = e.lastIndexOf("<");
if (n === -1 || t(n)) return { text: e };
const r = e.slice(n);
if (!isPotentialTrailingFinalTagFragment(r)) return { text: e };
return {
text: e.slice(0, n),
pendingTagFragment: r
};
}
function splitTrailingFenceFragment(e, t) {
const n = e.lastIndexOf("\n") + 1;
const r = e.slice(n);
if (!t && n === 0 || !/^(?: {0,3})(?:`+|~+)$/.test(r)) return { text: e };
return {
text: e.slice(0, n),
pendingFenceFragment: r
};
}
function createStreamRendering({ params: e, state: t, log: n, blockChunker: r, emitBlockReply: i, flushAssistantStream: a, pendingBlockReplyTasks: o, pushAssistantText: s, shouldSkipAssistantText: c }) {
const l = t.messagingToolSentTextsNormalized;
const u = createStreamingDirectiveAccumulator();
let d = createAssistantThinkingStream();
const f = /* @__PURE__ */ new Map();
const stripBlockTags = (t, n, r) => {
const i = `${n.pendingFenceFragment ?? ""}${n.pendingTagFragment ?? ""}${t}`;
n.pendingFenceFragment = void 0;
n.pendingTagFragment = void 0;
if (!i) return t;
const { text: a, pendingFenceFragment: o } = r?.final ? {
text: i,
pendingFenceFragment: void 0
} : splitTrailingFenceFragment(i, n.fence?.atLineStart ?? true);
n.pendingFenceFragment = o;
if (!a) return "";
const s = n.inlineCode ?? createInlineCodeState();
const c = n.fence;
const l = buildCodeSpanIndex(a, s, c);
const { text: u, pendingTagFragment: d } = r?.final ? {
text: a,
pendingTagFragment: void 0
} : splitTrailingBlockTagFragment(a, l.isInside);
n.pendingTagFragment = d;
if (!u) return "";
const f = u === a ? l : buildCodeSpanIndex(u, s, c);
let p = "";
let m = 0;
let h = 0;
let g = n.reasoningDepth;
let _ = n.reasoningInlineCode ? { ...n.reasoningInlineCode } : createInlineCodeState();
let v = n.reasoningFence?.open ? {
atLineStart: n.reasoningFence.atLineStart,
open: { ...n.reasoningFence.open }
} : n.reasoningFence ? { atLineStart: n.reasoningFence.atLineStart } : void 0;
let y = n.reasoningPendingFenceFragment;
n.reasoningPendingFenceFragment = void 0;
const advanceHiddenCodeState = (e) => {
const t = `${y ?? ""}${e}`;
y = void 0;
if (!t) return;
const { text: n, pendingFenceFragment: i } = r?.final ? {
text: t,
pendingFenceFragment: void 0
} : splitTrailingFenceFragment(t, v?.atLineStart ?? true);
y = i;
if (!n) return;
const a = buildCodeSpanIndex(n, _, v);
_ = a.inlineState;
v = a.fenceState;
};
for (let e = 0; e < u.length;) {
const t = u.indexOf("<", e);
if (t === -1) break;
e = t + 1;
if (g > 0) advanceHiddenCodeState(u.slice(h, t));
const n = g > 0 && (_.open || Boolean(v?.open));
h = t;
if (g === 0 && f.isInside(t) || n) continue;
const r = parseReasoningTagAt(u, t, true);
if (r.kind !== "tag") continue;
const i = r.tag;
const a = i.isClose;
e = t + i.text.length;
h = e;
if (i.isSelfClosing) {
if (g === 0) p += u.slice(m, t);
m = e;
continue;
}
if (g === 0) {
if (a) {
const n = e;
const r = u.slice(m, t);
const i = u.slice(n);
if (hasOrphanReasoningCloseBoundary({
before: r,
after: i
})) p = "";
else p += r;
m = n;
continue;
}
p += u.slice(m, t);
}
g += a ? -1 : 1;
if (g === 1 && !a) {
_ = createInlineCodeState();
v = void 0;
y = void 0;
}
m = e;
}
if (g > 0) advanceHiddenCodeState(u.slice(h));
if (g === 0) p += u.slice(m);
n.reasoningDepth = g;
n.reasoningInlineCode = g > 0 ? _ : void 0;
n.reasoningFence = g > 0 ? v : void 0;
n.reasoningPendingFenceFragment = g > 0 ? y : void 0;
const b = p === u ? f : buildCodeSpanIndex(p, s, c);
if (!e.enforceFinalTag) {
n.inlineCode = b.inlineState;
n.fence = b.fenceState;
return stripFinalTagsOutsideCodeSpans(p, b.isInside);
}
let x = "";
let S = 0;
let C = n.final;
let w = n.final;
for (const e of findFinalTagMatches(p)) {
const t = e.index;
if (b.isInside(t)) continue;
const n = e.isClose;
const r = e.isSelfClosing;
if (C && (r || n)) {
x += p.slice(S, t);
C = false;
} else if (!C && (r || !n)) {
C = true;
w = true;
} else continue;
S = t + e.text.length;
}
if (C) x += p.slice(S);
n.final = C;
if (!w) {
n.inlineCode = createInlineCodeState();
n.fence = b.fenceState;
n.finalInlineCode = void 0;
n.finalFence = void 0;
return "";
}
const T = n.finalInlineCode ?? createInlineCodeState();
const E = n.finalFence;
const D = buildCodeSpanIndex(x, T, E);
n.inlineCode = b.inlineState;
n.fence = b.fenceState;
n.finalInlineCode = C ? D.inlineState : void 0;
n.finalFence = C ? D.fenceState : void 0;
return stripFinalTagsOutsideCodeSpans(x, D.isInside);
};
const stripFinalTagsOutsideCodeSpans = (e, t) => {
let n = "";
let r = 0;
for (const i of findFinalTagMatches(e)) {
const a = i.index;
if (t(a)) continue;
n += e.slice(r, a);
r = a + i.text.length;
}
n += e.slice(r);
return n;
};
const emitBlockChunk = (n, r) => {
if (t.suppressBlockChunks || e.silentExpected || shouldSuppressDeterministicApprovalOutput(t)) return;
const a = r?.final === true ? n.trimEnd() : n;
const o = t.pendingAssistantReplyDirectives?.audioAsVoice === true;
if (!a.trim() && !r?.finalReply && !o) return;
const markBlockReplyTextHandled = () => {
if (a) {
t.lastBlockReplyText = a;
t.lastDeliveredBlockReplyText = a;
}
t.toolExecutionSinceLastBlockReply = false;
};
if (shouldSuppressSourceReplyOutput({
params: e,
state: t
})) {
markBlockReplyTextHandled();
return;
}
let u = a;
let d = false;
const p = t.lastDeliveredBlockReplyText;
const m = p ? a.slice(p.length) : "";
const h = Boolean(!t.deferBlockReplyDelivery && t.blockReplyBreak === "text_end" && t.toolExecutionSinceLastBlockReply && p && p.trimEnd().endsWith(":") && a.length > p.length && a.startsWith(p));
if (h && !/^\s/.test(m)) {
u = m;
d = true;
}
if (!u && !r?.finalReply && !o) return;
const g = normalizeTextForComparison(u);
const _ = h ? normalizeTextForComparison(m.trimStart()) : "";
if (isMessagingToolDuplicateNormalized(g, l) || h && isMessagingToolDuplicateNormalized(_, l)) {
if (h) markBlockReplyTextHandled();
return;
}
const v = r?.assistantMessageIndex ?? t.assistantMessageIndex;
const y = r?.sourceText;
const b = r?.sourceStart;
const x = r?.sourceEnd;
const S = y !== void 0 && b !== void 0 && x !== void 0 ? [b, x] : void 0;
let C = false;
if (S) {
const e = f.get(v) ?? [];
const [t, n] = S;
let r = t;
let i = "";
for (const t of e.toSorted((e, t) => e.range[0] - t.range[0])) {
const [e, a] = t.range;
if (a <= r) continue;
if (e > r) break;
const o = r - e;
const s = Math.min(n, a) - r;
i += t.text.slice(o, o + s);
r += s;
if (r >= n) break;
}
C = r >= n && i === y;
}
if (u && (C || (!S || !f.has(v) || r?.reconciledSourceBreak) && c(u, g))) {
if (d) markBlockReplyTextHandled();
if (!r?.finalReply) return;
u = "";
}
if (!e.onBlockReply) {
s(u, g);
markBlockReplyTextHandled();
return;
}
let w = {
text: u,
replyToTag: false
};
if (r?.finalReply) {
let e = w.text;
if (trimTextPreservingCode(e) === r.finalReply.text) {
e = r.finalReply.text;
u = e;
}
w = {
...w,
...r.finalReply,
text: e
};
}
const { text: T, mediaUrls: E, mediaFailures: D, audioAsVoice: O, replyToId: k, replyToTag: A, replyToCurrent: j } = w;
const M = Boolean(r?.finalReply?.text && t.pendingToolMediaUrls.length);
if (!T && !D?.length && (!E || E.length === 0) && !O && !o && !M) {
if (d) markBlockReplyTextHandled();
return;
}
s(u, g);
const N = {
text: T || appendReplyMediaFailures(T, D ?? []),
mediaUrls: E?.length ? E : void 0,
audioAsVoice: O,
replyToId: k,
replyToTag: A,
replyToCurrent: j
};
addReplyPayloadMediaFailures(N, D);
const P = u === a && T === u && !C && !r?.reconciledSourceBreak ? S : void 0;
i(N, {
assistantMessageIndex: v,
blockSourceText: u === a && T === u && (r?.sourceStart === void 0 || P !== void 0) ? y : void 0,
blockSourceRange: P,
consumePendingToolMedia: r?.finalReply !== void 0 || o || Boolean(E?.length || O)
});
if (P) {
const e = f.get(v) ?? [];
e.push({
range: P,
text: y ?? ""
});
f.set(v, e);
}
markBlockReplyTextHandled();
};
const consumePartialReplyDirectives = (e, t) => u.consume(e, t);
const resetPartialReplyDirectives = () => {
u.reset();
t.lastAssistantAudioDirectiveCount = 0;
t.pendingAssistantReplyDirectives = void 0;
};
const flushBlockReplyBuffer = (n) => {
a();
if (!e.onBlockReply) return;
let i;
if (r.hasBuffered()) r.drain({
force: true,
emit: (e, t) => {
if (i !== void 0) emitBlockChunk(i.text, {
sourceText: i.sourceText,
reconciledSourceBreak: i.reconciledSourceBreak,
sourceStart: i.sourceStart,
sourceEnd: i.sourceEnd,
assistantMessageIndex: n?.assistantMessageIndex
});
i = {
text: e,
...t
};
}
});
if (i !== void 0 || n?.final || t.pendingAssistantReplyDirectives?.audioAsVoice === true) emitBlockChunk(i?.text ?? "", {
...n,
final: n?.final === true,
sourceText: i?.sourceText,
reconciledSourceBreak: i?.reconciledSourceBreak,
sourceStart: i?.sourceStart,
sourceEnd: i?.sourceEnd
});
if (o.size === 0) return;
return (async () => {
while (o.size > 0) await Promise.allSettled(o);
})();
};
const emitReasoningStream = (r, i) => {
if (e.silentExpected) return;
const o = d.text;
const s = d.update(r, i);
const c = s.text;
if (!c || c === t.lastStreamedReasoning) return;
const l = readAgentAssistantSource(t.lastAssistant);
const u = l ? l.itemId ??= randomUUID() : void 0;
a();
const f = t.lastStreamedReasoning ?? "";
const p = o === f && s.delta !== null ? s.delta : c.startsWith(f) ? c.slice(f.length) : c;
t.lastStreamedReasoning = c;
emitAgentEventWithAssistantSourceIfCurrent({
runId: e.runId,
stream: "thinking",
data: {
text: c,
delta: p,
...u ? { itemId: u } : {}
}
}, l);
if (t.streamReasoning && !shouldSuppressSourceReplyOutput({
params: e,
state: t
}) && e.onReasoningStream) runBestEffortCallback({
label: "reasoning stream",
log: n,
callback: () => e.onReasoningStream?.({
text: c,
...t.reasoningMode === "stream" ? {} : { requiresReasoningProgressOptIn: true }
})
});
};
const resetAssistantMessageState = (e) => {
a();
t.deltaBuffer = "";
t.streamBlockText = "";
t.streamBlockFinal = false;
t.blockReplyScopeStart = void 0;
t.blockReplyTextUnsettled = false;
t.thinkingTagStream = createThinkingTagStreamState();
t.deltaBufferIsCommentary = false;
t.hasFlushedPartialText = false;
r.reset();
resetPartialReplyDirectives();
t.partialBlockState = createAssistantStreamBlockState();
t.assistantStream = void 0;
t.nextCommentaryAt = void 0;
t.currentSourceMessagingToolHeldPartial = void 0;
t.lastBlockReplyText = void 0;
t.lastStreamedReasoning = void 0;
d = createAssistantThinkingStream();
t.reasoningStreamOpen = false;
t.suppressBlockChunks = false;
t.assistantMessageIndex += 1;
t.lastAssistantStreamContentIndex = void 0;
t.lastAssistantStreamItemId = void 0;
t.assistantTextBaseline = e;
};
return {
consumePartialReplyDirectives,
getPartialReplySourceText: () => u.sourceText,
resetPartialReplyDirectives,
emitBlockChunk,
emitReasoningStream,
flushBlockReplyBuffer,
resetAssistantMessageState,
stripBlockTags
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.tool-lifecycle.ts
function createEmbeddedToolLifecycleRunner(e) {
return async (t) => {
e.flushAssistantStream();
const n = {
type: "tool_execution_start",
toolName: t.toolName,
toolCallId: t.toolCallId,
parentToolCallId: t.parentToolCallId,
args: t.args,
replaySafe: t.replaySafe,
hideFromChannelProgress: t.hideFromChannelProgress,
lifecycleProvenance: "nested"
};
recordEmbeddedToolTrajectoryEvent(e, n, void 0);
await handleToolExecutionStart(e, n);
let r = false;
const finishToolLifecycle = async (n, i) => {
const a = r;
e.flushAssistantStream();
const o = {
type: "tool_execution_end",
toolName: t.toolName,
toolCallId: t.toolCallId,
isError: n,
executionStarted: a,
result: i,
hideFromChannelProgress: t.hideFromChannelProgress
};
const s = prepareToolResult(i);
recordEmbeddedToolTrajectoryEvent(e, o, s);
const c = await prepareToolExecutionEnd(e, o, s);
if (await t.onTerminal?.({
result: i,
readSanitizedResult: s,
isError: c.isError,
executedArguments: c.executedArguments ?? t.args,
effectReceipt: c.effectReceipt
}) !== false) await c.publishPresentation();
};
let i;
try {
i = await t.execute(() => {
r = true;
});
} catch (e) {
const t = consumeToolExecutionNotStarted(e);
const n = buildToolLifecycleErrorResult(e);
if (t) markToolExecutionNotStarted(n);
await finishToolLifecycle(true, n);
throw e;
}
await finishToolLifecycle(false, i);
return i;
};
}
//#endregion
//#region src/agents/embedded-agent-subscribe.ts
const embeddedLog = createSubsystemLogger("agent/embedded");
function resolveEmbeddedAgentSessionLogger(e) {
const t = normalizeMessageChannel(e);
if (t && isDeliverableMessageChannel(t)) return createSubsystemLogger(`gateway/channels/${t}`);
return embeddedLog;
}
function subscribeEmbeddedAgentSession(e) {
let t = e;
const n = t.onAgentEvent;
if (n) {
let e = false;
const r = t.session.sessionManager;
t = {
...t,
onAgentEvent: (t) => {
if (e || t.stream === "lifecycle" && typeof t.data.phase !== "string") return n(t);
const i = r[sessionManagerReadTranscriptStart]();
e = true;
return n({
...t,
transcriptStart: i
});
}
};
}
const r = resolveEmbeddedAgentSessionLogger(t.messageChannel);
const i = (t.toolResultFormat ?? "markdown") === "markdown";
const a = new EmbeddedAgentSubscribeState(t);
const { captureModelEvent: o, recordAuxiliaryUsage: s, getUsageTotals: c, getLastAssistantUsage: l, getCurrentAttemptAssistant: u, hasSuccessfulModelResponse: d } = createEmbeddedModelState(t, r);
let f = 0;
let p;
const m = a.assistantTexts;
const h = a.toolMetas;
const g = a.toolMetaById;
const _ = a.toolSummaryById;
const v = a.messagingToolSentTexts;
const y = a.messagingToolSentTextsNormalized;
const b = a.messagingToolSentTargets;
const x = a.messagingToolSentMediaUrls;
const S = a.messagingToolSourceReplyPayloads;
const didSendViaMessagingTool = () => hasCommittedMessagingToolDeliveryEvidence({
messagingToolSentTexts: v,
messagingToolSentMediaUrls: x,
messagingToolSentTargets: b
});
const C = createReplyDelivery({
params: t,
state: a,
log: r
});
const { clearAssistantStream: w, clearDeferredBlockReplies: T, emitAssistantStreamData: E, emitBlockReply: D, finalizeAssistantTexts: O, flushAssistantStream: k, noteLastAssistant: A, releaseDeferredReplies: j } = C;
const trimMessagingToolSent = () => {
if (v.length > 200) {
const e = v.length - 200;
v.splice(0, e);
y.splice(0, e);
}
for (const e of [
a.currentSourceMessagingToolSentTextsNormalized,
b,
x,
S
]) if (e.length > 200) e.splice(0, e.length - 200);
};
const ensureCompactionPromise = () => {
if (!p) {
p = createDeferredCore();
p.promise.catch((e) => {
r.debug(`compaction promise rejected (no waiter): ${String(e)}`);
});
}
};
const noteCompactionRetry = () => {
a.pendingCompactionRetry += 1;
ensureCompactionPromise();
};
const maybeResolveCompactionWait = () => {
if (a.pendingCompactionRetry !== 0 || a.compactionInFlight) return;
p?.resolve();
p = void 0;
};
const resolveCompactionRetry = () => {
if (a.pendingCompactionRetry <= 0) return;
a.pendingCompactionRetry -= 1;
maybeResolveCompactionWait();
};
const incrementCompactionCount = () => {
f += 1;
};
const noteCompactionTokensAfter = (e) => {
if (typeof e !== "number" || !Number.isFinite(e) || e < 0) return;
a.lastCompactionTokensAfter = Math.floor(e);
};
const M = t.blockReplyChunking;
const N = new EmbeddedBlockChunker(M);
const shouldEmitToolResult = () => typeof t.shouldEmitToolResult === "function" ? t.shouldEmitToolResult() : t.verboseLevel === "on" || t.verboseLevel === "full";
const shouldEmitToolOutput = () => typeof t.shouldEmitToolOutput === "function" ? t.shouldEmitToolOutput() : t.verboseLevel === "full";
const emitToolResultMessage = (e, n, i) => {
if (!t.onToolResult) return;
const a = parseInlineDirectives(n, {
stripAudioTag: true,
stripReplyTags: true
});
const o = i ? extractToolResultMediaArtifact(i) : void 0;
const s = filterToolResultMediaUrls(e, o?.mediaUrls ?? [], i, t.trustedLocalMediaToolNames);
if (t.sourceReplyDeliveryMode === "message_tool_only" && a.text && s.length === 0 && didSendViaMessagingTool()) return;
if (!a.text && s.length === 0) return;
runBestEffortCallback({
label: "tool result",
log: r,
callback: () => t.onToolResult?.({
text: a.text,
mediaUrls: s.length ? s : void 0,
...o?.audioAsVoice ? { audioAsVoice: true } : {}
})
});
};
const emitToolSummary = (e, n, r) => {
const a = t.verboseLevel === "full" || !r ? n : void 0;
const o = formatToolAggregate(e, a ? [a] : void 0, { markdown: i });
emitToolResultMessage(e, o);
};
const emitToolOutput = (e, t, n, r) => {
if (!n) return;
const a = formatToolAggregate(e, t ? [t] : void 0, { markdown: i });
const o = n.trim();
const s = `${a}\n${o ? i ? `\`\`\`txt\n${o}\n\`\`\`` : o : "(no output)"}`;
emitToolResultMessage(e, s, r);
};
const P = createStreamRendering({
params: t,
state: a,
log: r,
blockChunker: N,
emitBlockReply: C.emitBlockReply,
flushAssistantStream: k,
pendingBlockReplyTasks: C.pendingBlockReplyTasks,
pushAssistantText: C.pushAssistantText,
shouldSkipAssistantText: C.shouldSkipAssistantText
});
const resetForCompactionRetry = () => {
a.hadDeterministicSideEffect = a.hadDeterministicSideEffect === true || didSendViaMessagingTool() || a.successfulCronAdds > 0 || a.acceptedSessionSpawns.length > 0 || a.visibleBlockReplyCount > 0;
m.length = 0;
a.answerSegments.length = 0;
a.inputAnswer = void 0;
a.keptAnswer = void 0;
a.lastAssistant = void 0;
a.lastAssistantTextMessageIndex = -1;
a.lastAssistantTextContentIndex = void 0;
a.lastAssistantTextItemId = void 0;
a.lastAssistantTextNormalized = void 0;
a.lastAssistantTextTrimmed = void 0;
h.length = 0;
g.clear();
_.clear();
a.liveEditDiffStateById.clear();
a.itemActiveIds.clear();
a.itemStartedCount = 0;
a.itemCompletedCount = 0;
if (a.lastToolError?.mutatingAction !== true) a.lastToolError = void 0;
v.length = 0;
y.length = 0;
a.currentSourceMessagingToolSentTextsNormalized.length = 0;
b.length = 0;
x.length = 0;
a.pendingToolMediaUrls = [];
a.pendingToolMediaAttachments = [];
a.pendingToolMediaTrustByUrl.clear();
a.toolAutoDeliveryMediaUrls.clear();
a.pendingToolAudioAsVoice = false;
a.pendingToolMediaDeliveryFailed = false;
a.visibleBlockReplyCount = 0;
a.deferBlockReplyDelivery = typeof t.onBeforeTerminalDelivery === "function" && t.deferTerminalDelivery !== false;
w();
T();
a.deterministicApprovalPromptPending = false;
a.deterministicApprovalPromptSent = false;
a.lastDeliveredBlockReplyText = void 0;
a.lastReasoningSent = void 0;
a.toolExecutionSinceLastBlockReply = false;
a.replayState = mergeEmbeddedRunReplayState(a.replayState, t.initialReplayState);
a.livenessState = "working";
P.resetAssistantMessageState(0);
};
const flushPartialAssistantText = () => {
const e = a.deltaBuffer;
if (!e) return;
if (a.deltaBufferIsCommentary) {
a.hasFlushedPartialText = false;
return;
}
const t = stripDowngradedToolCallText(P.stripBlockTags(e, createAssistantStreamBlockState(), { final: true })).trimEnd();
if (m.length > a.assistantTextBaseline || a.hasFlushedPartialText) C.replaceCurrentAssistantText(t);
else if (t) C.pushAssistantText(t);
a.hasFlushedPartialText = Boolean(t);
};
const F = {
...P,
params: t,
state: a,
log: r,
blockChunking: M,
blockChunker: N,
hookRunner: t.hookRunner,
builtinToolNames: t.builtinToolNames,
trustedLocalMediaToolNames: t.trustedLocalMediaToolNames,
noteLastAssistant: A,
shouldEmitToolResult,
shouldEmitToolOutput,
emitToolSummary,
emitToolOutput,
emitAssistantStreamData: E,
emitBlockReply: D,
flushAssistantStream: k,
releaseDeferredReplies: j,
clearAssistantStream: w,
clearDeferredBlockReplies: T,
resetForCompactionRetry,
finalizeAssistantTexts: O,
trimMessagingToolSent,
consumeToolSendReceipt: (e) => consumeEmbeddedToolReceipt(t.session.sessionManager, e),
ensureCompactionPromise,
noteCompactionRetry,
resolveCompactionRetry,
maybeResolveCompactionWait,
captureModelEvent: o,
incrementCompactionCount,
noteCompactionTokensAfter,
getCompactionCount: () => f
};
const I = installToolAuthoredSourceReplyTerminalHook({
agent: t.session.agent,
sourceReplyCapableToolNames: t.sourceReplyCapableToolNames,
idempotencyScope: t.runId,
onSourceReplies: (e) => {
a.messagingToolSourceReplyPayloads.push(...e);
}
});
const L = t.session.subscribe(createEmbeddedAgentSessionEventHandler(F));
setSessionModelUsageSink(t.session.sessionManager, s);
const unsubscribe = () => {
if (a.unsubscribed) return;
a.unsubscribed = true;
I();
w();
cleanupRunToolStartData(t.runId);
a.liveEditDiffStateById.clear();
if (p) {
const { reject: e } = p;
p = void 0;
e(createAbortError("Unsubscribed during compaction"));
}
if (t.session.isCompacting) try {
t.session.abortCompaction();
} catch (e) {
r.warn(`unsubscribe: compaction abort failed runId=${t.runId} err=${String(e)}`);
}
setSessionModelUsageSink(t.session.sessionManager, null);
L();
};
return {
assistantTexts: m,
answerSegments: a.answerSegments,
getCurrentAttemptAssistant: u,
getKeptAnswer: () => a.keptAnswer,
hasSuccessfulModelResponse: d,
getLastAssistantTextMessageIndex: () => a.lastAssistantTextMessageIndex >= 0 ? a.lastAssistantTextMessageIndex : void 0,
toolMetas: h,
getAcceptedSessionSpawns: () => a.acceptedSessionSpawns.slice(),
getLatestMcpAppChannelView: () => a.latestMcpAppChannelView ? { ...a.latestMcpAppChannelView } : void 0,
getLatestMcpConnectAction: () => a.latestMcpConnectAction ? { ...a.latestMcpConnectAction } : void 0,
runToolLifecycle: createEmbeddedToolLifecycleRunner(F),
unsubscribe,
setTerminalLifecycleMeta: a.setTerminalLifecycleMeta.bind(a),
isCompacting: () => a.compactionInFlight || a.pendingCompactionRetry > 0,
isCompactionInFlight: () => a.compactionInFlight,
getMessagingToolSentTexts: () => v.slice(),
getMessagingToolSentMediaUrls: () => x.slice(),
getMessagingToolSentTargets: () => b.slice(),
getMessagingToolSourceReplyPayloads: () => S.slice(),
getSourceReplyDelivered: () => a.sourceReplyDelivered,
getSourceReplyDeliveryState: () => a.sourceReplyDeliveryState,
endsWithSourceProgress: () => a.lastToolTurnOnlySourceProgress === true,
getPendingToolMediaReply: () => readPendingToolMediaReply(a),
getToolAutoDeliveryMediaUrls: () => [...a.toolAutoDeliveryMediaUrls],
hasToolMediaBlockReply: () => a.hasToolMediaBlockReply,
getVisibleBlockReplyCount: () => a.visibleBlockReplyCount,
getSuccessfulCronAdds: () => a.successfulCronAdds,
getReplayState: () => ({ ...a.replayState }),
didSendViaMessagingTool,
didSendDeterministicApprovalPrompt: () => a.deterministicApprovalPromptSent,
getLastToolError: () => a.lastToolError ? { ...a.lastToolError } : void 0,
getUsageTotals: c,
getLastAssistantUsage: l,
getCompactionCount: () => f,
getLastCompactionTokensAfter: () => a.lastCompactionTokensAfter,
getAssistantTurnCount: () => a.assistantTurnCount,
waitForPendingEvents: C.waitForPendingEvents,
flushPartialAssistantText,
getItemLifecycle: () => ({
startedCount: a.itemStartedCount,
completedCount: a.itemCompletedCount,
activeCount: a.itemActiveIds.size
}),
waitForCompactionRetry: () => {
if (a.unsubscribed) return Promise.reject(createAbortError("Unsubscribed during compaction wait"));
if (a.compactionInFlight || a.pendingCompactionRetry > 0) {
ensureCompactionPromise();
return p?.promise ?? Promise.resolve();
}
return new Promise((e, t) => {
queueMicrotask(() => {
if (a.unsubscribed) {
t(createAbortError("Unsubscribed during compaction wait"));
return;
}
if (a.compactionInFlight || a.pendingCompactionRetry > 0) {
ensureCompactionPromise();
(p?.promise ?? Promise.resolve()).then(e, t);
} else e();
});
});
}
};
}
//#endregion
export { installMessageToolTerminalHook as n, subscribeEmbeddedAgentSession as t };