openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3,733 lines • 136 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { I as resolveOptionalIntegerOption, a as addTimerTimeoutGraceMs, h as clampPositiveTimerTimeoutMs, s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { a as asOptionalRecord, l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import "./utils-C8YECn2Q.mjs";
import { i as createAbortError, o as racePromiseWithAbortSignal, s as raceWithTimeout } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { r as getInProcessGatewayRequestContext } from "./gateway-request-scope-BvvDhs5D.mjs";
import { o as resolveExecutablePath } from "./executable-path-D8oWZRS5.mjs";
import { x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as compareValidSemver } from "./semver-DUtldgR6.mjs";
import { L as hasInternalDiagnosticEventListeners, T as markToolExecutionLivenessDiagnosticEvent, c as emitTrustedDiagnosticEventWithPrivateData, s as emitTrustedDiagnosticEvent, t as areDiagnosticsEnabledForProcess } from "./diagnostic-events-BjAH1Kbx.mjs";
import { _ as createDiagnosticTraceContextFromActiveScope, y as freezeDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import "./crypto-digest-B2m8wIBj.mjs";
import { n as truncateUtf8Suffix } from "./utf8-truncate-BH7Ecfuh.mjs";
import { i as withChildProcessOperation } from "./spawn-diagnostics-DBVI9KzR.mjs";
import { o as registerOpenClawAgentDatabaseAsyncResource } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { l as getAgentRunContext, v as registerAgentRunDelegatedAuthorityClosedHandler } from "./agent-run-registry-D7vkrqFT.mjs";
import { a as emitAgentEvent, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs";
import { d as runWithSessionSourceScope, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { t as applyPluginTextReplacements } from "./plugin-text-transforms-CMotGmZ0.mjs";
import { i as createCapturedOutputBuffers, n as appendCapturedOutput } from "./exec-output-BYE24ROR.mjs";
import { g as labelRuntimeContextText } from "./types-iq-cNLsd.mjs";
import { i as isSilentReplyText, n as SILENT_REPLY_TOKEN } from "./tokens-CcE6ESvH.mjs";
import { t as stripMixedSilentReplyTokens } from "./mixed-silent-reply-tokens-5vt94DeG.mjs";
import { i as isCurrentPlacementTurnClaim } from "./placement-record-Hs-bCbCm.mjs";
import { g as resolveAdmittedRunActiveAssertion, l as getAdmittedRunDelegatedAuthority } from "./admitted-run-context-D3Jvk_f_.mjs";
import { r as NODE_CLAUDE_NATIVE_AUTH_CAPABILITY, t as NODE_AGENT_CLI_CLAUDE_RUN_COMMAND } from "./node-commands-BfMJIlXP.mjs";
import { d as isSignalTimeoutReason, i as FailoverError, r as CLI_PARTIAL_OUTPUT_REJECTED_ERROR_CODE, u as isFailoverError } from "./error-BCRqSFIY.mjs";
import { h as resolveCliToolTerminalReason } from "./run-termination-0Ig0-bk6.mjs";
import { t as enqueueSessionEventForHost } from "./session-event-handoff-CC7Ui3SA.mjs";
import { p as isHostGeneratedInputProvenance } from "./input-provenance-DupvvURj.mjs";
import { d as withGatewayToolApprovalOwner, f as withGatewayToolCallerIdentity, o as getGatewayToolCallerIdentity, r as createAdmittedGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { r as captureSessionEventTargetForHost } from "./session-event-target-BPiQeS30.mjs";
import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { _ as retainPreparedSessionEntryPredicate } from "./session-accessor.sqlite-entry-cache-publication-state-B4mkg2yK.mjs";
import { u as projectRuntimeContextFragments } from "./internal-runtime-context-BEUlDNuI.mjs";
import { a as prepareAgentRunTerminalReply } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { T as withAgentQuestionAnswerAuthority } from "./host-private-capabilities-DDumj0c_.mjs";
import { d as withMessageInjectionAdmission, t as MessageInjectionAcceptedUnconfirmedError } from "./message-injection-authority-B9SdalrV.mjs";
import { i as shouldLogVerbose, r as logVerbose } from "./globals-CgepmiqE.mjs";
import { _ as recordSkillUsed, f as runBeforeToolCallHook, v as resolvedSkillUsageMatch } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { f as recordAdjustedParamsForToolCall } from "./agent-tools.before-tool-call.state-C5F7vnXY.mjs";
import { t as runAgentHarnessAfterToolCallHook } from "./hook-helpers-DKwpcDXZ.mjs";
import { t as captureSessionEntryMetadataRead } from "./session-entry-source-authority-Bxiv7qVT.mjs";
import { t as assertionSucceeds } from "./assertion-BVvbcE3a.mjs";
import { l as resolveFastModeForElapsed } from "./fast-mode-Dk3A3IUk.mjs";
import "./fast-mode-BcwTQ_IZ.mjs";
import { t as resolveExecApprovalsFromFileInternal } from "./exec-approvals-resolver-C6IwmycS.mjs";
import { l as readExecApprovalsSnapshotAsync } from "./exec-approvals-store-BUZ9uOWF.mjs";
import { n as evaluateShellAllowlistWithAuthorization } from "./exec-approvals-allowlist-f3-u9Y6p.mjs";
import { i as recordAllowlistMatchesUse } from "./exec-approvals-rOfoWejC.mjs";
import { i as resolveExecDefaultsAsync } from "./exec-defaults-BaVI-sJD.mjs";
import { n as applySkillEnvOverridesFromSnapshot } from "./env-overrides-CAhWtW9f.mjs";
import { t as classifyFailoverReason } from "./classify-o7Whl-By.mjs";
import { p as resolveFailoverStatus } from "./failover-error-CbIiC30n.mjs";
import { n as enqueueCommandInLane } from "./command-queue-BenRlAaO.mjs";
import { h as BLOCKED_TOOL_CALL_ABORT_FLOOR_MS, p as beginDiagnosticBackendActivity } from "./diagnostic-run-activity-BzWz2WN_.mjs";
import { n as resolveDiagnosticModelContentCapturePolicy } from "./diagnostic-llm-content-CvUZCA61.mjs";
import { a as sanitizeExecApprovalWarningTextWithStatus, t as exceedsApprovalTextLimit } from "./exec-approval-text-sanitize-Xx3Q87a8.mjs";
import { n as projectAgentActivityItem } from "./agent-activity-presentation-BIQtAp6v.mjs";
import { n as isAgentPlanProgressToolName } from "./progress-card-input-WVh4etRi.mjs";
import { r as mergePathPrepend } from "./path-prepend-HpofbiEN.mjs";
import { n as getInstallationTarget, r as installationTargetEnv, t as LOCAL_INSTALLATION_TARGET_UNSUPPORTED } from "./installation-target-context-C_xR1SHA.mjs";
import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs";
import { n as diagnosticErrorFailureKind, r as diagnosticErrorMessage, t as diagnosticErrorCategory } from "./diagnostic-error-metadata-Cc4dyoSL.mjs";
import { a as readToolResultDetails } from "./tool-result-error-B2GHe83l.mjs";
import { l as truncatePluginApprovalDetail, t as DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS } from "./plugin-approvals-DAqwCYQr.mjs";
import { t as callGatewayTool } from "./gateway-DL_Nxi-v.mjs";
import { a as isMessagingToolTargetEvidenceAction, i as isMessagingToolSendAction, n as isMessagingTool, r as isMessagingToolDeliveryAction } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { s as runWithAgentToolSourceExecutionScope } from "./agent-tool-source-execution-guard-CD-ezY7E.mjs";
import "./agent-tools.before-tool-call-CCkSq-k3.mjs";
import { t as createPluginToolsMcpHandlers } from "./plugin-tools-handlers-Xw__K0lj.mjs";
import { i as resolveWindowsExecutablePath, o as resolveWindowsSpawnProgramCandidate } from "./windows-spawn-BcHMKZuG.mjs";
import { n as getAgentScopedMediaLocalRoots } from "./local-roots-BTz6ULME.mjs";
import { t as AGENT_LANE_SUBAGENT } from "./lanes-FWlQGbs4.mjs";
import { a as resolveQuestionTimeoutMs } from "./ask-user-tool-normalization-BkE0uL3h.mjs";
import { l as readSessionWorkerPlacementAsync } from "./session-placement-lifecycle-3XCQYoeM.mjs";
import { n as cliBackendLog, r as formatCliBackendOutputDigest, t as CLI_BACKEND_LOG_OUTPUT_ENV } from "./log-C54MYINf.mjs";
import { C as isClaudeForegroundAgentToolName, E as runCliCleanup, T as isClaudeToolUseBlockType, b as createCliJsonlStreamingParser, d as createCliExitFailoverError, f as createCliFailoverError, g as resolveCliResumeAtError, h as recordCliStreamRefusalToolEffects, i as createCliLiveSessionCapability, m as readCliStreamRefusalOutput, n as buildCliLiveOwnerKey, o as ensureCliLiveSessionMemory, p as createCliStreamRefusalError, r as closeCliLiveSession, s as getCliLiveSessionApprovalGrants, t as acceptsCliLiveSession, u as restartCliLiveSession, v as formatCliOutputError, x as transformCliResultText, y as parseCliOutput } from "./cli-live-session-registry-DpyMtPCM.mjs";
import { n as createCliRunCurrentAssertion, t as attachCliReplyBackend } from "./execution-target-whyiKvuS.mjs";
import { a as normalizeAcceptedSessionSpawnResult } from "./accepted-session-spawn-DXCz6IHR.mjs";
import { t as getProcessSupervisor } from "./supervisor-BeB1eaLi.mjs";
import { r as projectAgentToolActivity } from "./agent-activity-events-BvMnPRzr.mjs";
import { n as resolveExecToolConfig } from "./lazy-exec-tool-C-cI3niu.mjs";
import { a as resolveCliRuntimeOwnerFingerprint, o as resolveCliExecutableIdentity, t as fingerprintCliRuntimeArtifact } from "./cli-auth-epoch-B5L_1N1V.mjs";
import { c as encodeNodeClaudeSkillMessage, i as NODE_CLAUDE_WORKSHOP_RESULT_BYTES, n as NODE_CLAUDE_SKILLS_MESSAGE_BYTES, o as NodeClaudeSkillUpstreamSchema, r as NODE_CLAUDE_WORKSHOP_CALL_BYTES, t as NODE_CLAUDE_SKILLS_CAPABILITY } from "./node-claude-skill-protocol-oFNHY2lK.mjs";
import { t as createNodeDuplexEndpoint } from "./node-duplex-framing-D2NjVVpH.mjs";
import { i as resolveNodeClaudeAuthEnv, r as NODE_CLAUDE_FORWARD_ENV_KEYS, t as resolveCliChildEnv } from "./execution-env-BmqW_atJ.mjs";
import { n as prepareSkillResourceDelivery } from "./resources-CNBzJPid.mjs";
import { c as prepareSystemRunMutableFileBinding, u as revalidateSystemRunMutableFileBinding } from "./system-run-approval-binding-B3btPgad.mjs";
import { t as buildAuthorizedShellCommandFromPlan } from "./exec-authorization-render-Bn4BVITQ.mjs";
import { n as resolveEventSessionRoutingPolicy, t as resolveEventSessionKeyForPolicy } from "./event-session-routing-QCFK39bz.mjs";
import { t as resolveToolLoopDetectionConfig } from "./tool-loop-detection-config-Dzb0KwUj.mjs";
import { t as createModelCallStreamProgressReporter } from "./diagnostic-model-stream-progress-D2GjiTSb.mjs";
import { t as EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS } from "./lane-runtime-Amkf2D3O.mjs";
import { l as resolveNodeCommandAllowlist, o as isNodeCommandAllowed } from "./node-command-policy-DkH-pkTr.mjs";
import { n as CLI_RESUME_WATCHDOG_DEFAULTS, r as CLI_WATCHDOG_MIN_TIMEOUT_MS, t as CLI_FRESH_WATCHDOG_DEFAULTS } from "./cli-watchdog-defaults-CzmnkdzO.mjs";
import { c as readEmbeddedMessageDeliveryFact } from "./embedded-agent-message-delivery-ClVuBxqZ.mjs";
import { i as resolveMessageToolSourceReplyFinal, n as isDeliveredMessagingToolResult, t as isDeliveredMessageToolOnlySourceReplyResult } from "./embedded-agent-message-tool-source-reply-BLgXJNuN.mjs";
import { r as compileStructuredInputQuestions } from "./structured-input-DSYgb17h.mjs";
import { t as runStructuredInput } from "./structured-input-execution-BMyxgore.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 { c as prepareToolResult, i as extractToolErrorMessage } 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 { t as shouldUseInternalSourceReplySink } from "./internal-source-reply-DPNOuFQV.mjs";
import { n as isResumingAlreadyPendingSessionsYieldResult } from "./sessions-yield-tool-DjKlbpxP.mjs";
import { i as resolveRegisteredExecApprovalDecision, r as registerExecApprovalRequestForHostOrThrow } from "./bash-tools.exec-approval-request-BDrMJ1hF.mjs";
import { n as hashCliImageTurnEntryId } from "./cli-image-turn-correlation-DVP0DD-I.mjs";
import { r as stripOpenClawMcpToolPrefix, t as normalizeCliToolName } from "./tool-policy-bZXUEBo2.mjs";
import { t as hasHydratableMediaImages } from "./images.media-refs-BoLVBqd7.mjs";
import { r as detectImageReferences } from "./images-BfGn0xAm.mjs";
import { c as resolvePromptInput, d as writeCliSystemPromptFile, l as resolveSessionIdToSend, n as buildCliArgs, o as prepareCliPromptImagePayload, r as isClaudeCliBackendId, s as resolveCliRunQueueKey, u as resolveSystemPromptUsage } from "./helpers-aqu9cn2k.mjs";
import { r as composeCliPromptContext, s as prepareCliBundleMcpCaptureAttempt } from "./prompt-context-DbTyffXb.mjs";
import { n as resolveCliSessionId } from "./auth-profile-preparation-error-BT33LvUK.mjs";
import { g as cliAssistantItemId, h as projectCliMessagingDeliveryEvidence, n as recordCliTrajectoryEvent, p as attachCliMessagingDeliveryEvidence, t as recordCliModelCompleted } from "./trajectory-D7Mvun0h.mjs";
import { t as buildMcpToolSchema } from "./mcp-http.schema-D3hjCI90.mjs";
import { g as waitForMcpLoopbackToolCallCaptureIdle, r as clearMcpLoopbackToolCallCapture, t as beginMcpLoopbackToolCallCapture } from "./mcp-http.loopback-runtime-CcKKo9xU.mjs";
import path from "node:path";
import crypto, { randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
import { isDeepStrictEqual } from "node:util";
import { parse as parse$1 } from "semver";
import { Value } from "typebox/value";
import { stripSystemPromptCacheBoundary } from "@openclaw/ai/internal/shared";
//#region src/agents/cli-runner/execute-events.ts
function resolveCliToolSource(e, t) {
return t === "mcp_tool_use" || e.startsWith("mcp__") ? "mcp" : "core";
}
function withBrowserTabDetails(e, t) {
if (isRecord(e) && Array.isArray(e.content)) return {
...e,
details: {
...asOptionalRecord(e.details),
browserTab: t
}
};
if (Array.isArray(e)) return {
content: e,
details: { browserTab: t }
};
if (typeof e === "string" || typeof e === "number" || typeof e === "boolean") return {
content: [{
type: "text",
text: String(e)
}],
details: { browserTab: t }
};
return e;
}
function createCliEventHandlers(e) {
const t = e.context;
const n = t.params;
const r = n.executionMode !== "side-question";
const emitLiveEvent = (e, t) => {
if (r) emitAgentEvent({
runId: n.runId,
stream: e,
data: t()
});
};
let i = false;
let a = false;
let o;
const s = /* @__PURE__ */ new Set();
const signalExecutionPhase = (e) => {
if (s.has(e)) return;
s.add(e);
n.onExecutionPhase?.({
phase: e,
provider: n.provider,
model: t.modelId,
backend: t.backendResolved.id
});
};
let c = 0;
let l = "";
const u = /* @__PURE__ */ new Map();
const d = /* @__PURE__ */ new Map();
const emitToolEvent = (e, t) => {
let r = projectAgentToolActivity({
...e,
name: stripOpenClawMcpToolPrefix(e.name),
args: t ? t.args : e.args
});
if (t?.args === void 0 && t?.requestedArgs !== void 0) r = projectAgentActivityItem(r, { args: t.requestedArgs });
const i = {
runId: n.runId,
stream: "item",
data: r
};
if (e.phase === "start") emitAgentEvent(i);
emitAgentEvent({
runId: n.runId,
stream: "tool",
data: {
...e,
name: stripOpenClawMcpToolPrefix(e.name)
}
});
if (e.phase !== "start") emitAgentEvent(i);
};
const f = /* @__PURE__ */ new Set();
const p = /* @__PURE__ */ new Map();
const recordToolSummary = (e, t) => {
let n = u.get(e.toolCallId);
if (n) n.failed ||= t;
else {
n = { failed: t };
u.set(e.toolCallId, n);
}
if (e.name) f.add(e.name);
return n;
};
const getToolSummary = () => ({
calls: u.size,
tools: [...f],
failures: Array.from(u.values()).filter((e) => e.failed).length
});
const emitToolUseStart = (t, n) => {
i = true;
d.set(t.toolCallId, {
args: t.args,
kind: t.kind,
tracked: n,
startedAt: Date.now()
});
recordToolSummary(t, false);
signalExecutionPhase("tool_execution_started");
if (n) e.toolTracking.handleCliToolUseStart(t);
if (r) emitToolEvent({
phase: "start",
name: t.name,
toolCallId: t.toolCallId,
args: t.args
});
};
const readNativeSkillCommand = (e) => typeof e?.skill === "string" ? t.claudeSkillsPlugin.skillCommands?.get(e.skill.trim()) : void 0;
const emitToolResult = (a, o) => {
i = true;
const s = prepareToolResult(a.result);
const c = recordToolSummary(a, a.isError);
const l = !c.terminalObserved;
c.terminalObserved = true;
const u = o ? e.toolTracking.resolveCliLoopbackTerminalOutcome(a.toolCallId) : void 0;
const f = o && !a.isError && stripOpenClawMcpToolPrefix(a.name) === "browser" ? e.toolTracking.resolveCliLoopbackBrowserTab(a.toolCallId) : void 0;
const p = o ? e.toolTracking.handleCliToolResult(a) : void 0;
const m = d.get(a.toolCallId);
d.delete(a.toolCallId);
const h = a.name === "Skill" && l && !a.isError ? readNativeSkillCommand(m?.args) : void 0;
if (h) recordSkillUsed({
ctx: n,
match: resolvedSkillUsageMatch({
activation: "read",
skill: h
}),
toolName: a.name,
toolCallId: a.toolCallId
});
if (a.name.trim() && l && !n.isolatedCompletion && !u && stripOpenClawMcpToolPrefix(a.name) === a.name) {
const e = s();
runAgentHarnessAfterToolCallHook({
toolName: normalizeCliToolName(a.name),
toolCallId: a.toolCallId,
runId: n.runId,
agentId: n.agentId,
sessionId: n.sessionId,
sessionKey: n.sessionKey,
channelId: n.currentChannelId,
startArgs: p ?? m?.args ?? {},
result: e,
...a.isError ? { error: extractToolErrorMessage(e) ?? "CLI tool execution failed" } : {},
startedAt: m?.startedAt
}).catch(() => {});
}
if (r) {
const e = stripOpenClawMcpToolPrefix(a.name);
const r = o ? t.resultContentSourceByToolName?.get(e) : void 0;
const i = m?.args;
const c = o && m?.tracked && !a.isError && (!u || u.outcome === "completed") && isAgentPlanProgressToolName(e) ? projectProgressCardChannelUpdate(p ?? i) : void 0;
if (c) emitAgentEvent({
runId: n.runId,
stream: "plan",
data: {
phase: "update",
title: "Plan updated",
source: "openclaw",
...c
}
});
emitToolEvent({
phase: "result",
name: a.name,
toolCallId: a.toolCallId,
isError: a.isError,
result: f === void 0 ? s() : withBrowserTabDetails(s(), f),
...o && i ? { args: i } : {},
...r ? { resultContentSource: r } : {}
}, {
args: p ?? (m?.kind === "tool_use" && !a.name.startsWith("mcp_") ? i : void 0),
requestedArgs: i
});
}
};
const emitParsedToolUseStart = (e) => {
const r = Date.now();
p.set(e.toolCallId, {
startedAt: r,
toolName: e.name,
kind: e.kind
});
const i = {
type: "tool.execution.started",
runId: n.runId,
sessionId: n.sessionId,
...n.sessionKey ? { sessionKey: n.sessionKey } : {},
...n.agentId ? { agentId: n.agentId } : {},
toolName: e.name,
toolSource: resolveCliToolSource(e.name, e.kind),
toolOwner: "cli-runner",
toolCallId: e.toolCallId
};
const a = t.managedMcpToolTimeoutMs;
const o = a !== void 0 && e.name.startsWith("mcp__openclaw__") ? r + a : void 0;
n.diagnosticOwner?.watchdogAttempt?.toolEvent({
phase: "start",
toolName: e.name,
toolCallId: e.toolCallId,
deadlineAtMs: o
});
emitTrustedDiagnosticEvent(o === void 0 ? i : markToolExecutionLivenessDiagnosticEvent(i, { deadlineAtMs: o }));
emitToolUseStart(e, true);
};
const emitParsedToolTerminal = (t) => {
const r = p.get(t.toolCallId);
p.delete(t.toolCallId);
const i = e.toolTracking.resolveCliLoopbackTerminalOutcome(t.toolCallId);
const a = r?.toolName ?? t.name;
if (!t.incomplete) n.diagnosticOwner?.watchdogAttempt?.toolEvent({
phase: "end",
toolName: a,
toolCallId: t.toolCallId
});
const o = Date.now();
const s = i && i.outcome !== "blocked" && i.outcome !== "completed" && i.outcome !== "unknown" ? i.outcome : void 0;
const c = e.getRunState();
const l = s ?? resolveCliToolTerminalReason({
error: t.incomplete ? c.error : void 0,
abortSignal: n.abortSignal
});
const u = t.incomplete && c.failed && r !== void 0 && r.kind !== "server_tool_use";
const d = {
runId: n.runId,
sessionId: n.sessionId,
...n.sessionKey ? { sessionKey: n.sessionKey } : {},
...n.agentId ? { agentId: n.agentId } : {},
toolName: a,
toolSource: resolveCliToolSource(a, r?.kind),
toolOwner: "cli-runner",
toolCallId: t.toolCallId,
durationMs: Math.max(0, o - (r?.startedAt ?? o))
};
if (i?.outcome === "unknown" && !u || t.incomplete && r?.kind === "server_tool_use" && !i) {
emitTrustedDiagnosticEvent({
type: "tool.execution.error",
...d,
errorCategory: "cli_tool_ambiguous",
errorCode: "tool_outcome_unknown"
});
return;
}
const f = i !== void 0 && i.outcome !== "completed";
emitTrustedDiagnosticEvent(i?.outcome === "blocked" ? {
type: "tool.execution.blocked",
...d,
deniedReason: i.deniedReason,
reason: "blocked by before-tool policy"
} : f || !i && t.isError ? {
type: "tool.execution.error",
...d,
errorCategory: l === "cancelled" ? "aborted" : t.incomplete && (!i || u) ? "cli_tool_incomplete" : "cli_tool",
terminalReason: l
} : {
type: "tool.execution.completed",
...d
});
};
const emitParsedToolResult = (e) => {
emitParsedToolTerminal(e);
emitToolResult(e, true);
};
const emitCliCompaction = (e) => {
i = true;
const n = a;
a = e.phase === "start";
if (a !== n) o?.();
emitLiveEvent("compaction", () => ({
...e,
backend: t.backendResolved.id
}));
};
const finalizeParsedTools = () => {
for (const [e, t] of Array.from(p)) emitParsedToolTerminal({
toolCallId: e,
name: t.toolName,
isError: true,
incomplete: true
});
};
const emitCliCommentaryText = (i) => {
if (!r || e.toolTracking.shouldSuppressAssistantOutput()) return;
const a = prepareAgentRunTerminalReply({ rawText: i });
const o = applyPluginTextReplacements(a.text, t.backendResolved.textTransforms?.output);
if (!o) return;
c += 1;
emitLiveEvent("item", () => ({
kind: "preamble",
itemId: `commentary-${n.runId}-${c}`,
phase: "end",
title: "commentary",
status: "running",
progressText: o
}));
};
const emitCliAssistantDelta = ({ text: r, delta: a }) => {
if (e.toolTracking.shouldSuppressAssistantOutput()) return;
if (r || a) {
n.diagnosticOwner?.watchdogAttempt?.progress("semantic", "cli:assistant");
i = true;
signalExecutionPhase("assistant_output_started");
}
const o = r.trimStart().toUpperCase();
const s = stripMixedSilentReplyTokens(r);
if (s === null && ("NO_REPLY".startsWith(o) || isSilentReplyText(o))) return;
const c = s ?? r;
const u = c.startsWith(l) ? c.slice(l.length) : c;
l = c;
const d = applyPluginTextReplacements(c, t.backendResolved.textTransforms?.output);
emitLiveEvent("assistant", () => ({
itemId: cliAssistantItemId(n.runId),
text: d,
delta: applyPluginTextReplacements(u, t.backendResolved.textTransforms?.output)
}));
};
const emitCliCompletedReply = (r, a) => {
if (e.toolTracking.shouldSuppressAssistantOutput()) return;
if (r) {
n.diagnosticOwner?.watchdogAttempt?.progress("semantic", "cli:completed_reply");
i = true;
}
l = "";
const o = prepareAgentRunTerminalReply({ rawText: r });
const s = applyPluginTextReplacements(o.text, t.backendResolved.textTransforms?.output);
if (!s) return;
emitLiveEvent("assistant", () => ({
assistantMessageIndex: a,
completedText: s
}));
};
const emitCliThinkingDelta = ({ text: t, delta: r, isReasoningSnapshot: a, modelProgress: o }) => {
if (e.toolTracking.shouldSuppressAssistantOutput()) return;
if (o) n.diagnosticOwner?.watchdogAttempt?.progressModel("cli:thinking");
if (t || r) i = true;
emitLiveEvent("thinking", () => ({
text: t,
delta: r,
...a ? { isReasoningSnapshot: a } : {}
}));
};
const emitCliThinkingProgress = ({ progressTokens: t, modelProgress: r }) => {
if (!e.toolTracking.shouldSuppressAssistantOutput() && r) n.diagnosticOwner?.watchdogAttempt?.progressModel("cli:thinking_tokens");
i = true;
emitLiveEvent("thinking", () => ({ progressTokens: t }));
};
const emitCliToolInputDelta = (e) => {
i = true;
emitLiveEvent("tool", () => ({
phase: "input_delta",
...e
}));
};
return {
emitLiveEvents: r,
emitCliToolInputDelta,
emitCliDisplayToolUseStart: (e) => emitToolUseStart(e, false),
emitCliDisplayToolResult: (e) => emitToolResult(e, false),
emitParsedToolUseStart,
emitParsedToolResult,
emitCliCompaction,
finalizeParsedTools,
emitCliCommentaryText,
emitCliAssistantDelta,
emitCliCompletedReply,
emitCliThinkingDelta,
emitCliThinkingProgress,
hasObservedCliActivity: () => i,
hasActiveCompaction: () => a,
setOnCompactionActiveChange: (e) => {
o = e;
},
activeParsedToolCount: () => p.size,
isActiveForegroundAgentTool: (e) => {
const t = p.get(e);
return t !== void 0 && isClaudeForegroundAgentToolName(t.toolName);
},
getToolSummary
};
}
//#endregion
//#region src/gateway/node-claude-skill-runtime.ts
/** Captures the real session assignment, connection, and admitted owner before any file work. */
async function prepareNodeClaudeSkillRuntime(e, t) {
const n = e.params;
if (n.controlOperation || !n.skillsSnapshot?.librarySelections?.length && !e.nodeSkillWorkshop) return;
const r = getInProcessGatewayRequestContext();
const i = e.executionTarget;
const a = i.kind === "node" ? r?.nodeRegistry.get(i.placement.nodeId) : void 0;
if (!r || !a || !a.caps.includes("claude-cli-skills-v1")) throw new Error("Paired node needs claude-cli-skills-v1. Upgrade OpenClaw on the paired node, restart its node host, and retry this turn.");
const o = resolveAdmittedRunActiveAssertion(n.admittedRunContext, t);
if (!o || !n.sessionKey) throw new Error("Paired-node skills require a live admitted session. Send a fresh message.");
const s = n.sessionKey;
const c = {
sessionKey: s,
agentId: n.agentId,
storePath: n.storePath,
hydrateSkillPromptRefs: false,
readConsistency: "latest"
};
const l = a.connId;
const u = a.pairingGeneration;
const d = getGatewayToolCallerIdentity();
const f = captureSessionEntryMetadataRead(c, o);
let p = true;
let m;
let unregisterSource = () => {};
const releaseSource = async () => {
p = false;
m?.release();
unregisterSource();
};
const readSession = async () => f ? f.readCurrent() : await withSessionEntryReadOnlyInWorker(c, o, async (e, t) => {
if (!e.ok) throw e.error;
const n = e.value;
if (t.kind === "file" && typeof t.source?.databaseIdentity === "string") {
m = retainPreparedSessionEntryPredicate({
databaseIdentity: `file:${t.source.databaseIdentity}`,
sessionKey: t.scope?.sessionKey ?? s,
entry: n,
matches: (e, t) => e?.sessionId === t?.sessionId && e?.lifecycleRevision === t?.lifecycleRevision && e?.execHost === t?.execHost && e?.execNode === t?.execNode && e?.execCwd === t?.execCwd
});
unregisterSource = registerOpenClawAgentDatabaseAsyncResource({
agentId: t.source.agentId,
path: t.source.path,
revoke: () => {
releaseSource();
},
close: releaseSource
});
}
return n;
});
const h = await readSession().catch(async (e) => {
await releaseSource();
throw e;
});
const g = r.workerSessionPlacementService;
const readPlacement = () => g?.getMany([n.sessionId]).get(n.sessionId);
const _ = await readSessionWorkerPlacementAsync({
context: r,
sessionId: n.sessionId
}).catch(async (e) => {
await releaseSource();
throw e;
});
const v = _?.turnClaim;
const y = v?.owner === "local" ? {
sessionId: n.sessionId,
claimId: v.claimId,
runId: v.runId,
placementGeneration: v.generation,
owner: {
kind: "local",
..._?.environmentId && _.activeOwnerEpoch !== null ? {
environmentId: _.environmentId,
ownerEpoch: _.activeOwnerEpoch
} : {}
}
} : void 0;
const b = new AbortController();
const x = getAdmittedRunDelegatedAuthority(n.admittedRunContext);
const S = registerAgentRunDelegatedAuthorityClosedHandler((e) => {
if (e === x) b.abort(/* @__PURE__ */ new Error("Paired-node skill run authority closed."));
});
const C = y && _ ? g?.registerTurnClaimClosedHandler?.((e) => {
if (e.sessionId === n.sessionId && isCurrentPlacementTurnClaim(_, e)) b.abort(/* @__PURE__ */ new Error("Paired-node skill placement claim closed."));
}) : void 0;
const w = AbortSignal.any([t, b.signal]);
const close = () => {
S();
C?.();
b.abort();
return releaseSource();
};
const T = Object.assign(() => {
if (d?.receiptAuthority?.() === false) throw new Error("Paired-node skill assignment or run authority changed. Retry from a fresh turn.");
}, d?.receiptAuthority);
const E = composeSessionSourceAssertion([o, T], (e) => {
e();
w.throwIfAborted();
const t = f ? f.readCurrent() : h;
const o = readPlacement();
if (!p || !f && !m?.isCurrent() || r.nodeRegistry.get(a.nodeId) !== a || a.connId !== l || a.pairingGeneration !== u || a.client.socket.readyState !== 1 || !a.caps.includes("claude-cli-skills-v1") || !isNodeCommandAllowed({
command: "agent.cli.claude.run.v1",
declaredCommands: a.commands,
allowlist: resolveNodeCommandAllowlist(r.getRuntimeConfig(), {
...a,
approvedCommands: a.commands
})
}).ok || !h || h.sessionId !== n.sessionId || (n.expectedLifecycleRevision ?? n.sessionEntry?.lifecycleRevision) !== void 0 && h.lifecycleRevision !== (n.expectedLifecycleRevision ?? n.sessionEntry?.lifecycleRevision) || t?.sessionId !== h.sessionId || t?.lifecycleRevision !== h.lifecycleRevision || t.execHost !== "node" || t.execNode?.trim() !== a.nodeId || (t.execCwd?.trim() || void 0) !== (i.kind === "node" ? i.placement.cwd : void 0) || o?.generation !== _?.generation || o?.environmentId !== _?.environmentId || o?.activeOwnerEpoch !== _?.activeOwnerEpoch || _ && (!y || !C || y.runId !== n.runId || !o || !isCurrentPlacementTurnClaim(o, y))) throw new Error("Paired-node skill assignment or run authority changed. Retry from a fresh turn.");
});
try {
E();
const t = n.skillsSnapshot;
const r = t?.librarySelections?.length ? await runWithSessionSourceScope(E, () => prepareSkillResourceDelivery(t, E, [], e.workspaceDir), { checkAfter: false }) : void 0;
E();
const i = e.nodeSkillWorkshop;
const o = i ? buildMcpToolSchema([i])[0] : void 0;
const s = {
type: "init",
...r ? { resources: r } : {},
...o ? { workshop: {
description: o.description ?? "",
inputSchema: o.inputSchema
} } : {}
};
encodeNodeClaudeSkillMessage(s, NODE_CLAUDE_SKILLS_MESSAGE_BYTES);
return {
node: a,
run: n,
init: s,
workshop: i,
assertCurrent: E,
signal: w,
close
};
} catch (e) {
await close();
throw e;
}
}
/** One invocation owns resource delivery, stdout, and host-only Workshop callbacks. */
async function invokeNodeClaudeSkillRuntime(e) {
const { runtime: t, registry: n } = e;
t.assertCurrent();
const r = new AbortController();
const i = AbortSignal.any([t.signal, r.signal]);
let a;
const o = composeSessionSourceAssertion([t.assertCurrent], (e) => {
e();
i.throwIfAborted();
if (!a || !n.isInvokeCurrent(a, t.node.nodeId, t.node.connId)) throw new Error("Paired-node Workshop invocation is no longer active.");
});
const s = createAdmittedGatewayToolCallerIdentity({
admittedRunContext: t.run.admittedRunContext,
agentId: t.run.agentId,
sessionKey: t.run.sessionKey,
receiptAuthority: o
});
const c = createPluginToolsMcpHandlers(t.workshop ? [t.workshop] : []);
const l = /* @__PURE__ */ new Set();
const u = /* @__PURE__ */ new Set();
const d = createNodeDuplexEndpoint({
requireReady: true,
maxMessageBytes: NODE_CLAUDE_SKILLS_MESSAGE_BYTES,
sendFrame(e) {
o();
n.sendInvokeInput(a, e);
},
onReady() {
o();
runWithSessionSourceScope(o, async () => {
o();
await d.send(encodeNodeClaudeSkillMessage(t.init, NODE_CLAUDE_SKILLS_MESSAGE_BYTES));
}, { checkAfter: false }).catch((e) => r.abort(e));
},
onError: (e) => r.abort(e)
});
const receive = async (n) => {
o();
if (n.byteLength > 67108864) throw new Error("Paired-node Workshop request exceeds its limit.");
const r = JSON.parse(Buffer.from(n).toString("utf8"));
if (!Value.Check(NodeClaudeSkillUpstreamSchema, r)) throw new Error("Invalid paired-node skill message.");
if (r.type === "stdout") {
await runWithSessionSourceScope(o, async () => {
o();
e.onProgress(r.text);
}, { checkAfter: false });
return;
}
if (!t.workshop || !s || l.has(r.id) || l.size >= 64) throw new Error("Paired-node Workshop callback is unavailable or already consumed. Send a fresh message.");
l.add(r.id);
const a = await withGatewayToolCallerIdentity(s, () => c.callTool({
name: "skill_workshop",
arguments: r.arguments
}, i));
await runWithSessionSourceScope(o, async () => {
o();
await d.send(encodeNodeClaudeSkillMessage({
type: "result",
id: r.id,
result: a
}, NODE_CLAUDE_WORKSHOP_RESULT_BYTES));
}, { checkAfter: false });
};
d.onMessage((e) => {
const t = receive(e).finally(() => u.delete(t));
u.add(t);
return t;
});
const abort = () => d.close();
i.addEventListener("abort", abort, { once: true });
try {
return await n.invoke({
...e.invocation,
signal: i,
expectedConnId: t.node.connId,
expectedPairingGeneration: t.node.pairingGeneration,
isDispatchAuthorized: Object.assign(() => {
t.assertCurrent();
return !i.aborted && e.invocation.isDispatchAuthorized?.() !== false;
}, t.assertCurrent),
onDispatchReady: (e) => {
a = e;
},
onProgress: (e) => {
o();
d.receive(e);
}
});
} finally {
r.abort();
i.removeEventListener("abort", abort);
d.close();
await Promise.allSettled(u);
}
}
//#endregion
//#region src/gateway/node-agent-cli-runtime.ts
/** In-process Gateway seam for streaming a Claude CLI turn from a paired node. */
async function invokeNodeClaudeCliRun(e) {
const t = getInProcessGatewayRequestContext();
if (!t) return {
ok: false,
error: {
code: "UNAVAILABLE",
message: "Gateway node runtime unavailable"
}
};
const n = t.nodeRegistry.get(e.nodeId);
if (!n || !n.commands.includes("agent.cli.claude.run.v1")) return {
ok: false,
error: {
code: "UNAVAILABLE",
message: "paired node does not advertise Claude CLI agent runs"
}
};
const r = resolveNodeCommandAllowlist(t.getRuntimeConfig(), {
...n,
approvedCommands: n.commands
});
const i = isNodeCommandAllowed({
command: NODE_AGENT_CLI_CLAUDE_RUN_COMMAND,
declaredCommands: n.commands,
allowlist: r
});
if (!i.ok) return {
ok: false,
error: {
code: "PERMISSION_DENIED",
message: `paired-node Claude CLI agent runs are blocked by node command policy (${i.reason})`
}
};
e.skillRuntime?.assertCurrent();
const a = e.assertReadable;
const o = {
nodeId: e.nodeId,
expectedConnId: n.connId,
...n.pairingGeneration ? { expectedPairingGeneration: n.pairingGeneration } : {},
command: NODE_AGENT_CLI_CLAUDE_RUN_COMMAND,
params: {
argv: e.argv,
stdin: e.stdin,
...e.cwd ? { cwd: e.cwd } : {},
...e.env ? { env: e.env } : {},
...e.clearEnv ? { clearEnv: e.clearEnv } : {},
...e.nativeAuthOnly && n.caps.includes("claude-cli-native-auth-v1") ? { nativeAuthOnly: true } : {},
...e.systemPrompt !== void 0 ? { systemPrompt: e.systemPrompt } : {},
...e.agentId ? { agentId: e.agentId } : {},
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.approvalDecision ? { approvalDecision: e.approvalDecision } : {},
...e.systemRunPlan ? { systemRunPlan: e.systemRunPlan } : {},
idleTimeoutMs: e.idleTimeoutMs,
timeoutMs: e.timeoutMs,
...e.skillRuntime ? { skillRuntime: true } : {}
},
timeoutMs: e.timeoutMs,
idleTimeoutMs: e.idleTimeoutMs,
idempotencyKey: randomUUID(),
onProgress: e.onProgress,
...e.signal ? { signal: e.signal } : {},
authorizeDispatch: a ? async () => {
await a();
e.assertCurrent?.();
return true;
} : void 0,
isDispatchAuthorized: () => {
e.assertCurrent?.();
return true;
}
};
return e.skillRuntime ? await invokeNodeClaudeSkillRuntime({
registry: t.nodeRegistry,
invocation: o,
runtime: e.skillRuntime,
onProgress: e.onProgress
}) : await t.nodeRegistry.invoke(o);
}
//#endregion
//#region src/agents/cli-runner/execute-node-claude.ts
const NODE_CLI_MAX_TIMEOUT_MS = 864e5;
const NODE_CLI_MAX_IDLE_TIMEOUT_MS = 18e5;
const NODE_CLI_OMIT_BARE_ARGS = /* @__PURE__ */ new Set(["--strict-mcp-config", "--exclude-dynamic-system-prompt-sections"]);
const NODE_CLI_OMIT_VALUE_ARGS = /* @__PURE__ */ new Set([
"--permission-mode",
"--plugin-dir",
"--plugin-dir-no-mcp"
]);
const NODE_CLI_OMIT_VARIADIC_ARGS = /* @__PURE__ */ new Set([
"--mcp-config",
"--allowedTools",
"--allowed-tools"
]);
/** Remove Gateway-local file, plugin, MCP, and allow-list arguments. */
function stripGatewayLocalClaudeArgs(e) {
const t = [];
for (let n = 0; n < e.length; n += 1) {
const r = e[n] ?? "";
const i = r.indexOf("=");
const a = i > 0 ? r.slice(0, i) : r;
if (NODE_CLI_OMIT_BARE_ARGS.has(a)) continue;
if (NODE_CLI_OMIT_VALUE_ARGS.has(a)) {
if (i < 0) n += 1;
continue;
}
if (NODE_CLI_OMIT_VARIADIC_ARGS.has(a)) {
if (i < 0) while (typeof e[n + 1] === "string" && !e[n + 1]?.startsWith("-")) n += 1;
continue;
}
t.push(r);
}
return t;
}
function parseNodeClaudePayload(e) {
return asNullableRecord(e.payloadJSON ? JSON.parse(e.payloadJSON) : e.payload);
}
function parseNodeClaudeResultPayload(e) {
if (!e) throw new Error("paired node returned an invalid Claude CLI result");
if (!Number.isInteger(e.exitCode) || typeof e.stderrTail !== "string" || typeof e.truncated !== "boolean" || e.timeoutKind !== void 0 && e.timeoutKind !== "hard" && e.timeoutKind !== "idle") throw new Error("paired node returned an invalid Claude CLI result");
return {
exitCode: e.exitCode,
stderrTail: e.stderrTail,
truncated: e.truncated,
...e.timeoutKind ? { timeoutKind: e.timeoutKind } : {}
};
}
function parseNodeClaudeApprovalRequired(e) {
if (!e) return null;
if (e.approvalRequired !== true || !e.systemRunPlan || typeof e.systemRunPlan !== "object" || Array.isArray(e.systemRunPlan) || e.security !== "deny" && e.security !== "allowlist" && e.security !== "full" || e.ask !== "off" && e.ask !== "on-miss" && e.ask !== "always") return null;
return {
systemRunPlan: e.systemRunPlan,
security: e.security,
ask: e.ask
};
}
function createCliAbortError() {
return createAbortError("CLI run aborted");
}
async function executeNodeClaudeRun(e) {
const t = e.context.params;
const n = Date.now();
const r = Math.min(t.timeoutMs, NODE_CLI_MAX_TIMEOUT_MS);
const i = n + r;
const a = new AbortController();
const o = a.signal;
const s = createCliRunCurrentAssertion(t, o);
let c = false;
const l = setTimeout(() => {
c = true;
a.abort();
}, r);
const abortNodeRun = () => a.abort();
t.abortSignal?.addEventListener("abort", abortNodeRun, { once: true });
if (t.abortSignal?.aborted) abortNodeRun();
const u = attachCliReplyBackend(t, abortNodeRun);
const hardTimeoutResult = () => ({
ok: false,
error: {
code: "TIMEOUT",
message: "paired-node Claude CLI invocation exceeded its hard timeout"
}
});
let d;
let f;
let p;
try {
s();
p = await prepareNodeClaudeSkillRuntime(e.context, o);
const invokeNode = async (n) => {
const r = i - Date.now();
if (r <= 0) {
c = true;
a.abort();
return hardTimeoutResult();
}
s();
return await runWithAgentToolSourceExecutionScope(s, () => invokeNodeClaudeCliRun({
assertCurrent: s,
assertReadable: e.context.cliHistoryWriter?.assertReadable,
nodeId: e.nodePlacement.nodeId,
argv: e.executionArgs,
stdin: e.stdinPayload,
...e.nodePlacement.cwd ? { cwd: e.nodePlacement.cwd } : {},
...e.nodeSystemPrompt !== void 0 ? { systemPrompt: e.nodeSystemPrompt } : {},
...e.nodeEnv ? { env: e.nodeEnv } : {},
...e.nodeClearEnv ? { clearEnv: e.nodeClearEnv } : {},
...t.nativeAuthOnly ? { nativeAuthOnly: true } : {},
...t.agentId ? { agentId: t.agentId } : {},
...t.sessionKey ? { sessionKey: t.sessionKey } : {},
...n ? {
approvalDecision: n.decision,
systemRunPlan: n.plan
} : {},
timeoutMs: r,
idleTimeoutMs: Math.max(1e3, Math.min(e.noOutputTimeoutMs, NODE_CLI_MAX_IDLE_TIMEOUT_MS)),
onProgress: e.consumeStdout,
signal: p?.signal ?? a.signal,
...p ? { skillRuntime: p } : {}
}));
};
d = await invokeNode();
f = d.ok ? parseNodeClaudePayload(d) : null;
const n = parseNodeClaudeApprovalRequired(f);
if (n) {
p?.assertCurrent();
const r = crypto.randomUUID();
const i = await racePromiseWithAbortSignal(() => registerExecApprovalRequestForHostOrThrow({
approvalId: r,
command: n.systemRunPlan.commandText,
commandArgv: n.systemRunPlan.argv,
systemRunPlan: n.systemRunPlan,
workdir: n.systemRunPlan.cwd ?? void 0,
host: "node",
nodeId: e.nodePlacement.nodeId,
security: n.security,
ask: n.ask,
unavailableDecisions: ["allow-always"],
agentId: t.agentId,
sessionKey: t.sessionKey,
...t.approvalReviewerDeviceId ? { approvalReviewerDeviceIds: [t.approvalReviewerDeviceId] } : {}
}), p?.signal ?? a.signal, createCliAbortError);
const o = await racePromiseWithAbortSignal(() => resolveRegisteredExecApprovalDecision({
approvalId: i.id,
expiresAtMs: i.expiresAtMs,
preResolvedDecision: i.finalDecision
}), p?.signal ?? a.signal, createCliAbortError);
if (o === "allow-once" || o === "allow-always") {
d = await invokeNode({
decision: o,
plan: n.systemRunPlan
});
f = void 0;
} else d = {
ok: false,
error: {
code: "PERMISSION_DENIED",
message: "paired-node Claude CLI agent run was not approved"
}
};
}
} catch (e) {
if (!c) throw e;
d = hardTimeoutResult();
} finally {
if (p?.signal.aborted) a.abort();
await p?.close();
clearTimeout(l);
u?.();
t.abortSignal?.removeEventListener("abort", abortNodeRun);
}
if (c) d = hardTimeoutResult();
const m = d.ok ? void 0 : d.error?.code;
const h = d.ok ? void 0 : Date.now() - n;
const g = d.ok ? parseNodeClaudeResultPayload(f === void 0 ? parseNodeClaudePayload(d) : f) : {
exitCode: 1,
stderrTail: d.error?.message ?? "paired-node Claude CLI invocation failed",
truncated: false,
timeoutKind: m === "IDLE_TIMEOUT" ? "idle" : m === "TIMEOUT" ? "hard" : void 0
};
if (!d.ok || g.stderrTail) e.consumeStderr(g.stderrTail);
return {
result: {
reason: g.timeoutKind === "idle" ? "no-output-timeout" : g.timeoutKind === "hard" ? "overall-timeout" : m === "ABORTED" ? "manual-cancel" : "exit",
exitCode: g.timeoutKind || m === "ABORTED" ? null : g.exitCode,
exitSignal: null,
durationMs: h ?? Date.now() - n,
stdout: "",
stderr: g.stderrTail,
timedOut: g.timeoutKind !== void 0,
noOutputTimedOut: g.timeoutKind === "idle"
},
nodeRunAbortSignal: o,
nodeRunTruncated: g.truncated
};
}
//#endregion
//#region src/agents/cli-runner/cli-native-tool-approval.ts
const CLI_NATIVE_TOOL_DESCRIPTION_HEAD_CHARS = 300;
const CLI_NATIVE_TOOL_DESCRIPTION_TAIL_CHARS = 80;
const CLI_NATIVE_TOOL_DESCRIPTION_MAX_CHARS = 380;
const CLI_NATIVE_TOOL_APPROVAL_GATEWAY_GRACE_MS = 1e4;
const CLI_NATIVE_TOOL_ARBITRARY_EXECUTION_TOOL = "Bash";
function resolveCliNativeToolApprovalPlan(e) {
if (e.security === "deny") return "deny";
if (e.ask === "off") return e.security === "full" ? "allow" : "deny";
return "prompt";
}
/**
* The gateway caps approval descriptions (PLUGIN_APPROVAL_DESCRIPTION_MAX_LENGTH),
* so full inputs cannot ride this channel. Head+tail display defeats padded
* prefixes hiding an executable tail, and the quantified marker makes a partial
* view an explicit operator decision. Accepted tradeoff: the middle stays
* unreviewable; oversized inputs therefore never earn allow-always.
*/
function formatCliNativeToolDescription(e) {
const t = JSON.stringify(e) ?? "{}";
if (t.length <= CLI_NATIVE_TOOL_DESCRIPTION_MAX_CHARS) return {
compact: t,
text: t,
truncated: false
};
const n = truncateUtf16Safe(t, CLI_NATIVE_TOOL_DESCRIPTION_HEAD_CHARS);
const r = sliceUtf16Safe(t, t.length - CLI_NATIVE_TOOL_DESCRIPTION_TAIL_CHARS);
return {
compact: t,
text: `${n} …[+${t.length - n.length - r.length} chars hidden]… ${r}`,
truncated: true
};
}
async function requestCliNativeToolApproval(e) {
try {
const t = DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS;
const n = addTimerTimeoutGraceMs(t, CLI_NATIVE_TOOL_APPROVAL_GATEWAY_GRACE_MS) ?? t + CLI_NATIVE_TOOL_APPROVAL_GATEWAY_GRACE_MS;
const r = formatCliNativeToolDescription(e.toolInput);
const i = e.toolName === CLI_NATIVE_TOOL_ARBITRARY_EXECUTION_TOOL ? sanitizeExecApprovalWarningTextWithStatus(r.text) : null;
if (e.toolName === CLI_NATIVE_TOOL_ARBITRARY_EXECUTION_TOOL && (r.truncated || i?.truncated === true || i?.oversized === true || i && exceedsApprovalTextLimit(i.text, 512))) return {
kind: "deny",
reason: "policy-oversized"
};
const a = e.toolName === CLI_NATIVE_TOOL_ARBITRARY_EXECUTION_TOOL && typeof e.toolInput.command === "string" ? e.toolInput.command : void 0;
let autoAllow;
if (e.ask === "on-miss" && e.pluginId === "claude-cli" && a && e.agentId) {
const t = captureOpenClawStateWorkerContext();
const n = (await readExecApprovalsSnapshotAsync(t)).file;
e.abortSignal?.throwIfAborted();
e.assertActive?.();
const { allowlist: i } = resolveExecApprovalsFromFileInternal({
file: n,
agentId: e.agentId
});
const o = await evaluateShellAllowlistWithAuthorization({
command: a,
allowlist: i,
safeBins: /* @__PURE__ */ new Set(),
cwd: e.cwd,
env: e.env
});
const s = o.authorizationPlan;
const c = s?.groups.flatMap((e) => e.candidates) ?? [];
const l = c.findIndex((e, t) => e.transport.kind !== "direct" || e.trustMode !== "executable" || !e.sourceSegment.resolution?.execution.resolvedPath || e.sourceSegment.resolution.wrapperChain?.length || o.segmentSatisfiedBy[t] !== "allowlist");
const u = s?.ok && e.cwd && c.length > 0 && l === -1 ? buildAuthorizedShellCommandFromPlan({
plan: s,
mode: "enforced",
segmentSatisfiedBy: o.segmentSatisfiedBy
}) : {
ok: false,
reason: s && !s.ok ? s.reason : c[l]?.sourceStep.text ?? "no classified executable"
};
if (u.ok) autoAllow = async () => {
const assertCurrent = () => {
e.abortSignal?.throwIfAborted();
e.assertActive?.();
};
assertCurrent();
const n = {
source: "current-policy",
security: "allowlist",
ask: e.ask,
allowlistSatisfied: true
};
const r = await recordAllowlistMatchesUse({
assertCurrent,
agentId: e.agentId,
matches: o.allowlistMatches,
command: a,
resolvedPath: c[0]?.sourceSegment.resolution?.execution.resolvedPath,
authorization: n
}, t);
assertCurrent();
r();
logVerbose("Claude CLI native Bash auto-allowed via exec allowlist");
return {
kind: "allow",
grantAlways: false,
updatedInput: {
...e.toolInput,
command: u.command
}
};
};
else {
const e = sanitizeExecApprovalWarningTextWithStatus(u.reason).text;
r.text += `\nExec allowlist miss: ${truncateUtf16Safe(e, 100)}`;
}
}
let o;
if (e.toolName === CLI_NATIVE_TOOL_ARBITRARY_EXECUTION_TOOL) {
const t = await prepareSystemRunMutableFileBinding({
command: {
kind: "shell",
text: a ?? ""
},
cwd: e.cwd ?? e.fallbackCwd,
env: autoAllow ? e.env : e.bindingEnv ?? e.env
});
if (!t.ok) {
const e = t.reason === "unsupported-command-shape" ? `${t.message}\nNo approval request was created for this attempt; this is not a user denial. Retry a supported direct executable/script command with explicit paths through the normal approval flow.` : t.message;
return {
kind: "deny",
reason: "operand-binding",
message: sanitizeExecApprovalWarningTextWithStatus(`${e}\n${r.text}`).text
};
}
o = t.binding.operands.length > 0 ? t.binding : void 0;
}
if (autoAllow) return await autoAllow();
if (a && exceedsApprovalTextLimit(sanitizeExecApprovalWarningTextWithStatus(r.text).text, 512)) return {
kind: "deny",
reason: "policy-oversized"
};
const s = e.ask === "always" || e.toolName === CLI_NATIVE_TOOL_ARBITRARY_EXECUTION_TOOL || r.truncated ? ["allow-once", "deny"] : [
"allow-once",
"allow-always",
"deny"
];
const c = await racePromiseWithAbortSignal(withGatewayToolApprovalOwner(e.pluginId, async () => await callGatewayTool("plugin.approval.request", { timeoutMs: n }, {
pluginId: e.pluginId,
toolName: e.toolName,
toolCallId: e.toolCallId,
agentId: e.agentId,
sessionKey: e.sessionKey,
title: truncateUtf16Safe(`${e.pluginId} native tool: ${e.toolName}`, 80),
description: r.text,
detail: truncatePluginApprovalDetail(r.compact),
severity: "warning",
allowedDecisions: s,
timeoutMs: t,
twoPhase: true
}, {
expectFinal: false,
signal: e.abortSignal
})), e.abortSignal);
const l = typeof c?.id === "string" ? c.id : "";
if (!l) return {
kind: "deny",
reason: "unavailable"
};
let u;
if (Object.hasOwn(c ?? {}, "decision")) u = c.decision;
else {
const t = await racePromiseWithAbortSignal(callGatewayTool("plugin.approval.waitDecision", { timeoutMs: n }, { id: l }, { signal: e.abortSignal }), e.abortSignal);
u = t?.id === l ? t.decision : void 0;
}
if (e.abortSignal?.aborted) return {
kind: "deny",
reason: "unavailable"
};
if ((u === "allow-once" || u === "allow-always") && o) {
const t = await revalidateSystemRunMutableFileBinding({
binding: o,
cwd: e.cwd ?? e.fallbackCwd
});
if (!t.ok) return {
kind: "deny",
reason: "operand-binding",
message: t.message
};
}
if (u === "allow-once" || u === "allow-always" && s.includes(u)) return {
kind: "allow",
grantAlways: u === "allow-always"
};
return {
kind: "deny",
reason: u === "deny" ? "user" : "unavailable"
};
} catch (t) {
if (!e.abortSignal?.aborted) cliBackendLog.warn(`native tool approval unavailable for ${e.toolName}: ${formatErrorMessage(t)}`);
return {
kind: "deny",
reason: "unavailable"
};
}
}
//#endregion
//#region src/agents/cli-runner/execute-plugin-iterator.ts
const PLUGIN_ITERATOR_CLOSE_TIMEOUT_MS = 5e3;
function waitForIteratorValue(e, t) {
return racePromiseWithAbortSignal(() => e.next().catch((e) => {
throw toErrorObject(e, "CLI plugin execution stream failed.");
}), t, () => toErrorObject(t.reason, "CLI plugin execution was aborted."));
}
async function closePluginIterator(e) {
if (!e?.return) return;
try {
await raceWithTimeout(e.return(), PLUGIN_ITERATOR_CLOSE_TIMEOUT_MS, () => {
throw new Error("CLI plugin runtime did not close after its run ended.");
}, { ref: false });
} catch (e) {
recordAgentCleanupFailure();
throw e;
}
}
//#endregion
//#region src/agents/cli-runner/execute-plugin-status.ts
function readTurnAssessment(e) {
if (isRecord(e)) {
const { state: t, basis: n } = e;
if (t === "closed" && (n === "process_exited" || n === "transport_closed")) return {
state: t,
basis: n
};
if (t === "unknown" && (n === "process_present" || n === "status_unsupported" || n === "busy" || n === "transient_error")) return {
state: t,
basis: n
};
}
return {
state: "unknown",
basis: "invalid"
};
}
/** Bind plugin facts to the host's exact registration; the watchdog owns the only timeout. */
function bindCliTurnStatus(e, t) {
return { capture() {
if (!t()) return;
const n = e.capture();
if (!n) return;
const isCurrent = () => t() && n.isCurrent() && t();
return {
isCurrent,
async assess({ signal: e }) {
if (!isCurrent()) return {
state: "unknown",
basis: "status_unsupported"
};
const t = await n.assess({ signal: e });
return isCurrent() ? readTurnAssessment(t) : {
state: "unknown",
basis: "status_unsupported"
};
}
};
} };
}
//#endregion
//#region src/agents/cli-runner/no-output-timeout-policy.ts
const isReplaySafeCliResumeControlOnly = (e, ...t) => e && !t.some(Boolean);
function resolveCliNoOutputTimeoutDecision(e) {
const t = e.cliTimeout.activeToolCount + e.cliTimeout.backgroundTaskCount > 0 || e.cliTimeout.compactionActive === true;
const n = e.outstandingWorkGraceMs;
const r = t && n !== void 0 ? Math.max(e.timeoutMs, n) - e.quietDurationMs : void 0;
const i = !e.cliTimeout.observedActivity && !e.hasOutputText || e.allowResumeControlOnlyRetry === true && isReplaySafeCliResumeControlOnly(e.useResume, e.hasOutputText, e.hasReplayUnsafeActivity, t);
return {
...r !== void 0 && r > 0 ? { deferMs: r } : {},
error: createCliTimeoutError(e.context, e.cliTimeout, i ? "cli_no_output_timeout" : void 0)
};
}
function createCliTimeoutError(e, t, n) {
return createCliFailoverError(t.mode === "no-output" ? `CLI produced no output for ${t.timeoutSeconds}s and was terminated.` : `CLI exceeded timeout (${t.timeoutSeconds}s) and was terminated.`, "timeout", e, {
code: n,
cliTimeout: t,
timeout: { timeoutPhase: "provider" }
});
}
//#endregion
//#region src/agents/cli-runner/execute-plugin-watchdog.ts
const HOST_SUSPEND_TICK_THRESHOLD_MS = 45e3;
const WATCHDOG_TICK_MS = 1e3;
const clock = {
now: () => Date.now(),
setTimeout: (e, t) => {
const n = setTimeout(e, t);
return () => clearTimeout(n);
}
};
function createCliPluginWatchdog(e) {
const t = e.noOutputTimeoutMs;
const n = e.overallTimeoutMs;
let r = clock.now();
let i = 0;
let a = n;
let o;
let s = clock.now();
let c = s;
let l = false;
const dispose = () => {
l = true;
o?.();
o = void 0;
};
const scheduleTick = () => {
if (l || t === void 0 && n === void 0) return;
const e = clock.now();
const r = Math.min(t === void 0 ? Number.POSITIVE_INFINITY : i - e, a === void 0 ? Number.POSITIVE_INFINITY : a - Math.max(0, e - s), WATCHDOG_TICK_MS);
const u = e + Math.max(1, r);
if (o !== void 0 && c <= u) return;
o?.();
c = u;
o = clock.setTimeout(tick, u - e);
};
const tick = () => {
o = void 0;
const n = clock.now();
const l = Math.max(0, n - s);
s = n;
const u = l >= HOST_SUSPEND_TICK_THRESHOLD_MS ? Math.max(0, n - c) : 0;
if (u > 0) {
const t = n - u;
const a = Math.max(0, n - Math.max(r, t));
r += a;
i += a;
cliBackendLog.info(`cli watchdog credited timer gap: provider=${e.provider} model=${e.model} suspendedMs=${Math.round(u)} creditedMs=${Math.round(a)}`);
}
const d = l - u;
if (a !== void 0) {
a -= d;
if (a <= 0) {
dispose();
e.onOverallTimeout();
return;
}
}
if (t !== void 0 && n >= i) {
const a = n - r;
const o = e.getActiveAskUserDeadline?.();
const s = resolveCliNoOutputTimeoutDecision({
context: {
provider: e.provider,
model: e.model,
sessionId: e.sessionId,
lane: e.lane
},
timeoutMs: t,
quietDurationMs: a,
cliTimeout: {
mode: "no-output",
timeoutSeconds: Math.round(a / 1e3),
observedActivity: e.hasObservedActivity(),
activeToolCount: e.activeToolCount(),
backgroundTaskCount: e.backgroundTaskCount(),
compactionActive: e.compactionActive()
},
hasOutputText: false,
useResume: e.useResume,
hasReplayUnsafeActivity: e.hasReplayUnsafeActivity(),
allowResumeControlOnlyRetry: true,
outstandingWorkGraceMs: o === void 0 ? BLOCKED_TOOL_CALL_ABORT_FLOOR_MS : Math.max(BLOCKED_TOOL_CALL_ABORT_FLOOR_MS, o - r)
});
if (s.deferMs !== void 0) i = n + s.deferMs;
else {
dispose();
e.onNoOutputTimeout(s.error);
return;
}
}
scheduleTick();
};
const reset = () => {
if (l) return;
if (t !== void 0) {
const n = r + t;
const a = e.getActiveAskUserDeadline?.();
i = a === void 0 ? n : Math.max(n, a);
}
scheduleTick();
};
return {
noteOutput: () => {
r = clock.now();
reset();
},
reset,
dispose
};
}
//#endregion
//#region src/agents/cli-runner/execute-plugin.steered-transcript.ts
/** One host adapter owns final input admission and accepted transcript custody. */
function createSteeredCliMessageInjection(e) {
const queueMessage = async (t, n, r, i) => {
const a = e.getInjection();
if (!a) throw new Error("CLI plugin runtime does not accept input during its turn.");
const o = e.cwd;
let s = false;
let c;
let l;
const u = n?.userTurnTranscriptRecorder;
try {
const c = await u?.resolveMessage();
const d = n?.currentInboundContext;
await a.queueMessage(t, async (t) => {
let n = false;
try {
await runWithAgentToolSourceExecutionScope(e.assertCurrent, async () => {
await withMessageInjectionAdmission(i, () => {
r();
e.assertCurrent();
t();
n = true;
e.onInputSubmitted?.();
});
});
} catch (e) {
if (n) throw new MessageInjectionAcceptedUnconfirmedError({ cause: e });
throw e;
}
}, {
...isHostGeneratedInputProvenance(c?.provenance) ? { promptOrigin: "host" } : {},
...d ? { promptContext: { prependContext: labelRuntimeContextText(projectRuntimeContextFragments(d.fragments ?? [{
kind: "conversation-data",
text: d.text
}])) } } : {}
});
s = true;
n?.onQueueAccepted?.(true);
if (u && !u.hasPersisted() && !u.isBlocked()) {
if (!await u.persistApproved({ cwd: o }) && !u.hasPersisted() && await u.resolveMessage()) {
u.markBlocked();
l = {
transcriptCommit: "unconfirmed",
errorMessage: "steered CLI user turn transcript commitment could not be confirmed"
};
}
}
} catch (e) {
c = toErrorObject(e, "CLI steering failed.");
}
try {
n?.onQueueSettled?.();
} catch (e) {
c ??= toErrorObject(e, "CLI steering completion observer failed.");
}
if (c) {
if (!s) throw c;
const e = `steered CLI user turn was not settled: ${formatErrorMessage(c)}`;
cliBackendLog.warn(e);
return {
transcriptCommit: "unconfirmed",
errorMessage: e
};
}
return l;
};
return {
version: 2,
isAvailable: () => !e.signal.aborted && e.getInjection()?.isAvailable() === true,
queueMessage: (e, t, n) => queueMessage(e, t, n),
queueMessageAsync: (e, t, n) => queueMessage(e, t, n.assertCurrent, n.prepareCurrent)
};
}
//#endregion
//#region src/agents/cli-runner/execute-plugin.ts
function denyTool(e) {
return {
behavior: "deny",
message: e
};
}
async function createPluginToolPermissionHandler(e) {
const t = e.context.params;
const n = await resolveExecDefaultsAsync({
cfg: t.config,
sessionEntry: t.sessionEntry,
execOverrides: t.execOverrides,
agentId: t.agentId,
sessionKey: t.runtimePolicySessionKey ?? t.sessionKey
});
const r = /* @__PURE__ */ new Set();
return async (i) => {
const a = i.abortSignal ? AbortSignal.any([e.abortSignal, i.abortSignal]) : e.abortSignal;
const o = createCliRunCurrentAssertion(t, a);
try {
o();
} catch {
return denyTool("OpenClaw denied native tool use: the admitted run is no longer active.");
}
const s = i.toolName.trim();
if (!s) return denyTool("OpenClaw denied an unnamed native tool.");
const c = t.cliToolAvailability?.discovery?.includes(s) === true;
if (t.cliToolAvailability && !t.cliToolAvailability.native.includes(s) && !c) return denyTool(`OpenClaw denied native tool ${s}: it is unavailable to this run.`);
const l = normalizeCliToolName(s);
if (e.context.hostOwnedTools?.includes(l)) return denyTool(`Use OpenClaw ${l}; its native equivalent is unavailable.`);
const u = [
"read",
"write",
"edit"
].includes(l) && Object.hasOwn(i.toolInput, "file_path");
let d = i.toolInput;
if (u) {
const e = i.toolInput.file_path;
if (typeof e !== "string") return denyTool("OpenClaw denied native file tool use: invalid file path.");
if (Object.hasOwn(i.toolInput, "path") && i.toolInput.path !== e) return denyTool("OpenClaw denied native file tool use: conflicting file paths.");
d = {
...i.toolInput,
path: e
};
if (l === "edit") {
const { old_string: e, new_string: t, edits: n } = i.toolInput;
if (typeof e !== "string" || typeof t !== "string") return denyTool("OpenClaw denied native edit tool use: invalid replacement.");
if (n !== void 0 && (!Array.isArray(n) || n.length !== 1 || !isRecord(n[0]) || n[0].oldText !== e || n[0].newText !== t)) return denyTool("OpenClaw denied native edit tool use: conflicting replacements.");
d.edits = [{
oldText: e,
newText: t
}];
}
}
const f = {
...t.messageChannel ?? t.messageProvider ? { channel: t.messageChannel ?? t.messageProvider } : {},
...t.agentAccountId ? { accountId: t.agentAccountId } : {},
...t.senderId ? { senderId: t.senderId } : {},
...t.senderIsOwner !== void 0 ? { senderIsOwner: t.senderIsOwner } : {}
};
const p = await runBeforeToolCallHook({
toolName: l,
params: d,
...i.toolCallId ? { toolCallId: i.toolCallId } : {},
signal: a,
ctx: {
...t.agentId ? { agentId: t.agentId } : {},
...t.config ? { config: t.config } : {},
cwd: e.context.cwd ?? e.context.workspaceDir,
workspaceDir: e.context.workspaceDir,
...t.sessionKey ? { sessionKey: t.sessionKey } : {},
sessionId: t.sessionId,
runId: t.runId,
...t.trigger ? { trigger: t.trigger } : {},
...t.approvalReviewerDeviceId ? { approvalReviewerDeviceId: t.approvalReviewerDeviceId } : {},
...t.currentChannelId ? { channelId: t.currentChannelId } : {},
...Object.keys(f).length > 0 ? { requester: f } : {},
turnSourceChannel: t.messageChannel ?? t.messageProvider,
turnSourceTo: t.chatId ?? t.currentChannelId,
turnSourceAccountId: t.agentAccountId,
turnSourceThreadId: t.currentThreadTs,
loopDetection: resolveToolLoopDetectionConfig({
cfg: t.config,
agentId: t.agentId
})
}
});
try {
o();
} catch {
return denyTool("OpenClaw denied native tool use: the admitted run closed during policy.");
}
if (p.blocked) return denyTool(p.reason);
if (!isRecord(p.params)) return denyTool("OpenClaw denied native tool use: before_tool_call returned invalid input.");
let m = p.params;
if (u) {
if (typeof m.path !== "string") return denyTool("OpenClaw denied native file tool use: invalid rewritten file path.");
if (m === d) m = i.toolInput;
else {
m = {
...m,
file_path: m.path
};
if (!Object.hasOwn(i.toolInput, "path")) delete m.path;
if (l === "edit") {
const e = m.edits;
if (!Array.isArray(e) || e.length !== 1 || !isRecord(e[0]) || typeof e[0].oldText !== "string" || typeof e[0].newText !== "string") return denyTool("OpenClaw denied an unrepresentable native edit rewrite.");
m.old_string = e[0].oldText;
m.new_string = e[0].newText;
if (!Object.hasOwn(i.toolInput, "edits")) delete m.edits;
}
}
}
if (c) {
o();
return {
behavior: "allow",
updatedInput: m
};
}
const h = resolveCliNativeToolApprovalPlan(n);
if (h === "deny") return denyTool(`OpenClaw exec policy denied native tool use (security=${n.security}, ask=${n.ask}).`);
const g = getCliLiveSessionApprovalGrants(e.context) ?? r;
if (h === "allow" || n.ask !== "always" && g.has(s)) {
o();
recordAdjustedParamsForToolCall(i.toolCallId, m, t.runId);
return {
behavior: "allow",
updatedInput: m
};
}
e.onPendingApproval(1);
let _;
try {
_ = await requestCliNativeToolApproval({
toolName: s,
toolInput: m,
pluginId: e.context.backendResolved.id,
sessionKey: t.sessionKey,
agentId: t.agentId,
toolCallId: i.toolCallId,
cwd: i.cwd,
fallbackCwd: e.context.cwd ?? e.context.workspaceDir,
bindingEnv: e.env,
env: {
...e.env,
PATH: mergePathPrepend(e.env.PATH, resolveExecToolConfig({
cfg: t.config,
agentId: t.agentId
}).pathPrepend ?? [])
},
assertActive: o,
abortSignal: a,
ask: n.ask
});
} finally {
e.onPendingApproval(-1);
}
try {
o();
} catch {
return denyTool("OpenClaw denied native tool use: the admitted run closed during approval.");
}
if (_.kind !== "allow") return denyTool(_.message ?? (_.reason === "user" ? `OpenClaw user denied native tool use (${s}).` : `OpenClaw approval was not granted for native tool use (${s}).`));
if (_.grantAlways) g.add(s);
const v = _.updatedInput ?? m;
recordAdjustedParamsForToolCall(i.toolCallId, v, t.runId);
return {
behavior: "allow",
updatedInput: v
};
};
}
function cancelUserInput(e) {
return {
status: "cancelled",
message: e
};
}
function createPluginUserInputHandler(e) {
const t = e.context.params;
return async (n) => {
const r = n.abortSignal ? AbortSignal.any([e.abortSignal, n.abortSignal]) : e.abortSignal;
const i = createCliRunCurrentAssertion(t, r);
try {
i();
} catch {
return cancelUserInput("OpenClaw cancelled operator input: the admitted run is no longer active.");
}
const a = n.toolName.trim();
if (!a || t.cliToolAvailability && !t.cliToolAvailability.native.includes(a)) return cancelUserInput(a ? `OpenClaw cancelled operator input from ${a}: it is unavailable to this run.` : "OpenClaw cancelled an unnamed operator input request.");
if (n.questions.length === 0 || n.questions.length > 12) return cancelUserInput("OpenClaw cancelled an invalid operator input request.");
const o = e.context.bindQuestionAnswerAuthority?.(i);
const assertQuestionActive = () => {
i();
o?.assertActive();
};
e.onPendingInput(1);
try {
const e = await withAgentQuestionAnswerAuthority(o, () => runStructuredInput({
input: compileStructuredInputQuestions({
questions: n.questions.map((e) => ({
...e,
isSecret: false
})),
intro: n.intro?.trim() || "Agent needs input:"
}),
sessionKey: t.sessionKey ?? t.sessionId,
agentId: t.agentId,
runId: t.runId,
timeoutMs: t.timeoutMs,
delivery: {
onBlockReply: t.onBlockReply,
onPartialReply: t.onPartialReply
},
signal: r,
isActive: () => assertionSucceeds(assertQuestionActive),
questionId: n.toolCallId ? (e) => `${n.toolCallId}:${e}` : void 0
}));
try {
assertQuestionActive();
} catch {
return cancelUserInput("OpenClaw cancelled operator input: the admitted run closed before the answer was committed.");
}
return e.status === "answered" ? {
status: "answered",
answers: e.answers
} : cancelUserInput(e.message ?? "OpenClaw cancelled operator input; continue with your best judgment.");
} catch {
return cancelUserInput("OpenClaw could not collect operator input; continue with your best judgment.");
} finally {
e.onPendingInput(-1);
}
};
}
/** Runs a prepared plugin transport while keeping cancellation and approvals host-owned. */
async function executePluginOwnedProcess(e) {
const t = e.context.params;
const n = e.context.cwd ?? e.context.workspaceDir;
const r = process.platform === "win32" ? resolveWindowsExecutablePath(e.executionCommand, e.env, n) : e.executionCommand;
let i = resolveExecutablePath(r, {
cwd: n,
env: e.env
});
if (!i) throw new Error(`CLI backend executable could not be resolved: ${e.executionCommand}`);
let a = e.executionArgs;
if (process.platform === "win32") {
const t = resolveWindowsSpawnProgramCandidate({
command: i,
env: e.env
});
i = t.resolution === "node-entrypoint" ? resolveWindowsExecutablePath("node", e.env, n) : t.command;
if (t.leadingArgv.length > 0) a = [...t.leadingArgv, ...a];
}
const o = Date.now();
const s = new AbortController();
const c = t.abortSignal ? AbortSignal.any([s.signal, t.abortSignal]) : s.signal;
const l = createCliRunCurrentAssertion(t, c);
const u = createCliRunCurrentAssertion(t);
const d = { reason: "exit" };
const assertCaptureCurrent = () => (d.reason === "exit" ? u : l)();
const f = {
approvals: 0,
background: 0,
observed: false,
replayUnsafe: false
};
const reportOutstandingWork = () => {
const t = f.approvals > 0 || f.background > 0;
e.onOutstandingWorkChange?.(t || (e.compactionActive?.() ?? false));
};
const updatePendingApproval = (e) => {
f.approvals = Math.max(0, f.approvals + e);
reportOutstandingWork();
};
let p;
let m;
let h;
const g = attachCliReplyBackend(t, () => {
d.reason = "manual-cancel";
s.abort(createCliAbortError());
}, {
get turnStatus() {
return h;
},
supportsTranscriptCommitWait: true,
messageInjectionV2: createSteeredCliMessageInjection({
getInjection: () => m,
signal: c,
assertCurrent: l,
cwd: t.cwd ?? t.workspaceDir,
onInputSubmitted: e.mcpCapture?.onInputSubmitted
})
});
let _;
let v;
let y = "none";
try {
const r = await racePromiseWithAbortSignal(() => createPluginToolPermissionHandler({
context: e.context,
abortSignal: c,
onPendingApproval: updatePendingApproval,
env: e.env
}), c, createCliAbortError);
l();
p = createCliPluginWatchdog({
provider: t.provider,
model: e.context.modelId,
sessionId: t.sessionId,
lane: t.lane,
overallTimeoutMs: clampPositiveTimerTimeoutMs(t.timeoutMs),
noOutputTimeoutMs: clampPositiveTimerTimeoutMs(e.noOutputTimeoutMs),
useResume: e.useResume,
getActiveAskUserDeadline: e.getActiveLoopbackAskUserDeadline,
activeToolCount: () => Math.max(e.activeToolCount?.() ?? 0, f.approvals),
backgroundTaskCount: () => f.background,
compactionActive: () => e.compactionActive?.() ?? false,
hasObservedActivity: () => f.observed,
hasReplayUnsafeActivity: () => f.replayUnsafe,
onNoOutputTimeout: (t) => {
d.reason = "no-output-timeout";
e.onNoOutputTimeout?.(t);
s.abort(t);
},
onOverallTimeout: () => {
d.reason = "overall-timeout";
s.abort(/* @__PURE__ */ new Error("CLI plugin runtime exceeded its execution timeout."));
}
});
e.setOnActiveLoopbackAskUserDeadlineChange?.(() => p?.reset());
e.setOnCompactionActiveChange?.(() => reportOutstandingWork());
p.reset();
if (e.liveSession && (e.forceNewSession || Boolean(e.context.preparedBackend.backend.resumeArgs?.length) && !e.useResume)) {
if (e.liveSession.requiredGeneration) throw new Error("The required CLI live session cannot be replaced by a fresh process.");
await restartCliLiveSession(e.context, c);
}
l();
if (e.liveSession) {
await ensureCliLiveSessionMemory(e.context, c);
l();
v = createCliLiveSessionCapability({
context: e.context,
argv: [i, ...a],
argv0: e.executionArgv0,
env: e.env,
...e.liveSession,
captureKey: e.mcpCapture?.captureKey,
beginCapture: (t) => e.mcpCapture?.beginCapture(t, assertCaptureCurrent),
abortSignal: c,
claimResources: e.context.preparedBackend.claimLiveSessionResources
});
} else e.mcpCapture?.beginCapture(e.mcpCapture.captureKey, assertCaptureCurrent);
const o = e.context.cliHistoryWriter;
await o?.assertReadable();
l();
const u = await runWithAgentToolSourceExecutionScope(l, async () => {
l();
const u = e.execute({
command: i,
argv0: e.executionArgv0,
args: a,
cwd: n,
env: e.env,
prompt: e.prompt,
...e.promptContext ? { promptContext: e.promptContext } : {},
...isHostGeneratedInputProvenance(e.context.params.inputProvenance) ? { promptOrigin: "host" } : {},
modelId: e.context.normalizedModel,
systemPrompt: stripSystemPromptCacheBoundary(e.context.systemPrompt).trim(),
...e.sessionId ? { sessionId: e.sessionId } : {},
useResume: e.useResume,
abortSignal: c,
assertCurrent: AsyncLocalStorage.bind(l),
...o?.bindsNativeLogin ? { assertPrivateInputCurrent: AsyncLocalStorage.bind(() => o.checkNativeLoginBoundary(o.replaysHistory)) } : {},
timeoutMs: t.timeoutMs,
...t.executionMode ? { executionMode: t.executionMode } : {},
...t.cliToolAvailability ? { toolAvailability: t.cliToolAvailability } : {},
...v ? { liveSession: v } : {},
registerTurnStatus: AsyncLocalStorage.bind((e) => {
l();
const t = bindCliTurnStatus(e, () => h === t && assertionSucceeds(l));
h = t;
}),
registerTurnInterrupt: AsyncLocalStorage.bind((t) => {
l();
e.mcpCapture?.registerTurnInterrupt?.({ interrupt: async (e) => {
l();
try {
await t.interrupt(e);
} catch (e) {
s.abort(e);
throw e;
}
} });
}),
...g ? { registerMessageInjection: AsyncLocalStorage.bind((e) => {
m = e;
}) } : {},
requestToolPermission: AsyncLocalStorage.bind(r),
requestUserInput: AsyncLocalStorage.bind(createPluginUserInputHandler({
context: e.context,
abortSignal: c,
onPendingInput: updatePendingApproval
}))
})[Symbol.asyncIterator]();
_ = u;
return {
iterator: u,
next: await waitForIteratorValue(u, c)
};
});
let b = u.next;
for (;;) {
if (b.done) break;
if (!isRecord(b.value)) {
f.replayUnsafe = true;
throw new Error("CLI plugin runtime emitted an invalid structured stream event.");
}
if (b.value.type === "result" && b.value.openclaw_interim_result !== true) y = y === "error" || b.value.is_error === true || typeof b.value.subtype === "string" && b.value.subtype.startsWith("error_") ? "error" : "success";
if (b.value.type === "system" && b.value.subtype === "background_tasks_changed" && Array.isArray(b.value.tasks)) {
f.background = b.value.tasks.filter(isRecord).length;
reportOutstandingWork();
}
e.consumeStdout(`${JSON.stringify(b.value)}\n`);
f.observed = true;
if (!(b.value.type === "system" && b.value.subtype === "init") && b.value.type !== "command_lifecycle") f.replayUnsafe = true;
p.noteOutput();
b = await waitForIteratorValue(u.iterator, c);
}
if (y === "none") throw new Error("CLI plugin runtime completed without a terminal result.");
await e.mcpCapture?.waitForTurnInterrupt?.();
} catch (n) {
if (t.abortSignal?.aborted || d.reason === "manual-cancel") {
const n = isSignalTimeoutReason(t.abortSignal?.reason) ? "timeout" : "aborted";
if (!e.onInterrupted?.(n)) throw createCliAbortError();
d.reason = "manual-cancel";
}
if (d.reason === "exit" && y !== "error") {
if (e.liveSession?.requiredGeneration && isReplaySafeCliResumeControlOnly(e.useResume, f.replayUnsafe, Boolean(f.approvals || f.background || e.activeToolCount?.()))) try {
v?.current();
} catch (e) {
if (e instanceof FailoverError && e.reason === "session_expired") {
const { code: t, message: r, reason: i } = e;
throw createCliFailoverError(r, i, e, {
cause: n,
code: t
});
}
}
throw n;
}
} finally {
h = void 0;
e.mcpCapture?.registerTurnInterrupt?.(void 0);
p?.dispose();
e.setOnActiveLoopbackAskUserDeadlineChange?.(void 0);
e.setOnCompactionActiveChange?.(void 0);
e.onOutstandingWorkChange?.(false);
s.abort(/* @__PURE__ */ new Error("CLI plugin runtime turn is no longer active."));
g?.();
await closePluginIterator(_);
}
return {
reason: d.reason,
exitCode: d.reason === "exit" ? 0 : null,
exitSignal: null,
durationMs: Date.now() - o,
stdout: "",
stderr: "",
timedOut: d.reason === "overall-timeout" || d.reason === "no-output-timeout",
noOutputTimedOut: d.reason === "no-output-timeout"
};
}
//#endregion
//#region src/agents/cli-runner/reliability.ts
function resolveCliNoOutputTimeoutMs(e) {
if (e.expectedQuiet) return e.timeoutMs;
const t = e.runTimeoutOverrideMs !== void 0 && Number.isFinite(e.runTimeoutOverrideMs) && e.runTimeoutOverrideMs > 0;
const n = e.useResume ? e.backend.reliability?.watchdog?.resume : e.backend.reliability?.watchdog?.fresh;
const r = e.useResume && !n && (e.trigger === "cron" || t) ? CLI_FRESH_WATCHDOG_DEFAULTS : e.useResume ? CLI_RESUME_WATCHDOG_DEFAULTS : CLI_FRESH_WATCHDOG_DEFAULTS;
const i = asFiniteNumber(n?.noOutputTimeoutRatio);
const a = i === void 0 ? r.noOutputTimeoutRatio : Math.max(.05, Math.min(.95, i));
const o = resolveOptionalIntegerOption(n?.minMs, { min: 1e3 }) ?? r.minMs;
const s = resolveOptionalIntegerOption(n?.maxMs, { min: 1e3 }) ?? r.maxMs;
const c = Math.max(CLI_WATCHDOG_MIN_TIMEOUT_MS, e.timeoutMs - 1e3);
const l = Math.floor(e.timeoutMs * a);
return Math.min(Math.min(Math.max(o, s), Math.max(Math.min(o, s), l)), c);
}
function resolveCliRunTimeoutOverrideMs(e) {
if (e.runTimeoutOverrideMs !== void 0) return e.runTimeoutOverrideMs;
const t = e.config?.agents?.defaults?.timeoutSeconds;
return e.lane !== AGENT_LANE_SUBAGENT && t !== void 0 && t > 0 ? e.timeoutMs : void 0;
}
function buildCliSupervisorScopeKey(e) {
const t = normalizeLowercaseStringOrEmpty(path.basename(e.backend.command ?? ""));
const n = normalizeLowercaseStringOrEmpty(e.backendId);
const r = e.cliSessionId?.trim();
if (!r) return;
return `cli:${n}:${t}:${r}`;
}
//#endregion
//#region src/agents/cli-runner/execute-process.ts
const CLI_RUNNER_OUTPUT_PARSE_BYTES = 1048576;
const CLI_RUNNER_OUTPUT_TAIL_BYTES = 65536;
async function executeCliProcess(e) {
const t = e.context;
const n = t.params;
const r = {
provider: n.provider,
model: t.modelId,
sessionId: n.sessionId,
lane: n.lane
};
const i = {
...r,
runId: n.runId,
classifyErrorCode: t.backendResolved.classifyErrorCode
};
const refuseStream = (t, n, i) => createCliStreamRefusalError(t, r, n && {
...n,
finalPromptText: e.prompt
}, i);
const a = e.useResume && n.cliSessionResumeAt ? e.backend.resumeAtArg : void 0;
const o = e.useResume ? n.cliSessionResumeAt : void 0;
const createOutputFailoverError = (e) => {
if (!e.errorText) return;
const t = resolveCliResumeAtError(e.errorText, { resumeCheckpointId: o }, r);
if (t) return t;
const n = formatCliOutputError(e, {
runId: i.runId,
sessionId: i.sessionId
});
const a = e.terminalFailure?.reason;
const s = a ? a === "synthetic_no_response" ? "format" : "unknown" : classifyFailoverReason(n, { provider: i.provider }) ?? "unknown";
const c = a ? `cli_${a}` : s === "context_overflow" ? "cli_context_overflow" : i.classifyErrorCode?.(e.errorText);
return new FailoverError(n, {
reason: s,
provider: i.provider,
model: i.model,
sessionId: i.sessionId,
lane: i.lane,
status: resolveFailoverStatus(s),
code: c,
rawError: e.errorText
});
};
const s = e.outputMode === "jsonl";
const c = n.sourceReplyDeliveryMode === "message_tool_only" || getAgentRunContext(n.runId)?.sessionEventDelivery === false ? false : void 0;
const l = n.sessionKey ? resolveEventSessionKeyForPolicy(n.sessionKey, resolveEventSessionRoutingPolicy({
cfg: n.config,
sessionKey: n.sessionKey,
channel: n.messageProvider,
accountId: n.agentAccountId
})) : void 0;
const u = l ? resolveSessionAgentId({
config: n.config ?? {},
sessionKey: l,
agentId: n.agentId
}) : void 0;
let d;
if (l && u && e.events.emitLiveEvents) {
try {
d = await captureSessionEventTargetForHost(u, l, {
producerPolicy: t.sessionEventSourcePolicy,
assertCaptureCurrent: e.assertCurrent
});
} catch (e) {
cliBackendLog.warn(`CLI watchdog follow-up unavailable: ${formatErrorMessage(e)}`);
}
e.assertCurrent();
}
const f = s ? createCliJsonlStreamingParser({
backend: e.backend,
providerId: t.backendResolved.id,
parseJsonlEvent: t.backendResolved.parseJsonlEvent,
parseJsonlLifecycleEvent: t.backendResolved.parseJsonlLifecycleEvent,
onAssistantDelta: e.events.emitCliAssistantDelta,
onCompletedReply: e.events.emitCliCompletedReply,
onThinkingDelta: e.events.emitCliThinkingDelta,
onThinkingProgress: e.events.emitCliThinkingProgress,
onCompaction: e.events.emitCliCompaction,
onToolUseStart: e.events.emitParsedToolUseStart,
onToolInputDelta: e.events.emitCliToolInputDelta,
onToolResult: e.events.emitParsedToolResult,
onDisplayToolUseStart: e.events.emitCliDisplayToolUseStart,
onDisplayToolResult: e.events.emitCliDisplayToolResult,
onCommentaryText: e.events.emitLiveEvents && n.emitCommentaryText ? e.events.emitCliCommentaryText : void 0,
onSessionId: e.observeForkSuccessor,
onNativeTools: t.preparedBackend.mcpClientGrantCapture?.captureNativeTools,
onAssistantMessage: e.diagnostics?.observeAssistantMessage,
onUsage: e.diagnostics?.observeUsage,
onAttributedSubagentProgress: (t) => {
if (!e.events.isActiveForegroundAgentTool(t)) return;
O?.observeAttributedAgentProgress(t);
}
}) : null;
let p = "";
const m = createCapturedOutputBuffers();
let h = 0;
const g = crypto.createHash("sha256");
let _ = "";
const v = createCapturedOutputBuffers();
let y = 0;
const b = crypto.createHash("sha256");
const x = createModelCallStreamProgressReporter({
recordProgress: () => O?.observeOutput(false) ?? false,
target: {
runId: n.runId,
...n.sessionKey ? { sessionKey: n.sessionKey } : {},
...n.sessionId ? { sessionId: n.sessionId } : {}
}
});
let stopForParserRefusal;
const consumeStdout = (t) => {
const n = Buffer.byteLength(t);
e.diagnostics?.observeCliOutput(t, "stdout", n);
if (n > 0) {
if (e.events.activeParsedToolCount() === 0) x();
else O?.observeOutput(false);
}
h += n;
g.update(t);
p = truncateUtf8Suffix(`${p}${t}`, CLI_RUNNER_OUTPUT_TAIL_BYTES);
if (t && m.truncatedBytes === 0) appendCapturedOutput(m, t, CLI_RUNNER_OUTPUT_PARSE_BYTES, "head");
f?.push(t);
if (f?.getErrorText()) stopForParserRefusal?.();
};
const consumeStderr = (t) => {
e.diagnostics?.observeCliOutput(t, "stderr");
y += Buffer.byteLength(t);
b.update(t);
_ = truncateUtf8Suffix(`${_}${t}`, CLI_RUNNER_OUTPUT_TAIL_BYTES);
if (t && v.truncatedBytes === 0) appendCapturedOutput(v, t, CLI_RUNNER_OUTPUT_PARSE_BYTES, "head");
};
n.onExecutionPhase?.({
phase: "process_spawned",
provider: n.provider,
model: t.modelId,
backend: t.backendResolved.id
});
let S;
let C;
let w = false;
const T = {};
let E;
let D;
n.assertCurrent?.();
e.diagnostics?.observeRequestPayload(e.stdin ?? e.argsPrompt ?? "");
e.assertCurrent();
n.diagnosticOwner?.watchdogAttempt?.setExecutionDeadline(Date.now() + n.timeoutMs + EMBEDDED_RUN_LANE_TIMEOUT_GRACE_MS);
const O = n.diagnosticOwner ? beginDiagnosticBackendActivity({
owner: n.diagnosticOwner,
noOutputTimeoutMs: e.noOutputTimeoutMs,
assertCurrent: e.assertCurrent
}) : void 0;
try {
if (e.nodePlacement) {
const n = await executeNodeClaudeRun({
context: t,
nodePlacement: e.nodePlacement,
executionArgs: e.resolveExecutionArgs(),
stdinPayload: e.stdin ?? "",
...e.nodeSystemPrompt !== void 0 ? { nodeSystemPrompt: e.nodeSystemPrompt } : {},
...e.nodeEnv ? { nodeEnv: e.nodeEnv } : {},
...e.nodeClearEnv ? { nodeClearEnv: e.nodeClearEnv } : {},
noOutputTimeoutMs: e.noOutputTimeoutMs,
consumeStdout,
consumeStderr
});
D = n.result;
C = n.nodeRunAbortSignal;
w = n.nodeRunTruncated;
} else if (t.executionTarget.kind === "plugin") D = await executePluginOwnedProcess({
context: t,
execute: t.executionTarget.execute,
executionCommand: e.executionCommand,
executionArgv0: e.executionArgv0,
executionArgs: [...e.executionLeadingArgv, ...e.resolveExecutionArgs()],
env: e.env,
prompt: e.prompt,
...e.promptContext ? { promptContext: e.promptContext } : {},
useResume: e.useResume,
forceNewSession: e.cliSessionIdToUse === void 0 && t.openClawHistoryPrompt !== void 0,
sessionId: e.resolvedSessionId,
noOutputTimeoutMs: e.noOutputTimeoutMs,
consumeStdout: (e) => {
consumeStdout(e);
const t = f?.getErrorText();
if (t) throw refuseStream(t, f?.getOutput());
},
onOutstandingWorkChange: O?.setOutstandingWork,
activeToolCount: e.events.activeParsedToolCount,
compactionActive: e.events.hasActiveCompaction,
setOnCompactionActiveChange: e.events.setOnCompactionActiveChange,
getActiveLoopbackAskUserDeadline: e.toolTracking.getActiveLoopbackAskUserDeadline,
setOnActiveLoopbackAskUserDeadlineChange: e.toolTracking.setOnActiveLoopbackAskUserDeadlineChange,
onNoOutputTimeout: (e) => {
T.error = e;
},
onInterrupted: (e) => {
f?.finish();
const t = f?.getOutput();
if (t?.partialOutputRejected && t.errorText) throw refuseStream(t.errorText, t, { code: CLI_PARTIAL_OUTPUT_REJECTED_ERROR_CODE });
if (!t?.text.trim() || t.errorText || t.terminalFailure) return false;
E = { reason: e };
return true;
},
mcpCapture: {
captureKey: e.initialGatewayCaptureKey,
beginCapture: e.toolTracking.beginGatewayCapture,
registerTurnInterrupt: e.toolTracking.registerTurnInterrupt,
waitForTurnInterrupt: e.toolTracking.waitForTurnInterrupt,
onInputSubmitted: e.toolTracking.onInputSubmitted
},
...e.useManagedClaudeLiveSession ? { liveSession: { requiredGeneration: e.cliSessionIdToUse ? t.requiredClaudeLiveSessionGeneration : void 0 } } : {}
}).catch((t) => {
n.assertCurrent?.();
if (n.abortSignal?.aborted || e.events.hasObservedCliActivity()) throw t;
throw resolveCliResumeAtError(t, { resumeAtArg: a }, r) ?? t;
});
else {
const r = getProcessSupervisor();
const i = buildCliSupervisorScopeKey({
backend: e.backend,
backendId: t.backendResolved.id,
cliSessionId: e.useResume ? e.resolvedSessionId : void 0
});
if (n.abortSignal?.aborted) throw createCliAbortError();
let a = false;
const assertProcessCurrent = () => {
e.assertCurrent();
if (a) throw new Error("CLI process authority is no longer active");
};
const abortManagedRun = () => {
a = true;
r.cancel(n.runId, "manual-cancel");
};
n.abortSignal?.addEventListener("abort", abortManagedRun, { once: true });
try {
e.toolTracking.beginGatewayCapture(e.initialGatewayCaptureKey, assertProcessCurrent);
const o = await runWithAgentToolSourceExecutionScope(e.assertCurrent, () => withChildProcessOperation("agent.cli", () => r.spawn({
assertCurrent: e.assertCurrent,
prepareSpawn: e.argsPrompt ? t.cliHistoryWriter?.assertReadable : void 0,
prepareInput: e.stdin ? t.cliHistoryWriter?.assertReadable : void 0,
runId: n.runId,
scopeKey: i,
replaceExistingScope: Boolean(e.useResume && i),
mode: "child",
argv: [e.executionCommand, ...e.executionLeadingArgv],
resolveArgs: e.resolveExecutionArgs,
argv0: e.executionArgv0,
timeoutMs: n.timeoutMs,
noOutputTimeoutMs: e.noOutputTimeoutMs,
onCancel: () => {
a = true;
},
cwd: t.cwd ?? t.workspaceDir,
env: e.env,
input: e.stdin ?? "",
secretInput: n.nativeAuthOnly ? void 0 : t.preparedBackend.secretInput,
captureOutput: false,
onStdout: consumeStdout,
onStderr: consumeStderr
})));
S = o.pid;
stopForParserRefusal = () => {
a = true;
o.cancel("manual-cancel");
};
if (f?.getErrorText()) stopForParserRefusal();
const s = attachCliReplyBackend(n, stopForParserRefusal);
try {
D = await o.wait();
a ||= D.reason !== "exit";
} finally {
s?.();
}
} finally {
n.abortSignal?.removeEventListener("abort", abortManagedRun);
}
}
} finally {
O?.close();
}
if ((n.abortSignal?.aborted || C?.aborted) && D.reason === "manual-cancel" && !E) throw createCliAbortError();
e.options?.onPhase?.("resolve");
f?.finish();
const k = f?.getErrorText();
if (k) throw refuseStream(k, f?.getOutput());
if (w && D.exitCode === 0 && !D.timedOut && !f?.hasTerminalResult()) throw createCliFailoverError("paired node truncated the Claude CLI stream before the terminal result; refusing to accept partial output.", "format", r);
let A;
const readStdout = () => A ??= Buffer.concat(m.chunks, m.bytes).toString("utf8").trim();
const j = p.trim();
const M = _.trim();
const N = {
backendId: t.backendResolved.id,
processReason: D.reason,
exitCode: D.exitCode,
exitSignal: D.exitSignal,
durationMs: D.durationMs,
stdoutBytes: h,
stdoutHash: g.digest("hex").slice(0, 12),
stderrBytes: y,
stderrHash: b.digest("hex").slice(0, 12),
useResume: e.useResume
};
for (const t of ["info", "debug"]) if (t === "info" ? e.logOutputText : shouldLogVerbose()) {
for (const [e, n] of [["stdout", j], ["stderr", M]]) if (n) cliBackendLog[t](`cli ${e}:\n${n}`);
}
const P = f?.getOutput();
const parseOutput = () => parseCliOutput({
raw: readStdout(),
backend: e.backend,
providerId: t.backendResolved.id,
outputMode: e.outputMode,
fallbackSessionId: e.resolvedSessionId
});
const F = P ?? (e.outputMode === "json" && m.truncatedBytes === 0 ? parseOutput() : null);
if (F?.terminalFailure) {
const e = createOutputFailoverError(F);
if (e) throw e;
}
if (!E && (D.exitCode !== 0 || D.reason !== "exit")) {
e.options?.onPhase?.("send");
if (D.reason === "no-output-timeout" || D.noOutputTimedOut) {
const i = Math.round(e.noOutputTimeoutMs / 1e3);
cliBackendLog.warn(`cli watchdog timeout: provider=${n.provider} model=${t.modelId} session=${e.resolvedSessionId ?? n.sessionId} noOutputTimeoutMs=${e.noOutputTimeoutMs} pid=${S ?? "node"}`);
const a = e.events.hasObservedCliActivity();
const o = T.error ? { error: T.error } : resolveCliNoOutputTimeoutDecision({
context: r,
timeoutMs: e.noOutputTimeoutMs,
quietDurationMs: e.noOutputTimeoutMs,
cliTimeout: {
mode: "no-output",
timeoutSeconds: i,
observedActivity: a,
activeToolCount: e.events.activeParsedToolCount(),
backgroundTaskCount: 0,
compactionActive: e.events.hasActiveCompaction()
},
hasOutputText: Boolean(j || M),
useResume: e.useResume,
hasReplayUnsafeActivity: a
});
const s = o.error.code === "cli_no_output_timeout" && Boolean(e.cliSessionIdToUse) && Boolean(e.resolvedSessionId) && Boolean(t.openClawHistoryPrompt) && Boolean(n.sessionKey) && n.timeoutMs - (performance.now() - t.startedMonotonicMs) > 0;
if (n.sessionKey && e.events.emitLiveEvents && !s) {
const e = [
`CLI agent (${n.provider}) produced no output for ${i}s and was terminated.`,
"It may have been waiting for interactive input or an approval prompt.",
"Check CLI permission settings and OpenClaw approval prompts."
].join(" ");
if (l && u && d) try {
enqueueSessionEventForHost(e, {
agentId: u,
sessionKey: l,
source: "exec",
expectedTarget: d,
deliver: c
}).settled.then((e) => {
if (e.status === "failed") cliBackendLog.warn(`CLI watchdog follow-up failed: ${e.error}`);
});
} catch (e) {
cliBackendLog.warn(`CLI watchdog follow-up rejected: ${formatErrorMessage(e)}`);
}
}
throw o.error;
}
if (D.reason === "overall-timeout") {
const t = Math.round(n.timeoutMs / 1e3);
throw createCliTimeoutError(r, {
mode: "overall",
timeoutSeconds: t,
observedActivity: e.events.hasObservedCliActivity(),
activeToolCount: e.events.activeParsedToolCount(),
backgroundTaskCount: 0
}, "cli_overall_timeout");
}
const i = D.reason === "exit" && !e.events.hasObservedCliActivity();
const s = Buffer.concat(v.chunks, v.bytes).toString("utf8").trim();
throw createCliExitFailoverError({
context: r,
classifyErrorCode: t.backendResolved.classifyErrorCode,
candidates: [
s,
readStdout(),
M,
j
],
retryEmptyFailure: i,
resumeAtArg: i ? a : void 0,
resumeCheckpointId: o
});
}
if (m.truncatedBytes > 0 && !P) throw createCliFailoverError(`CLI stdout exceeded ${CLI_RUNNER_OUTPUT_PARSE_BYTES} bytes; refusing to parse truncated output.`, "format", r);
if (n.controlOperation === "compact") {
const n = t.backendResolved.manualCompaction;
if (!n) throw new Error(`CLI backend ${t.backendResolved.id} does not support manual compaction`);
const i = n.validateOutput(readStdout());
if (!i.ok) throw createCliFailoverError(i.reason, "unknown", r);
return {
text: "",
rawText: "",
diagnostics: { process: N },
finalPromptText: e.prompt
};
}
const I = F ?? parseOutput();
const L = createOutputFailoverError(I);
if (L) throw L;
const R = I.text;
cliBackendLog.info(`cli turn: provider=${n.provider} model=${t.modelId} durationMs=${Date.now() - e.cliTurnStartedAt} ${formatCliBackendOutputDigest(R)}`);
return {
...transformCliResultText(I, t.backendResolved.textTransforms?.output),
...E ? { terminalInterruption: E } : {},
diagnostics: {
...I.diagnostics,
process: N
},
finalPromptText: e.prompt
};
}
//#endregion
//#region src/agents/cli-runner/execute-ask-user-deadline.ts
function createAskUserDeadlineTracking(e, t) {
const n = /* @__PURE__ */ new WeakMap();
let r;
let i;
const selectDeadline = () => {
if (t()) return;
let r = Number.POSITIVE_INFINITY;
for (const { loopbackCall: t, loopbackAmbiguous: i } of e.values()) {
if (!t || i || t.ambiguous) continue;
r = Math.min(r, n.get(t) ?? Number.POSITIVE_INFINITY);
}
return Number.isFinite(r) ? r : void 0;
};
const refresh = () => {
const e = selectDeadline();
if (e === i) return;
i = e;
r?.();
};
const clear = (e) => {
n.delete(e);
refresh();
};
const update = (e, t, r) => {
n.delete(e);
if (t === "ask_user") try {
n.set(e, Date.now() + resolveQuestionTimeoutMs(r.timeoutSeconds));
} catch {}
refresh();
};
return {
clear,
update,
refresh,
get: () => i,
setOnChange: (e) => {
r = e;
}
};
}
//#endregion
//#region src/agents/cli-runner/execute-messaging.ts
const CLI_MESSAGING_EVIDENCE_MAX_CALLS = 64;
function extractCliMessagingTarget(e, t, n) {
const r = stripOpenClawMcpToolPrefix(t);
const i = e.params.messageChannel ?? e.params.messageProvider;
const a = typeof n.provider === "string" && n.provider.trim().length > 0 || typeof n.channel === "string" && n.channel.trim().length > 0;
const o = r === "message" && i && !a ? {
...n,
provider: i
} : n;
if (!isMessagingToolTargetEvidenceAction(r, o)) return;
return extractMessagingToolSend(r, o, {
config: e.params.config,
currentChannelId: e.params.currentChannelId,
currentThreadId: e.params.currentThreadTs,
currentMessageId: e.params.currentMessageId
});
}
function buildMessagingToolSendEvidenceKey(e) {
return sha256Hex(JSON.stringify([
e.tool,
e.provider,
e.accountId,
e.to,
e.threadId,
e.threadImplicit,
e.threadSuppressed,
e.text,
e.mediaUrls
]));
}
function extractCliMessagingContent(e, t) {
const n = [
"message",
"SendMessage",
"content",
"text",
"caption"
].map((t) => e[t]).find((e) => typeof e === "string" && e.trim().length > 0);
const r = [...collectMessagingMediaUrlsFromRecord(e), ...collectMessagingMediaUrlsFromToolResult(t)].filter((e, t, n) => n.indexOf(e) === t);
return {
...n ? { text: n } : {},
...r.length > 0 ? { mediaUrls: r } : {}
};
}
function appendUniqueCliMessagingEvidence(e, t) {
for (const n of t) {
if (!n || e.has(n)) continue;
if (e.size >= 64) for (const t of e) {
e.delete(t);
break;
}
e.add(n);
}
}
//#endregion
//#region src/agents/cli-runner/execute-yield-turn.ts
/** Own yield interruption and delivered-reply state for each accepted native input. */
function createCliYieldTurnEnd() {
let e = false;
let t = false;
let n = false;
let r;
let i = false;
let a = false;
let o;
const requestYieldInterrupt = () => {
if (!e && !n || !a || !r || o) return;
const t = r;
o = Promise.resolve().then(() => t.interrupt("yield"));
o.catch(() => {});
};
const shouldSuppressAssistantOutput = () => (e || n) && i;
return {
markYielded() {
e = true;
},
markDelivered(e) {
t ||= e;
},
observe(e, r) {
if (r.outcome === "completed" && t && isResumingAlreadyPendingSessionsYieldResult(e, r.result)) n = true;
},
onToolResult(t, r) {
if ((e || n) && !r && stripOpenClawMcpToolPrefix(t) === "sessions_yield") {
a = true;
requestYieldInterrupt();
}
},
register(e) {
r = e;
i ||= e !== void 0;
requestYieldInterrupt();
},
async wait() {
await o;
},
beginInput() {
t = false;
n = false;
},
yielded: () => e,
suppressesAssistantOutput: shouldSuppressAssistantOutput
};
}
//#endregion
//#region src/agents/cli-runner/execute-tool-tracking.ts
const CLI_LOOPBACK_CORRELATION_MAX_CALLS = 64;
const CLI_MCP_DELIVERY_DRAIN_GRACE_MS = 5e3;
function createCliToolTracking(e) {
let t;
let n;
const r = createCliYieldTurnEnd();
const i = r.suppressesAssistantOutput;
let a = false;
let o = false;
let s;
let c = 0;
let l = 0;
const u = /* @__PURE__ */ new Set();
const d = /* @__PURE__ */ new Map();
const f = [];
const p = /* @__PURE__ */ new Map();
let m = false;
const h = createAskUserDeadlineTracking(p, () => m);
const g = /* @__PURE__ */ new Set();
const _ = /* @__PURE__ */ new Set();
const v = /* @__PURE__ */ new Map();
const y = [];
const b = /* @__PURE__ */ new Set();
let x = false;
let S = false;
const C = [];
const matchesCliLoopbackCall = (e, t, n) => stripOpenClawMcpToolPrefix(e) === n.toolName && isDeepStrictEqual(t, n.args);
const markCliLoopbackCallsAmbiguous = (e, t = Array.from(p.entries()).filter(([, t]) => t.loopbackCall !== void 0 && e.includes(t.loopbackCall))) => {
const n = /* @__PURE__ */ new Set();
for (const t of e) if (t.ambiguityGroup) n.add(t.ambiguityGroup);
for (const [, e] of t) if (e.ambiguityGroup) n.add(e.ambiguityGroup);
const r = n.values().next().value ?? /* @__PURE__ */ new Set();
for (const e of n) {
if (e === r) continue;
for (const t of e) {
t.ambiguityGroup = r;
r.add(t);
}
for (const t of p.values()) if (t.ambiguityGroup === e) t.ambiguityGroup = r;
e.clear();
}
for (const t of e) {
t.ambiguous = true;
t.ambiguityGroup = r;
r.add(t);
}
for (const [, e] of t) {
e.loopbackAmbiguous = true;
e.ambiguityGroup = r;
}
h.refresh();
};
const matchingActiveCliTools = (e) => Array.from(p.entries()).filter(([, t]) => matchesCliLoopbackCall(t.toolName, t.args, e));
const markCliLoopbackSignatureAmbiguous = (e) => {
const t = f.filter((t) => matchesCliLoopbackCall(e.toolName, e.args, t.admitted));
markCliLoopbackCallsAmbiguous(t, matchingActiveCliTools(e));
};
const retainCliLoopbackCall = (e) => {
if (f.length >= CLI_LOOPBACK_CORRELATION_MAX_CALLS) {
m = true;
for (const e of p.values()) if (e.loopbackCall || e.toolName.startsWith("mcp__")) e.loopbackAmbiguous = true;
f.length = 0;
h.refresh();
return;
}
const t = {
admitted: e,
current: e,
ambiguous: false
};
f.push(t);
return t;
};
const bindCliLoopbackCall = (e, t, n) => {
e.boundToolCallId = t;
n.loopbackCall = e;
n.loopbackAmbiguous ||= e.ambiguous;
if (e.ambiguityGroup) n.ambiguityGroup = e.ambiguityGroup;
h.refresh();
};
const removeCliLoopbackCall = (e) => {
if (!e) return;
const t = f.indexOf(e);
if (t >= 0) f.splice(t, 1);
};
const retireCliLoopbackCorrelation = (e) => {
removeCliLoopbackCall(e?.loopbackCall);
const t = e?.ambiguityGroup;
if (!t) return;
for (const e of p.values()) if (e.ambiguityGroup === t) return;
for (const e of t) if (e.boundToolCallId === void 0 && f.includes(e)) return;
for (const e of t) removeCliLoopbackCall(e);
t.clear();
};
const commitMessagingToolResult = (t) => {
const n = readEmbeddedMessageDeliveryFact(readToolResultDetails(t.result)?.messageDelivery);
if (!(n ? n.status === "settled" && (!t.isError || n.partialDelivery) : isDeliveredMessagingToolResult(t))) return;
a = true;
if (n?.sourceReplyDelivered === true) s = true;
const i = t.args;
const c = isMessagingToolSendAction(t.toolName, i);
const l = c ? extractMessagingToolSourceReplyPayload(t.result) : void 0;
const u = c ? extractCliMessagingContent(i, t.result) : {};
const d = t.target && extractMessagingToolSendResult(t.target, t.result);
const f = isDeliveredMessageToolOnlySourceReplyResult({
sourceReplyDeliveryMode: e.params.sourceReplyDeliveryMode,
toolName: t.toolName,
args: t.args,
result: t.result,
isError: t.isError,
allowExplicitSourceRoute: isDeliveredMessagingToolSendToCurrentSource({
send: d,
config: e.params.config,
currentProvider: e.params.messageChannel ?? e.params.messageProvider,
currentAccountId: e.params.agentAccountId,
currentChannelId: e.params.currentChannelId,
currentThreadId: e.params.currentThreadTs,
sessionKey: e.params.sessionKey,
deliveredPayload: t.result
}),
deliveryConfirmed: true
});
const p = f || l ? resolveMessageToolSourceReplyFinal(i, e.params.messageToolFinalByDefault) : void 0;
if (!f && l && p && e.params.inputProvenance?.kind !== "inter_session") s = true;
if (c) {
appendUniqueCliMessagingEvidence(g, u.text ? [u.text] : []);
appendUniqueCliMessagingEvidence(_, u.mediaUrls ?? []);
}
if (f || l && p) {
o ||= f;
r.markDelivered(f);
const e = c ? l : extractMessagingToolSourceReplyPayload(t.result);
if (e) {
if (y.length >= 64) y.shift();
y.push({
...e,
...p !== void 0 ? { sourceReplyFinal: p } : {}
});
}
}
if (!d) return;
const m = {
...d,
...u,
...p !== void 0 ? { sourceReplyFinal: p } : {}
};
const h = buildMessagingToolSendEvidenceKey(m);
if (v.has(h)) return;
if (v.size >= 64) for (const e of v.keys()) {
v.delete(e);
break;
}
v.set(h, m);
};
const isPreparedInternalSourceReply = async (t) => {
if (e.params.sourceReplyDeliveryMode !== "message_tool_only" || stripOpenClawMcpToolPrefix(t.toolName) !== "message" || t.args.action !== "send" || !e.params.config) return false;
return await shouldUseInternalSourceReplySink({
cfg: e.params.config,
action: "send",
sessionKey: e.params.sessionKey,
sourceReplyDeliveryMode: e.params.sourceReplyDeliveryMode,
toolContext: {
currentChannelProvider: e.params.messageChannel ?? e.params.messageProvider,
currentChannelId: e.params.currentChannelId,
currentThreadTs: e.params.currentThreadTs,
currentMessageId: e.params.currentMessageId,
replyToMode: e.params.replyToMode
}
}, t.args);
};
const beginGatewayCapture = (i, a) => {
if (!i || t === i) return;
if (t) throw new Error("CLI MCP capture key changed during an active attempt");
e.preparedBackend.mcpClientGrantCapture?.activate(i, a);
t = i;
const isPotentialDelivery = (e) => isMessagingTool(stripOpenClawMcpToolPrefix(e));
const isPreparedDelivery = (e, t) => t.dryRun !== true && isMessagingToolDeliveryAction(stripOpenClawMcpToolPrefix(e), t);
beginMcpLoopbackToolCallCapture({
captureKey: i,
onYield: (e, t) => {
r.markYielded();
n = t;
},
onRequestStart: () => {
c += 1;
},
onRequestClassified: () => {
c = Math.max(0, c - 1);
},
onToolCallStart: (e) => {
const t = retainCliLoopbackCall(e);
const n = matchingActiveCliTools(e);
let r = t && n.length === 1 && !n[0]?.[1].loopbackCall && !n[0]?.[1].loopbackAmbiguous ? n[0] : void 0;
if (t && r) bindCliLoopbackCall(t, r[0], r[1]);
else if (t && n.length > 0) {
markCliLoopbackSignatureAmbiguous(e);
r = n.find(([, e]) => !e.loopbackCall);
if (r) bindCliLoopbackCall(t, r[0], r[1]);
}
if (isPotentialDelivery(e.toolName)) l += 1;
return r?.[0];
},
onToolCallUpdate: ({ previous: e, current: t }) => {
const n = f.filter((t) => matchesCliLoopbackCall(e.toolName, e.args, t.current));
const r = n.at(0);
if (n.length === 1 && r && !r.ambiguous) {
r.current = t;
const e = stripOpenClawMcpToolPrefix(t.toolName);
h.update(r, e, t.args);
} else if (n.length > 0) markCliLoopbackCallsAmbiguous(n);
u.delete(e);
const i = isPotentialDelivery(e.toolName);
const a = isPreparedDelivery(t.toolName, t.args);
if (i !== a) l = Math.max(0, l + (a ? 1 : -1));
if (a) u.add(t);
},
onToolCallFinish: (e, { prepared: t }) => {
if (t ? isPreparedDelivery(e.toolName, e.args) : isPotentialDelivery(e.toolName)) l = Math.max(0, l - 1);
u.delete(e);
},
onToolCallResult: (t) => {
const n = t.outcome === "blocked" ? {
outcome: t.outcome,
deniedReason: t.deniedReason
} : { outcome: t.outcome };
const i = t.correlationId ? f.find((e) => e.boundToolCallId === t.correlationId) : void 0;
const a = i ? [i] : f.filter((e) => matchesCliLoopbackCall(t.toolName, t.args, e.current));
const o = stripOpenClawMcpToolPrefix(t.toolName);
if (a.length === 1 && a[0]) {
const e = a[0];
e.outcome = n;
e.browserTab = !e.ambiguous && o === "browser" && t.outcome === "completed" ? readToolResultDetails(t.result)?.browserTab : void 0;
} else if (a.length > 1) markCliLoopbackCallsAmbiguous(a);
const s = o === "sessions_spawn" && t.outcome === "completed" ? normalizeAcceptedSessionSpawnResult(t.result) : null;
if (s && C.length < CLI_LOOPBACK_CORRELATION_MAX_CALLS) C.push(s);
r.observe(o, t);
if (isMessagingToolDeliveryAction(o, t.args)) commitMessagingToolResult({
toolName: o,
target: extractCliMessagingTarget(e, o, t.args),
args: t.args,
result: "result" in t ? t.result : void 0,
isError: t.outcome !== "completed"
});
else if (t.outcome === "completed") {
const e = extractToolResultMediaArtifact(t.result);
const n = e ? filterToolResultMediaUrls(o, e.mediaUrls, t.result) : [];
appendUniqueCliMessagingEvidence(b, n);
if (n.length > 0) {
x ||= e?.audioAsVoice === true;
S ||= e?.trustedLocalMedia === true;
}
}
}
});
};
const handleCliToolUseStart = (n) => {
if (n.kind !== "server_tool_use") {
const e = {
toolName: n.name,
args: n.args,
loopbackAmbiguous: m && n.name.startsWith("mcp__")
};
p.set(n.toolCallId, e);
const t = {
toolName: stripOpenClawMcpToolPrefix(n.name),
args: n.args
};
const r = f.filter((e) => e.boundToolCallId === void 0 && matchesCliLoopbackCall(n.name, n.args, e.admitted));
const i = matchingActiveCliTools(t).some(([e, t]) => e !== n.toolCallId && (t.loopbackCall !== void 0 || t.loopbackAmbiguous));
const a = r[0];
if (i || r.length > 1 || a?.ambiguous) markCliLoopbackSignatureAmbiguous(t);
if (a) bindCliLoopbackCall(a, n.toolCallId, e);
}
const r = stripOpenClawMcpToolPrefix(n.name);
if (n.kind === "server_tool_use" || t || n.args.dryRun === true || !isMessagingToolDeliveryAction(r, n.args)) return;
if (d.size >= 64) {
const e = d.keys().next().value;
if (e !== void 0) {
d.delete(e);
a = true;
}
}
d.set(n.toolCallId, {
toolName: r,
args: n.args,
target: extractCliMessagingTarget(e, r, n.args)
});
};
const handleCliToolResult = (e) => {
const t = p.get(e.toolCallId);
r.onToolResult(t?.toolName ?? e.name, e.isError);
if (t?.loopbackCall) h.clear(t.loopbackCall);
p.delete(e.toolCallId);
retireCliLoopbackCorrelation(t);
const n = d.get(e.toolCallId);
if (n) {
d.delete(e.toolCallId);
commitMessagingToolResult({
...n,
result: e.result,
isError: e.isError
});
}
return t?.loopbackAmbiguous ? void 0 : t?.loopbackCall?.current.args;
};
const resolveCliLoopbackTerminalOutcome = (e) => {
const t = p.get(e);
if (t?.loopbackAmbiguous) return { outcome: "unknown" };
return t?.loopbackCall?.outcome;
};
const finishDeliveryTracking = async (n) => {
try {
if (!t && d.size > 0) {
const e = Array.from(d.values());
if ((await Promise.all(e.map(isPreparedInternalSourceReply))).some((e) => !e)) {
a = true;
n.recordRunError(/* @__PURE__ */ new Error("CLI JSONL message tool call remained unresolved after exit"));
} else n.recordRunError(/* @__PURE__ */ new Error("CLI JSONL source reply call remained unresolved after exit"));
}
if (!t) return;
if (await waitForMcpLoopbackToolCallCaptureIdle(t, { timeoutMs: CLI_MCP_DELIVERY_DRAIN_GRACE_MS })) return;
if (n.useManagedClaudeLiveSession) await closeCliLiveSession(e, "mcp-capture-rotation");
const r = (await Promise.all(Array.from(u).map(isPreparedInternalSourceReply))).filter(Boolean).length;
if (c > 0 || l > r) {
a = true;
n.recordRunError(/* @__PURE__ */ new Error("CLI message tool call remained in flight after exit"));
} else if (l > 0) n.recordRunError(/* @__PURE__ */ new Error("CLI source reply call remained in flight after exit"));
} catch (e) {
if (d.size > 0 || c > 0 || l > 0) a = true;
n.recordRunError(e);
}
};
const finalizeCapture = (n) => {
try {
n();
} finally {
if (t) try {
e.preparedBackend.mcpClientGrantCapture?.deactivate(t);
} finally {
clearMcpLoopbackToolCallCapture(t);
}
}
};
const evidence = () => ({
didSendViaMessagingTool: a,
didDeliverSourceReplyViaMessageTool: o,
sourceReplyDelivered: s,
messagingToolSentTexts: [...g],
messagingToolSentMediaUrls: [..._],
messagingToolSentTargets: [...v.values()],
messagingToolSourceReplyPayloads: y,
toolMediaUrls: [...b],
toolAudioAsVoice: x,
toolTrustedLocalMedia: S,
acceptedSessionSpawns: C
});
return {
beginGatewayCapture,
registerTurnInterrupt: r.register.bind(r),
waitForTurnInterrupt: r.wait.bind(r),
onInputSubmitted: r.beginInput.bind(r),
shouldSuppressAssistantOutput: i,
getActiveLoopbackAskUserDeadline: h.get,
setOnActiveLoopbackAskUserDeadlineChange: h.setOnChange,
handleCliToolUseStart,
handleCliToolResult,
resolveCliLoopbackTerminalOutcome,
resolveCliLoopbackBrowserTab(e) {
const t = p.get(e);
const n = t?.loopbackCall;
return t?.loopbackAmbiguous || n?.ambiguous ? void 0 : n?.browserTab;
},
finishDeliveryTracking,
finalizeCapture,
withExecutionEvidence(e) {
const t = evidence();
t.messagingToolSourceReplyPayloads = t.messagingToolSourceReplyPayloads.slice();
return {
...e,
...i() ? {
text: "",
rawText: "",
rawFinalText: "",
textParts: void 0,
interimNativeReplies: void 0
} : {},
...r.yielded() ? { yielded: true } : {},
...n ? { yieldAcknowledgment: n } : {},
...projectCliMessagingDeliveryEvidence(t),
...t.toolMediaUrls.length > 0 ? { toolMediaUrls: t.toolMediaUrls } : {},
...t.toolAudioAsVoice ? { toolAudioAsVoice: true } : {},
...t.toolTrustedLocalMedia ? { toolTrustedLocalMedia: true } : {},
...t.acceptedSessionSpawns.length > 0 ? { acceptedSessionSpawns: t.acceptedSessionSpawns.slice() } : {}
};
},
attachDeliveryEvidence(e) {
return attachCliMessagingDeliveryEvidence(e, evidence());
}
};
}
//#endregion
//#region src/agents/cli-runner/model-call-diagnostics.ts
/** Trusted turn-level model-call diagnostics for the Claude Code CLI runtime. */
const MAX_CAPTURED_CONTENT_BYTES = 131072;
const FALLBACK_RESPONSE_RESERVE_BYTES = 16384;
const MAX_CAPTURED_OUTPUT_MESSAGES = 200;
const MAX_CAPTURED_OUTPUT_BLOCKS = 200;
const TRUNCATED_CONTENT_SUFFIX = "...(truncated)";
const MAX_CAPTURED_OUTPUT_STRUCTURE_BYTES = Buffer.byteLength(JSON.stringify(Array.from({ length: MAX_CAPTURED_OUTPUT_MESSAGES }, () => ({
role: "assistant",
content: [{
type: "tool_call",
name: "",
id: ""
}],
stopReason: ""
}))), "utf8");
function serializedStringContentBytes(e) {
return Buffer.byteLength(JSON.stringify(e), "utf8") - 2;
}
const TRUNCATED_CONTENT_SUFFIX_BYTES = serializedStringContentBytes(TRUNCATED_CONTENT_SUFFIX);
function truncateSerializedStringSafe(e, t) {
if (t <= 0) return "";
if (serializedStringContentBytes(e) <= t) return e;
let n = 0;
let r = Math.min(e.length, t);
let i = "";
while (n <= r) {
const a = Math.floor((n + r) / 2);
const o = truncateUtf16Safe(e, a);
if (serializedStringContentBytes(o) <= t) {
i = o;
n = a + 1;
} else r = a - 1;
}
return i;
}
function releaseFallbackReserve(e) {
e.remainingBytes += e.fallbackReserveBytes;
e.remainingItems += e.fallbackReserveItems;
e.fallbackReserveBytes = 0;
e.fallbackReserveItems = 0;
}
function captureTextWithinBudget(e, t) {
if (t.remainingBytes <= 0) {
t.truncated = true;
return;
}
const n = serializedStringContentBytes(e);
if (n <= t.remainingBytes) {
t.remainingBytes -= n;
return e;
}
const r = truncateSerializedStringSafe(TRUNCATED_CONTENT_SUFFIX, t.remainingBytes);
const i = `${truncateSerializedStringSafe(e, Math.max(0, t.remainingBytes - serializedStringContentBytes(r)))}${r}`;
t.remainingBytes -= serializedStringContentBytes(i);
t.truncated = true;
return i;
}
function captureBoundedText(e) {
return captureTextWithinBudget(e, {
remainingBytes: MAX_CAPTURED_CONTENT_BYTES,
remainingItems: 1,
fallbackReserveBytes: 0,
fallbackReserveItems: 0,
truncated: false
}) ?? "";
}
function parseAssistantContentBlock(e) {
if (!isRecord(e)) return;
if (e.type === "text" && typeof e.text === "string") return {
type: "text",
text: e.text
};
if (e.type === "thinking" && typeof e.thinking === "string") return {
type: "thinking",
thinking: e.thinking
};
if (isClaudeToolUseBlockType(e.type) && typeof e.name === "string") return {
type: "tool_call",
name: e.name,
...typeof e.id === "string" ? { id: e.id } : {}
};
}
function assistantMessageHasText(e) {
return e.content.some((e) => e?.type === "text" && e.text.length > 0);
}
function parseClaudeAssistantMessage(e) {
if (!isRecord(e) || e.content === "") return;
const t = e.content;
const n = Array.isArray(t) ? t : void 0;
return {
content: typeof t === "string" ? [{
type: "text",
text: t
}] : n?.slice(0, MAX_CAPTURED_OUTPUT_BLOCKS).map(parseAssistantContentBlock) ?? [],
truncated: (n?.length ?? 0) > MAX_CAPTURED_OUTPUT_BLOCKS,
...typeof e.stop_reason === "string" ? { stopReason: e.stop_reason } : {}
};
}
function normalizeClaudeAssistantMessage(e, t) {
const n = [];
t.truncated ||= e.truncated;
for (const [r, i] of e.content.entries()) {
let a;
if (i?.type === "text" && i.text.length > 0) {
releaseFallbackReserve(t);
const e = captureTextWithinBudget(i.text, t);
a = e === void 0 ? void 0 : {
type: "text",
text: e
};
} else if (i?.type === "thinking") {
const e = captureTextWithinBudget(i.thinking, t);
a = e === void 0 ? void 0 : {
type: "thinking",
thinking: e
};
} else if (i?.type === "tool_call") {
const e = captureTextWithinBudget(i.name, t);
if (e !== void 0) {
const n = i.id !== void 0 ? captureTextWithinBudget(i.id, t) : void 0;
a = {
type: "tool_call",
name: e,
...n !== void 0 ? { id: n } : {}
};
}
}
if (a) {
if (t.remainingItems > 0) {
n.push(a);
t.remainingItems -= 1;
} else t.truncated = true;
}
if (t.remainingBytes <= 0 || t.remainingItems <= 0) {
if (e.content.slice(r + 1).some((e) => e !== void 0)) t.truncated = true;
break;
}
}
if (n.length === 0) return;
const r = e.stopReason !== void 0 ? captureTextWithinBudget(e.stopReason, t) : void 0;
return {
role: "assistant",
content: n,
...r !== void 0 ? { stopReason: r } : {}
};
}
function appendOutputTruncationMarker(e) {
const t = {
type: "text",
text: TRUNCATED_CONTENT_SUFFIX
};
if (e.length < MAX_CAPTURED_OUTPUT_MESSAGES) {
e.push({
role: "assistant",
content: [t]
});
return;
}
const n = e.length - 1;
const r = e[n];
e[n] = {
...r,
content: [...r.content, t]
};
}
function privateData(e) {
if (!e.modelContent && !e.errorMessage) return;
return {
...e.errorMessage ? { errorMessage: e.errorMessage } : {},
...e.modelContent ? { modelContent: e.modelContent } : {}
};
}
function usageField(e) {
return e ? { usage: e } : {};
}
/** Creates one exactly-once Claude CLI model-call lifecycle for a prepared turn. */
function createClaudeCliModelCallDiagnostics(e) {
if (e.context.backendResolved.id !== "claude-cli" || !areDiagnosticsEnabledForProcess() || !hasInternalDiagnosticEventListeners()) return;
const t = resolveDiagnosticModelContentCapturePolicy(e.context.params.config ?? e.context.contextEngineConfig);
const n = e.context.contextWindowInfo;
const r = freezeDiagnosticTraceContext(createDiagnosticTraceContextFromActiveScope());
const i = {
runId: e.context.params.runId,
...e.context.params.agentId ? { agentId: e.context.params.agentId } : {},
callId: `${e.context.params.runId}:claude-cli:${crypto.randomUUID()}`,
...e.context.params.sessionKey ? { sessionKey: e.context.params.sessionKey } : {},
sessionId: e.context.params.sessionId,
provider: e.context.backendResolved.modelProvider ?? e.context.params.modelProvider ?? "anthropic",
model: e.context.normalizedModel,
api: "claude-code",
transport: e.transport,
observationUnit: "turn",
...n ? {
contextTokenBudget: n.tokens,
contextWindowSource: n.source,
...n.referenceTokens ? { contextWindowReferenceTokens: n.referenceTokens } : {}
} : {},
promptStats: {
inputMessagesCount: 1,
inputMessagesChars: e.prompt.length,
...e.systemPrompt ? { systemPromptChars: e.systemPrompt.length } : {},
totalChars: e.prompt.length + (e.systemPrompt?.length ?? 0)
},
trace: r
};
const a = [];
const o = {
remainingBytes: MAX_CAPTURED_CONTENT_BYTES - MAX_CAPTURED_OUTPUT_STRUCTURE_BYTES - TRUNCATED_CONTENT_SUFFIX_BYTES - FALLBACK_RESPONSE_RESERVE_BYTES,
remainingItems: 198,
fallbackReserveBytes: FALLBACK_RESPONSE_RESERVE_BYTES,
fallbackReserveItems: 1,
truncated: false
};
let s = false;
let c = false;
let l = 0;
let u;
let d = 0;
let f;
let p;
let m;
const baseModelContent = () => {
if (!t.anyModelContent) return;
const n = {
...t.inputMessages ? { inputMessages: [{
role: "user",
content: [{
type: "text",
text: captureBoundedText(e.prompt)
}]
}] } : {},
...t.systemPrompt && e.systemPrompt ? { systemPrompt: captureBoundedText(e.systemPrompt) } : {}
};
return Object.keys(n).length > 0 ? n : void 0;
};
const outputMessages = (e) => {
const t = a.slice();
const n = e?.rawText ?? e?.text;
if (!t.some(assistantMessageHasText) && n && t.length < MAX_CAPTURED_OUTPUT_MESSAGES) {
const e = normalizeClaudeAssistantMessage({
content: [{
type: "text",
text: n
}],
truncated: false
}, o);
if (e) t.push(e);
}
if (o.truncated) appendOutputTruncationMarker(t);
return t;
};
const completedModelContent = (e) => {
const n = baseModelContent();
if (!t.outputMessages) return n;
return {
...n,
outputMessages: outputMessages(e)
};
};
const sizeTimingFields = () => ({
...u !== void 0 ? { requestPayloadBytes: u } : {},
...d > 0 ? { responseStreamBytes: d } : {},
...f !== void 0 ? { timeToFirstByteMs: Math.max(0, f - l) } : {}
});
return {
emitStarted: () => {
if (s) return;
s = true;
l = Date.now();
emitTrustedDiagnosticEventWithPrivateData({
type: "model.call.started",
...i
}, privateData({ modelContent: baseModelContent() }));
},
observeRequestPayload: (e) => {
u = Buffer.byteLength(e, "utf8");
},
observeCliOutput: (e, t, n) => {
if (!e) return;
f ??= Date.now();
if (t === "stdout") d += n ?? Buffer.byteLength(e, "utf8");
},
observeAssistantMessage: (e) => {
if (!t.outputMessages) return;
if (a.length >= 199 || (o.remainingBytes <= 0 || o.remainingItems <= 0) && o.fallbackReserveItems <= 0) {
o.truncated = true;
return;
}
const n = parseClaudeAssistantMessage(e);
if ((o.remainingBytes <= 0 || o.remainingItems <= 0) && !(o.fallbackReserveItems > 0 && n && assistantMessageHasText(n))) {
o.truncated = true;
return;
}
const r = n && normalizeClaudeAssistantMessage(n, o);
if (r) a.push(r);
},
observeUsage: (e, t) => {
p = e;
if (t) m = e;
},
emitCompleted: (e) => {
if (!s || c) return;
c = true;
emitTrustedDiagnosticEventWithPrivateData({
type: "model.call.completed",
...i,
durationMs: Math.max(0, Date.now() - l),
...sizeTimingFields(),
...usageField(e.diagnosticUsage ?? m ?? e.usage ?? p)
}, privateData({ modelContent: completedModelContent(e) }));
},
emitError: (t) => {
if (!s || c) return;
c = true;
const n = isFailoverError(t) && t.reason === "timeout" ? "timeout" : diagnosticErrorFailureKind(t) ?? (e.context.params.abortSignal?.aborted ? "aborted" : void 0);
emitTrustedDiagnosticEventWithPrivateData({
type: "model.call.error",
...i,
durationMs: Math.max(0, Date.now() - l),
errorCategory: (isFailoverError(t) ? t.reason : void 0) ?? n ?? diagnosticErrorCategory(t),
...n ? { failureKind: n } : {},
...sizeTimingFields(),
...usageField(m ?? p)
}, privateData({
modelContent: completedModelContent(),
errorMessage: diagnosticErrorMessage(t)
}));
}
};
}
//#endregion
//#region src/agents/cli-runner/execute.ts
function exactToolAvailabilityError(e) {
if (!e.isolatedCompletion) return new Error(e.message);
return Object.assign(new Error(e.message), {
name: "IsolatedCompletionRuntimeError",
code: e.code
});
}
async function executePreparedCliRun(e, t, n) {
const r = e.cliHistoryWriter?.replaysHistory === true;
const i = e.cliHistoryWriter ? {
...e,
params: {
...e.params,
assertCurrent: e.cliHistoryWriter.assertCurrent
}
} : e;
const a = i.params;
const o = createCliRunCurrentAssertion(a);
o();
const s = i.preparedBackend.backend;
const c = i.executionTarget;
const l = installationTargetEnv(getInstallationTarget());
if (l && c.kind === "node") throw new Error(LOCAL_INSTALLATION_TARGET_UNSUPPORTED);
const u = c.kind === "node" ? c.placement : null;
const d = c.kind === "plugin";
const { sessionId: f, isNew: p } = resolveSessionIdToSend({
backend: s,
cliSessionId: t
});
const m = Boolean(t && f && s.resumeArgs && s.resumeArgs.length > 0);
const h = i.reusableCliSession.mode === "reuse-with-drift";
const g = resolveSystemPromptUsage({
backend: s,
isNewSession: p || h,
systemPrompt: i.systemPrompt
});
const _ = g && (!m || s.systemPromptWhen === "always" || h);
let v;
const y = u && _ ? g : void 0;
const b = t ? a.prompt : i.openClawHistoryPrompt ?? a.prompt;
const x = m && t === resolveCliSessionId(i.reusableCliSession) && !a.forkCliSessionOnResume ? i.resumeContext : void 0;
const S = [i.contextEngineSystemPromptAddition, x].filter(Boolean).join("\n\n");
const C = d ? b : composeCliPromptContext(b, { prependContext: S });
const w = [
d ? i.contextEngineSystemPromptAddition : void 0,
i.promptContext?.prependContext,
d ? x : void 0
].filter(Boolean).join("\n\n");
let T = a.controlOperation !== void 0 ? C : applyPluginTextReplacements(C, i.backendResolved.textTransforms?.input);
const E = w || i.promptContext?.appendContext ? {
...w ? { prependContext: applyPluginTextReplacements(w, i.backendResolved.textTransforms?.input) } : {},
...i.promptContext?.appendContext ? { appendContext: applyPluginTextReplacements(i.promptContext.appendContext, i.backendResolved.textTransforms?.input) } : {}
} : void 0;
if (u && ((a.images?.length ?? 0) > 0 || (a.mediaImageLayout ? a.mediaImageLayout.slots.length > 0 : hasHydratableMediaImages(a.media)) || (a.imagePrompt ? detectImageReferences(a.imagePrompt).length > 0 : false))) throw new Error("paired-node Claude CLI sessions do not support attachments or images");
const D = isClaudeCliBackendId(i.backendResolved.id) ? a.userTurnTranscriptRecorder?.getAdmissionReceipt()?.entryId : void 0;
const O = u ? {
prompt: T,
imagePaths: []
} : await prepareCliPromptImagePayload({
backend: s,
prompt: T,
imagePrompt: a.imagePrompt,
workspaceDir: i.workspaceDir,
localRoots: getAgentScopedMediaLocalRoots(a.config ?? {}, a.agentId),
images: a.images,
imageOrder: a.imageOrder,
mediaImageLayout: a.mediaImageLayout,
media: a.media,
preparedImages: n?.promptImages,
...D ? { imageTurnKey: hashCliImageTurnEntryId(D) } : {}
});
T = O.prompt;
const k = a.controlOperation === "compact" && i.backendResolved.manualCompaction ? {
...s,
input: i.backendResolved.manualCompaction.input
} : s;
const { argsPrompt: A, stdin: j } = resolvePromptInput({
backend: k,
prompt: T
});
const M = m ? s.resumeArgs ?? s.args ?? [] : s.args ?? [];
const N = m ? M.map((e) => e.replaceAll("{sessionId}", f ?? "")) : M;
const P = !u && i.claudeSkillsPlugin.args.length > 0 ? [...N, ...i.claudeSkillsPlugin.args] : N;
const F = buildCliLiveOwnerKey(a);
const I = resolveCliRunQueueKey({
backendId: i.backendResolved.id,
liveSession: s.liveSession,
serialize: s.serialize,
runId: a.runId,
workspaceDir: i.workspaceDir,
cliSessionId: m ? f : void 0,
ownerKey: F
});
const L = d && acceptsCliLiveSession(i) && !a.onSuccessfulAuthBinding;
const R = composeCliPromptContext(T, E);
n?.onPromptPrepared?.(R);
const z = createClaudeCliModelCallDiagnostics({
context: i,
prompt: R,
systemPrompt: g ?? void 0,
transport: u ? "paired-node-cli" : L ? "stdio-live" : "stdio"
});
let B;
let V;
let H;
let U = false;
let W = false;
let G;
const observeForkSuccessor = (e) => {
if (W || !U || !f || e === f) return;
W = true;
G = a.persistCliSessionForkSuccessor?.(e);
G?.catch(() => void 0);
};
const finishForkSuccessorPersistence = async () => {
try {
await G;
} catch (e) {
W = false;
throw e;
}
};
const executeAttempt = async () => {
o();
await i.preparedBackend.beforeExecution?.();
o();
if (!u && !d && _) v = await writeCliSystemPromptFile({
backend: s,
systemPrompt: g
});
const e = Date.now();
const c = a.skillsSnapshot && !a.controlOperation ? applySkillEnvOverridesFromSnapshot({
snapshot: a.skillsSnapshot,
config: a.config
}) : void 0;
let p;
let b;
let x;
let S = false;
const recordRunError = (e) => {
if (!S) {
S = true;
x = e;
}
};
const C = createCliToolTracking(i);
const w = createCliEventHandlers({
context: i,
toolTracking: C,
getRunState: () => ({
failed: S,
error: x
})
});
try {
const c = isTruthyEnvValue(process.env[CLI_BACKEND_LOG_OUTPUT_ENV]);
const _ = m ? s.resumeOutput ?? s.output : s.output;
const x = u || !i.mcpDeliveryCapture ? void 0 : crypto.randomUUID();
const S = u ? {
env: {},
cleanup: void 0
} : await prepareCliBundleMcpCaptureAttempt({
preparedBackend: i.preparedBackend,
captureKey: x
});
p = S.cleanup;
const D = i.preparedBackend.env ?? {};
const { env: k, selectedClaudeClearEnv: M } = resolveCliChildEnv(i.preparedBackend, a, {
...S.env,
...l
});
const N = Object.entries(D).filter(([e]) => NODE_CLAUDE_FORWARD_ENV_KEYS.has(e));
const F = u ? {
...Object.fromEntries(N),
...a.nativeAuthOnly ? {} : resolveNodeClaudeAuthEnv(i)
} : void 0;
const I = u ? [...NODE_CLAUDE_FORWARD_ENV_KEYS].filter((e) => s.clearEnv?.includes(e)) : [];
const B = [.../* @__PURE__ */ new Set([...M ?? [], ...I])];
i.cliHistoryWriter?.bindExecutionEnv(k, r);
let V = s.command;
let H;
let U = [];
i.runtimeOwnerFingerprint = void 0;
i.runtimeArtifactFingerprint = void 0;
const W = a.cliToolAvailability ? i.backendResolved.runtimeArtifact?.exactToolAvailabilityVersionPolicy : void 0;
if (W && u) throw exactToolAvailabilityError({
code: "unsupported",
isolatedCompletion: a.isolatedCompletion === true,
message: `CLI backend ${i.backendResolved.id} cannot verify its exact tool-availability runtime on a paired node`
});
if ((a.onSuccessfulAuthBinding || W) && !u) {
const e = await resolveCliExecutableIdentity({
command: s.command,
cwd: i.cwd ?? i.workspaceDir,
env: k,
...i.backendResolved.runtimeArtifact ? { runtimeArtifact: i.backendResolved.runtimeArtifact } : {}
});
if (!e) throw exactToolAvailabilityError({
code: "runtime-unavailable",
isolatedCompletion: a.isolatedCompletion === true && W !== void 0,
message: `CLI backend ${i.backendResolved.id} executable cannot be bound to one durable absolute owner`
});
if (W) {
const t = e.runtimeArtifact;
const n = t?.kind === "package-tree" ? t.packageVersion : void 0;
const r = n ? parse$1(n) : null;
const o = r?.prerelease[0];
const s = r?.prerelease.length === 0 ? W.stableMinimum : typeof o === "string" ? W.prereleaseMinimums?.[o] : void 0;
const c = n && s ? compareValidSemver(n, s) : null;
if (c === null || c < 0) throw exactToolAvailabilityError({
code: "unsupported",
isolatedCompletion: a.isolatedCompletion === true,
message: `CLI backend ${i.backendResolved.id} requires a supported package version for exact per-run tool availability${s ? ` (requires >=${s}` : " (unsupported release line"}${n ? `; found ${n})` : ")"}`
});
}
V = e.invocation.command;
H = e.invocation.argv0;
U = e.invocation.leadingArgv;
i.runtimeArtifactFingerprint = fingerprintCliRuntimeArtifact({
provider: a.provider,
backendId: i.backendResolved.id,
executableIdentity: e
});
if (a.onSuccessfulAuthBinding && !i.authBindingFingerprint) i.runtimeOwnerFingerprint = await resolveCliRuntimeOwnerFingerprint({
provider: a.provider,
config: a.config ?? i.contextEngineConfig,
...i.agentDir ? { agentDir: i.agentDir } : {},
agentId: a.agentId,
runtimeOwnerId: i.backendResolved.id,
...i.effectiveAuthProfileId ? { authProfileId: i.effectiveAuthProfileId } : {},
...i.authBindingSkipsLocalCredential ? { skipLocalCredential: true } : {},
runtimeArtifactFingerprint: i.runtimeArtifactFingerprint
});
}
const resolveExecutionArgs = () => {
o();
const e = i.backendResolved.resolveExecutionArgs?.({
config: a.config,
agentId: a.agentId,
workspaceDir: i.workspaceDir,
provider: a.provider,
modelId: i.modelId,
authProfileId: i.effectiveAuthProfileId,
thinkingLevel: a.thinkLevel === "ultra" ? i.providerThinkingLevel : a.thinkLevel,
fastMode: a.fastMode === void 0 ? void 0 : resolveFastModeForElapsed({
mode: a.fastMode,
startedAtMs: a.fastModeStartedAtMs ?? i.started,
fastAutoOnSeconds: a.fastModeAutoOnSeconds
}).enabled,
executionMode: a.executionMode ?? "agent",
toolAvailability: a.cliToolAvailability && u ? {
native: a.cliToolAvailability.native,
openClaw: []
} : a.cliToolAvailability,
hostOwnedTools: i.hostOwnedTools,
useResume: m,
...a.controlOperation === "compact" ? { controlOperation: "compact" } : {},
baseArgs: P
});
if (a.cliToolAvailability && i.backendResolved.toolAvailabilityEnforcement === "execution-args" && !e) throw new Error(`CLI backend ${i.backendResolved.id} did not enforce exact per-run tool availability`);
const t = u ? stripGatewayLocalClaudeArgs(e ?? P) : e ?? P;
return buildCliArgs({
backend: u ? {
...s,
systemPromptArg: void 0,
systemPromptFileArg: void 0
} : s,
baseArgs: Array.from(t),
modelId: i.normalizedModel,
sessionId: f,
systemPrompt: u || d ? void 0 : g,
systemPromptFilePath: v?.filePath,
imagePaths: O.imagePaths,
promptArg: A,
useResume: m,
forkResume: a.forkCliSessionOnResume,
resumeAt: a.cliSessionResumeAt,
sendSystemPromptOnResume: h
});
};
const G = resolveCliRunTimeoutOverrideMs(a);
const K = resolveCliNoOutputTimeoutMs({
backend: s,
timeoutMs: a.timeoutMs,
expectedQuiet: a.controlOperation === "compact",
runTimeoutOverrideMs: G,
useResume: m,
trigger: a.trigger
});
if (i.trajectoryRecorder) recordCliTrajectoryEvent(i.trajectoryRecorder, "prompt.submitted", {
prompt: R,
...g ? { systemPrompt: g } : {},
imagesCount: O.imagePaths?.length ?? 0
});
b = await executeCliProcess({
context: i,
assertCurrent: o,
backend: s,
events: w,
toolTracking: C,
diagnostics: z,
nodePlacement: u,
nodeSystemPrompt: y,
nodeEnv: F && Object.keys(F).length > 0 ? F : void 0,
nodeClearEnv: B.length > 0 ? B : void 0,
useManagedClaudeLiveSession: L,
initialGatewayCaptureKey: x,
useResume: m,
cliSessionIdToUse: t,
resolvedSessionId: f,
executionCommand: V,
executionArgv0: H,
executionLeadingArgv: U,
resolveExecutionArgs,
env: k,
prompt: T,
...E ? { promptContext: E } : {},
argsPrompt: A,
stdin: j,
noOutputTimeoutMs: K,
outputMode: _,
logOutputText: c,
cliTurnStartedAt: e,
observeForkSuccessor,
options: n
});
} catch (e) {
recordRunError(e);
} finally {
await i.cliHistoryWriter?.settleNativeLogin();
await C.finishDeliveryTracking({
useManagedClaudeLiveSession: L,
recordRunError
});
C.finalizeCapture(w.finalizeParsedTools);
try {
await runCliCleanup(a, "cli-mcp-capture", async () => {
await p?.();
});
} catch (e) {
recordRunError(e);
}
try {
await runCliCleanup(a, "cli-skill-env", async () => {
c?.();
});
} catch (e) {
recordRunError(e);
}
}
if (S) {
const e = readCliStreamRefusalOutput(x);
if (e) {
const { acceptedSessionSpawns: t } = C.withExecutionEvidence(e);
recordCliStreamRefusalToolEffects(x, {
toolSummary: w.getToolSummary(),
...t ? { acceptedSessionSpawns: t } : {}
});
}
throw C.attachDeliveryEvidence(x);
}
if (!b) throw new Error("CLI run completed without output");
return C.withExecutionEvidence({
...b,
toolSummary: w.getToolSummary()
});
};
try {
B = await enqueueCommandInLane(`cli:${I}`, () => {
const runQueuedAttempt = async () => {
o();
if (a.lifecycleGeneration) assertAgentRunLifecycleGenerationCurrent(a.lifecycleGeneration);
z?.emitStarted();
if (a.controlOperation === "compact") await restartCliLiveSession(i);
if (a.forkCliSessionOnResume && m) {
if (!a.persistCliSessionForkSuccessor) throw new Error("CLI session fork successor persistence is unavailable");
U = await a.claimCliSessionFork?.() === true;
if (!U) throw new Error("CLI session fork marker is no longer available");
await restartCliLiveSession(i);
}
return await executeAttempt();
};
const e = i.pluginExecutionConsumer;
return e ? e.run(runQueuedAttempt) : runQueuedAttempt();
}, { abortSignal: a.abortSignal });
if (B.sessionId) observeForkSuccessor(B.sessionId);
await finishForkSuccessorPersistence();
if (U && !W) {
await a.restoreCliSessionFork?.();
U = false;
throw new Error("forked CLI session did not report a successor session id");
}
} catch (e) {
V = e;
z?.emitError(e);
let t = e;
try {
await finishForkSuccessorPersistence();
} catch (n) {
t = new AggregateError([e, n], "CLI turn failed and its fork successor could not be persisted", { cause: e });
}
if (U && !W) try {
await a.restoreCliSessionFork?.();
} catch (e) {
t = new AggregateError([t, e], formatErrorMessage(t), { cause: t });
}
throw t;
} finally {
try {
await runCliCleanup(a, "cli-outer-resource", async () => {
await v?.cleanup();
});
} catch (e) {
if (B?.didSendViaMessagingTool) cliBackendLog.warn(`CLI outer resource cleanup failed after confirmed message delivery: ${formatErrorMessage(e)}`);
else if (V !== void 0) cliBackendLog.warn(`CLI outer resource cleanup also failed after run error: ${formatErrorMessage(e)}`);
else H = toErrorObject(e, "CLI outer resource cleanup failed");
}
}
if (H) {
n?.onPhase?.("cleanup");
z?.emitError(H);
throw H;
}
z?.emitCompleted(B);
if (i.trajectoryRecorder) recordCliModelCompleted(i.trajectoryRecorder, B);
return B;
}
//#endregion
export { executePreparedCliRun as t };