openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,015 lines (1,014 loc) • 36.1 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { g as toAgentStoreSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as makeZeroUsageSnapshot } from "./usage-CHLnzpJG.mjs";
import { t as truncateUtf8Prefix } from "./utf8-truncate-BH7Ecfuh.mjs";
import { a as createNativeModelOwnedRuntimeModel } from "./defaults-BWyoTPqn.mjs";
import { _ as readAgentAssistantSource, n as bindAgentAssistantSource } from "./agent-events-BdfWYmot.mjs";
import { _ as readRuntimeContextMetadata, m as isRuntimeContextMessage, p as hasRuntimeContextMarker } from "./types-iq-cNLsd.mjs";
import { a as WORKER_PROTOCOL_MAX_INFERENCE_PAYLOAD_BYTES, t as WORKER_INFERENCE_MAX_CONTEXT_MESSAGES } from "./worker-inference-Ci_T9A9P.mjs";
import { p as resolveAssistantMessagePhase } from "./chat-message-content-DNUdbbJ8.mjs";
import { l as normalizeAgentRunAttemptTerminal, s as mergeAgentRunAttemptTerminal, u as projectAgentRunAttemptTerminal } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { g as wrapToolWithGatewayCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { o as setPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { i as markToolExecutionRefused } from "./tool-effect-receipt-BbbEwqBS.mjs";
import { a as copyAgentToolMetadata, x as bindBeforeToolCallMetadata } from "./agent-tool-metadata-nrQgRaqv.mjs";
import { u as projectRuntimeContextFragments } from "./internal-runtime-context-BEUlDNuI.mjs";
import { i as jsonUtf8BytesOrInfinity } from "./json-utf8-bytes-DNwtq2cu.mjs";
import { a as projectSessionEntryMessage } from "./session-BC1-SoD4.mjs";
import { u as appendTextDeltaToAssistantMessage } from "./agent-core-DiRTR2U_.mjs";
import "./src-DFw9QOgs.mjs";
import { y as WORKER_TRANSCRIPT_MAX_BATCH_MESSAGES } from "./worker-admission-1P4EM7n_.mjs";
import { n as recordModelFallbackStop } from "./model-fallback-stop-BN_k3Te_.mjs";
import { i as resolveRuntimeOsLabel } from "./os-summary-CMRUbVgk.mjs";
import { s as wrapToolWithBeforeToolCallHook } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { t as redactAgentDiagnosticPayload } from "./diagnostic-redaction-DVtKJp3X.mjs";
import { i as toWorkerTranscriptMessage, n as isWorkerTranscriptMessageFrameSafe, o as projectWorkerTextOrImageContent, t as WORKER_PROVIDER_REPLAY_LOCAL_RETRY_MESSAGE } from "./transcript-message-CX61ai-2.mjs";
import { t as ModelRegistry } from "./model-registry.core-DcVMaqxb.mjs";
import { t as AuthStorage } from "./auth-storage.core-C5ytUL3b.mjs";
import { s as hasModelFallbackStop } from "./failover-error-CbIiC30n.mjs";
import { h as listRunningSessions } from "./bash-process-registry-Dh1460VO.mjs";
import { t as createStreamingDirectiveAccumulator } from "./streaming-directives-C1RBdaQG.mjs";
import { t as parseReplyDirectives } from "./reply-directives-BMfUGuku.mjs";
import { i as setMcpCodeModeGuestResult } from "./mcp-content-CYbca1LN.mjs";
import { o as toToolDefinitions } from "./agent-tool-definition-adapter-CAIOgFtX.mjs";
import { a as buildRuntimeContextCustomMessage } from "./runtime-context-prompt-CRmsG0oC.mjs";
import { n as wrapToolWithAbortSignal } from "./agent-tools.abort-BN-GwRlX.mjs";
import { t as DefaultResourceLoader } from "./resource-loader-hGpx6p2H.mjs";
import { t as event_stream_exports } from "./event-stream-BvhxOtdO.mjs";
import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs";
import { t as SettingsManager } from "./settings-manager-Byjum9f5.mjs";
import { o as getShellConfig, r as detectRuntimeShell } from "./shell-utils-rrqUwXNm.mjs";
import { t as materializeSkillResources } from "./resources-CNBzJPid.mjs";
import { r as projectMemoryFlushTools } from "./agent-tools.memory-flush-t5TUoO5U.mjs";
import { r as buildUsageWithNoCost, t as buildAssistantMessage } from "./stream-message-shared-CBUzFwdv.mjs";
import { t as assertSettledTurnFinalizationResult } from "./settled-turn-finalization-result-DSvueaqd.mjs";
import { r as resolveSystemPromptRepoRoot } from "./system-prompt-params-B0WSdtCC.mjs";
import { s as disposeAllCodeModeRuns } from "./code-mode-state-CYIS_OXN.mjs";
import { t as createAgentHarnessToolSurfaceRuntimeCore } from "./tool-surface-bridge-BDxYoRUW.mjs";
import { C as classifyAssistantTurn, b as resolveSettledToolTerminalContinuation, n as readSubscriptionCompletionEvidence } from "./tool-terminal-outcome-I8TmHIh2.mjs";
import { t as guardSessionManager } from "./session-tool-result-guard-wrapper-z-jVIqGv.mjs";
import { i as completeSystemPromptRuntime } from "./system-prompt-runtime-3CG6CMve.mjs";
import { t as convertToLlm } from "./messages-C39ZvzzS.mjs";
import { r as createAgentSession } from "./tool-send-receipts-DPctyfdu.mjs";
import { t as getMachineDisplayName } from "./machine-name-Dw9TPjxw.mjs";
import { t as buildExecutionHostRuntimeFacts } from "./runtime-execution-facts-iyWPzOim.mjs";
import { t as subscribeEmbeddedAgentSession } from "./embedded-agent-subscribe-Dd0TB6BC.mjs";
import { a as createWorkerPlacementTools, i as WORKER_TOOL_CONFIG, r as createWorkerBrowserToolRuntime, t as createWorkerComputerTool } from "./computer-runtime-Lqt-zZOt.mjs";
import { n as windowWorkerReplayMessages } from "./replay-message-window-CjXgxm-q.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import os from "node:os";
import { getSupportedThinkingLevels } from "@openclaw/ai/internal/runtime";
//#region src/worker/embedded-agent-live.runtime.ts
const MAX_LIVE_EVENT_BYTES = 32768;
const MAX_LIVE_PREVIEW_BYTES = 4096;
const LIVE_PREVIEW_INTERVAL_MS = 75;
function truncateLiveText(e) {
if (e.length <= MAX_LIVE_PREVIEW_BYTES && Buffer.byteLength(e, "utf8") <= MAX_LIVE_PREVIEW_BYTES) return e;
const t = "…";
return `${truncateUtf8Prefix(e, MAX_LIVE_PREVIEW_BYTES - Buffer.byteLength(t, "utf8"))}${t}`;
}
function boundLiveValue(e) {
try {
const t = JSON.stringify(e);
if (t === void 0) return null;
if (Buffer.byteLength(t, "utf8") <= MAX_LIVE_PREVIEW_BYTES) return e;
return {
truncated: true,
preview: truncateLiveText(t)
};
} catch {
return {
truncated: true,
preview: "[unserializable live payload]"
};
}
}
function redactLiveText(e) {
const t = redactAgentDiagnosticPayload(e);
return truncateLiveText(typeof t === "string" ? t : "[unreadable diagnostic text]");
}
function boundLiveEvent(e) {
if (!((e.kind === "assistant" || e.kind === "thinking") && e.payload.text.length > MAX_LIVE_EVENT_BYTES) && jsonUtf8BytesOrInfinity(e) <= MAX_LIVE_EVENT_BYTES) return e;
let t;
if (e.kind === "assistant") {
const n = truncateLiveText(e.payload.text);
t = {
kind: "assistant",
payload: {
...e.payload,
text: n,
delta: n,
replace: true
}
};
} else if (e.kind === "thinking") t = {
kind: "thinking",
payload: {
...e.payload,
text: truncateLiveText(e.payload.text),
delta: truncateLiveText(e.payload.delta)
}
};
else if (e.kind === "tool") t = {
kind: "tool",
payload: {
...e.payload,
...e.payload.phase === "start" ? { args: boundLiveValue(e.payload.args) } : e.payload.phase === "update" ? { partialResult: boundLiveValue(e.payload.partialResult) } : { result: boundLiveValue(e.payload.result) }
}
};
else throw new Error(`worker live ${e.kind} event exceeds the protocol payload limit`);
if (jsonUtf8BytesOrInfinity(t) > MAX_LIVE_EVENT_BYTES) throw new Error(`worker live ${e.kind} event cannot fit the protocol payload limit`);
return t;
}
function readAssistantSnapshot(e) {
if (e.role !== "assistant") return { text: "" };
const t = e.content.flatMap((t) => t.type === "text" ? [{
text: t.text,
phase: resolveAssistantMessagePhase({
...e,
content: [t]
})
}] : []);
const n = t[0]?.phase;
const r = t.every((e) => e.phase === n) ? n : void 0;
return {
text: t.filter((e) => r === "commentary" || e.phase !== "commentary").map((e) => e.text).join(""),
phase: r
};
}
function readAssistantThinking(e) {
if (e.role !== "assistant") return "";
return e.content.filter((e) => e.type === "thinking").map((e) => e.thinking).join("");
}
function createWorkerLiveRuntime(e) {
let t = true;
const enqueueLive = (n) => {
if (t) t = e.enqueuePreview(boundLiveEvent(n));
};
const n = Date.now();
let r;
let i = { kind: "ok" };
let a = false;
const enqueueTerminal = (e) => {
i = mergeAgentRunAttemptTerminal(i, normalizeAgentRunAttemptTerminal({
aborted: e.aborted,
promptError: e.error
}));
const t = projectAgentRunAttemptTerminal(i);
const o = t.aborted ? "aborted" : t.failed ? "error" : e.stopReason;
r = {
kind: "lifecycle",
payload: {
phase: "finishing",
startedAt: n,
endedAt: Date.now(),
...o ? { stopReason: o } : {},
...t.aborted ? { aborted: true } : {},
...a ? { replayInvalid: true } : {},
...typeof t.promptError === "string" ? { error: redactLiveText(t.promptError) } : {}
}
};
};
let o = "";
let s;
let c;
let l = "";
const emitAssistantSnapshot = (e, t = false) => {
const { text: n, phase: r } = readAssistantSnapshot(e);
if (t && !n && e.role === "assistant" && e.stopReason === "aborted") return;
const i = createStreamingDirectiveAccumulator();
i.consume(n, { final: t });
const a = i.sourceText;
const c = t ? parseReplyDirectives(a).mediaUrls : void 0;
if (a === o && r === s && !c?.length) return;
const l = s === "commentary" && r !== "commentary" ? "" : o;
const u = !a.startsWith(l);
enqueueLive({
kind: "assistant",
payload: {
text: a,
delta: u ? a : a.slice(l.length),
...c?.length ? { mediaUrls: c } : {},
...u ? { replace: true } : {},
...r ? { phase: r } : {},
itemId: readAgentAssistantSource(e)?.itemId
}
});
o = a;
s = r;
};
const emitThinkingSnapshot = (e, t) => {
const n = readAssistantThinking(e);
if (n === l) return;
enqueueLive({
kind: "thinking",
payload: {
text: n,
delta: t ?? n,
itemId: readAgentAssistantSource(e)?.itemId
}
});
l = n;
};
let u;
let d;
let f = 0;
const flushPreview = () => {
const e = u;
const n = d;
u = void 0;
d = void 0;
if (!e || !t) return;
f = Date.now() + LIVE_PREVIEW_INTERVAL_MS;
if (n !== void 0) emitThinkingSnapshot(e, n);
else emitAssistantSnapshot(e);
};
const handleSessionEvent = (e) => {
const r = e.type === "message_update" ? e.assistantMessageEvent.type : void 0;
if (!(r === "text_delta" || r === "thinking_delta")) flushPreview();
if ((e.type === "message_start" || e.type === "message_update" || e.type === "message_end") && e.message.role === "assistant") {
if (e.type === "message_start" || !c) c = { itemId: randomUUID() };
bindAgentAssistantSource(e.message, c);
}
if (!t && e.type !== "agent_end") return;
if (e.type === "agent_start") {
enqueueLive({
kind: "lifecycle",
payload: {
phase: "start",
startedAt: n
}
});
return;
}
if (e.type === "message_start" && e.message.role === "assistant") {
o = "";
s = void 0;
l = "";
f = 0;
return;
}
if (e.type === "message_update") {
const t = e.assistantMessageEvent;
if (t.type === "text_delta" || t.type === "thinking_delta") {
const n = t.type === "thinking_delta";
if (u && d !== void 0 !== n) flushPreview();
u = e.message;
if (n) d = (d ?? "") + t.delta;
if (Date.now() >= f) flushPreview();
} else if (t.type === "text_end") emitAssistantSnapshot(e.message);
return;
}
if (e.type === "message_end" && e.message.role === "assistant") {
emitAssistantSnapshot(e.message, true);
emitThinkingSnapshot(e.message);
return;
}
if (e.type === "tool_execution_start" || e.type === "tool_execution_update" || e.type === "tool_execution_end") {
const t = {
name: e.toolName,
toolCallId: e.toolCallId
};
enqueueLive({
kind: "tool",
payload: {
...e.type === "tool_execution_start" ? {
phase: "start",
...t,
args: redactAgentDiagnosticPayload(e.args)
} : e.type === "tool_execution_update" ? {
phase: "update",
...t,
partialResult: redactAgentDiagnosticPayload(e.partialResult)
} : {
phase: "result",
...t,
isError: e.isError,
result: redactAgentDiagnosticPayload(e.result)
},
...e.hideFromChannelProgress ? { hideFromChannelProgress: true } : {}
}
});
return;
}
if (e.type === "agent_end") {
const t = e.messages.findLast((e) => e.role === "assistant");
enqueueTerminal({
stopReason: t?.stopReason,
aborted: t?.stopReason === "aborted",
...t?.stopReason === "error" ? { error: t.errorMessage ?? "Worker inference failed." } : {}
});
}
};
const enqueueRunFailure = (e) => {
flushPreview();
a ||= hasModelFallbackStop(e.error);
enqueueTerminal({
aborted: e.aborted,
error: formatErrorMessage(e.error)
});
};
const emitTerminal = async () => {
if (!r) return;
await e.emitTerminal(boundLiveEvent(r));
};
return {
handleSessionEvent,
enqueueRunFailure,
emitTerminal
};
}
//#endregion
//#region src/worker/embedded-agent-transcript.runtime.ts
function toWorkerInferenceMessage(e) {
if (hasRuntimeContextMarker(e) && !isRuntimeContextMessage(e)) throw new Error("Cloud worker cannot preserve runtime context with media. Stop or reclaim the cloud worker, then retry locally.");
if (isRuntimeContextMessage(e)) return {
kind: "complete",
message: {
role: "user",
content: e.content,
timestamp: e.timestamp,
runtimeContext: readRuntimeContextMetadata(e)
}
};
if (e.role === "user") return {
kind: "complete",
message: {
role: "user",
content: typeof e.content === "string" ? e.content : e.content.map(projectWorkerTextOrImageContent),
timestamp: e.timestamp,
...e.operatorMessage ? { operatorMessage: e.operatorMessage } : {}
}
};
const t = toWorkerTranscriptMessage(e, "inference");
if (!t) throw new Error(`Unsupported inference message role: ${e.role}`);
return t;
}
function toWorkerInferenceContext(e) {
const t = windowWorkerReplayMessages(e.messages, WORKER_INFERENCE_MAX_CONTEXT_MESSAGES);
if (t.kind === "provider-replay-unavailable") return t;
const n = [];
for (const e of t.messages) {
const t = toWorkerInferenceMessage(e);
if (t.kind === "provider-replay-unavailable") return t;
n.push(t.message);
}
return {
kind: "complete",
context: {
...e.systemPrompt === void 0 ? {} : { systemPrompt: e.systemPrompt },
messages: n,
...e.tools ? { tools: e.tools.map((e) => ({
name: e.name,
description: e.description,
parameters: e.parameters
})) } : {}
}
};
}
function createWorkerTranscriptRuntime(e, t) {
const n = [];
let r;
const onMessagePersisted = (e) => {
const t = toWorkerTranscriptMessage(e, "transcript");
if (!t) return;
if (t.kind === "provider-replay-unavailable") throw new Error(`Worker transcript cannot persist authoritative provider replay: ${t.details.reason}.`);
const r = readAgentAssistantSource(e)?.itemId;
if (t.message.role === "assistant" && r) t.message.itemId = r;
if (!isWorkerTranscriptMessageFrameSafe(t.message)) throw new Error("Worker transcript message exceeds the protocol payload limit.");
n.push(t.message);
};
const flushTranscript = async () => {
while (n.length > 0) {
if (t?.aborted) {
if (r) throw r.error;
return;
}
const i = n.slice(0, 64);
try {
await e.commit(i);
} catch (e) {
r = { error: e };
throw e;
}
r = void 0;
n.splice(0, i.length);
}
};
let i = Promise.resolve();
const withSessionWriteSettlement = (e) => {
const t = i.then(async () => {
const t = await e();
await flushTranscript();
return t;
});
i = t.then(() => void 0, () => void 0);
return t;
};
return {
onMessagePersisted,
withSessionWriteSettlement
};
}
//#endregion
//#region src/worker/native-inference-stream.ts
function stringParts(e, t, n) {
let r = "";
if (typeof e === "string") {
n.push(e);
r = e;
} else if (Array.isArray(e)) for (const i of e) r += stringParts(i, t, n);
else if (e !== null && typeof e === "object") for (const [i, a] of Object.entries(e)) {
if (t) {
n.push(i);
r += i;
}
r += stringParts(a, t, n);
}
return r;
}
function generatedOutput(e) {
const { content: t, role: n, api: r, provider: i, model: a, usage: o, stopReason: s, timestamp: c, ...l } = e;
const u = [];
let d = "";
let f = "";
let p = "";
for (const e of t) if (e.type === "toolCall") {
u.push(e.id, e.name);
const t = e.id + e.name + stringParts(e.arguments, true, u) + stringParts(e.thoughtSignature, false, u);
f += t;
p += t;
} else if (e.type === "text") {
d += e.text;
const { type: t, text: n, ...r } = e;
const i = stringParts(r, false, u);
f += i;
p += e.text + i;
} else {
d += e.thinking;
const { type: t, thinking: n, ...r } = e;
const i = stringParts(r, false, u);
f += i;
p += e.thinking + i;
}
const m = stringParts(l, false, u);
f += m;
p += m;
return {
all: p,
strings: u,
structured: f,
text: d
};
}
/** Guard provider output before the shared loop can publish it or execute generated tools. */
function createNativeInferenceStreamGuard(e) {
let t = "";
return (n, r) => {
const i = (0, event_stream_exports.createAssistantMessageEventStream)();
(async () => {
let a = [];
let o = 0;
let s = 0;
let c;
try {
const l = await n();
const u = /* @__PURE__ */ new Map();
const d = /* @__PURE__ */ new Set();
const clearToolArguments = (e) => {
const t = u.get(e);
if (t !== void 0) {
s -= Buffer.byteLength(t);
u.delete(e);
}
d.delete(e);
};
const removePendingToolDelta = (e) => {
const t = a.findIndex((t) => t.type === "toolcall_delta" && t.contentIndex === e);
if (t >= 0) {
const e = a[t];
if (e) {
o -= Buffer.byteLength(JSON.stringify(e));
a.splice(t, 1);
}
}
};
const publish = (n) => {
r?.throwIfAborted();
let l = structuredClone(n);
const f = l.type === "done" || l.type === "error";
c = (l.type === "done" ? l.message : l.type === "error" ? l.error : l.partial) ?? (l.type === "text_delta" && c ? appendTextDeltaToAssistantMessage(c, l.contentIndex, l.delta) : void 0);
if (!c) throw new Error("Native stream delta has no message owner");
e.assertProtocolSafe(l);
const p = generatedOutput(c);
const m = t + p.text;
const h = [
m,
p.structured,
p.all
];
e.assertProtocolSafe(h);
const g = p.strings;
if ("delta" in l) g.push(l.delta);
if ("content" in l) g.push(l.content);
if (l.type === "toolcall_end") g.push(...generatedOutput({
...c,
content: [l.toolCall]
}).strings);
if (l.type === "toolcall_delta") {
const e = u.get(l.contentIndex) ?? "";
const t = e + l.delta;
if (Buffer.byteLength(t) > WORKER_PROTOCOL_MAX_INFERENCE_PAYLOAD_BYTES) throw new Error("Native tool arguments exceeded the protocol budget");
s += Buffer.byteLength(t) - Buffer.byteLength(e);
if (s > WORKER_PROTOCOL_MAX_INFERENCE_PAYLOAD_BYTES) throw new Error("Native tool arguments exceeded the aggregate protocol budget");
u.set(l.contentIndex, t);
g.push(t);
try {
g.push(stringParts(JSON.parse(t), true, g));
d.delete(l.contentIndex);
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
d.add(l.contentIndex);
}
l = {
...l,
delta: t
};
removePendingToolDelta(l.contentIndex);
} else if (l.type === "toolcall_end") {
removePendingToolDelta(l.contentIndex);
clearToolArguments(l.contentIndex);
}
e.assertProtocolSafe(g);
const _ = h.some(e.hasCredentialPrefix) || g.some(e.hasCredentialPrefix);
if (f && _) throw new Error("Native stream ended with an unresolved credential prefix");
if (!f && (d.size > 0 || _)) {
o += Buffer.byteLength(JSON.stringify(l));
if (o + s > WORKER_PROTOCOL_MAX_INFERENCE_PAYLOAD_BYTES) throw new Error("Native credential-prefix buffer exceeded");
a.push(l);
return;
}
if (f && d.size > 0) a = [];
if (l.type === "error" && a.length) throw new Error("Native stream failed with an unresolved credential prefix");
for (const e of a) {
i.push(e);
if (e.type === "toolcall_delta") clearToolArguments(e.contentIndex);
}
a = [];
o = 0;
i.push(l);
if (l.type === "toolcall_delta") clearToolArguments(l.contentIndex);
if (l.type === "done") t = m;
};
let f = false;
for await (const t of l) {
r?.throwIfAborted();
if (f) throw new Error("Native stream continued after its terminal event");
if (t.type === "done" || t.type === "error") {
e.assertProtocolSafe(t);
f = true;
} else publish(t);
}
const p = await l.result();
publish(p.stopReason === "error" || p.stopReason === "aborted" ? {
type: "error",
reason: p.stopReason,
error: p
} : {
type: "done",
reason: p.stopReason,
message: p
});
} catch {
const t = r?.aborted === true;
i.push({
type: "error",
reason: t ? "aborted" : "error",
error: {
role: "assistant",
content: [],
provider: e.model.provider,
model: e.model.id,
api: e.model.api,
timestamp: Date.now(),
stopReason: t ? "aborted" : "error",
errorMessage: t ? "Runtime-local inference cancelled" : "Runtime-local inference failed its output boundary",
usage: makeZeroUsageSnapshot()
}
});
} finally {
i.end();
}
})();
return i;
};
}
//#endregion
//#region src/worker/worker-gateway-tools.ts
function createWorkerGatewayToolProxies(e, t) {
const n = [];
for (const r of e.tools) {
if (r.execution !== "gateway") continue;
const i = {
...r.definition,
execute: async (n, i, a, o) => {
a?.throwIfAborted();
if (!isRecord(i)) throw new Error("Gateway tool arguments must be an object.");
const s = r.timeout?.argument ? i[r.timeout.argument] : void 0;
const c = r.timeout ? Math.max(r.timeout.minimumMs ?? 0, (typeof s === "number" ? s : r.timeout.defaultSeconds ?? 0) * 1e3 + (r.timeout.paddingMs ?? 0)) : void 0;
const l = {
generation: e.generation,
toolCallId: n
};
let u = false;
const cancel = () => {
if (u) return;
u = true;
t.cancelGatewayTool(l).catch(() => {});
};
a?.addEventListener("abort", cancel, { once: true });
try {
const e = await t.invokeGatewayTool({
...l,
toolId: r.id,
arguments: i
}, {
replay: r.replay,
timeoutMs: c,
signal: a,
onUpdate: o ? (e) => o({
...e,
details: e.details
}) : void 0
}).catch((e) => {
cancel();
throw e;
});
a?.throwIfAborted();
if (!e.ok) throw new Error(e.error.message);
const { mcpGuestResult: n, mcpBlockedReason: s, ...u } = e.payload;
const d = {
...u,
details: u.details
};
if (!r.plugin?.mcp) return d;
if (s !== void 0) return markToolExecutionRefused(d, {
kind: "blocked",
reason: s
});
return n !== void 0 ? setMcpCodeModeGuestResult(d, n) : d;
} finally {
a?.removeEventListener("abort", cancel);
}
}
};
if (r.plugin) setPluginToolMeta(i, r.plugin);
bindBeforeToolCallMetadata(i, {
sourceTool: { ...i },
options: { emitDiagnostics: false }
});
n.push(i);
}
return n;
}
//#endregion
//#region src/worker/embedded-agent.runtime.ts
function toWorkerAgentError(e, t) {
return e instanceof Error ? e : new Error(t, { cause: e });
}
async function runWorkerEmbeddedTurn(e) {
const t = e.skillResources ? await materializeSkillResources(e.skillResources, () => e.signal?.throwIfAborted(), {
sessionId: e.sessionId,
workspaceDir: e.cwd
}) : void 0;
try {
if (e.allowedToolNames.includes("browser") !== (e.browser !== void 0)) throw new Error("Worker Browser authority and launch descriptor must be provided together.");
if (e.allowedToolNames.includes("computer") !== (e.computer !== void 0)) throw new Error("Worker computer authority and launch descriptor must be provided together.");
if (e.operationalRunInstance.runId !== e.runId) throw new Error("worker operational run instance disagrees with the admitted turn");
const n = e.toolSurface;
const r = e.nativeInference?.model ?? createNativeModelOwnedRuntimeModel({
provider: e.modelRef.provider,
modelId: e.modelRef.model
});
if (!e.nativeInference) {
r.contextWindow = n.policy.modelContextWindowTokens ?? r.contextWindow;
if (n.policy.modelHasVision !== void 0) r.input = n.policy.modelHasVision ? ["text", "image"] : ["text"];
}
const i = e.inferenceOptions?.reasoning;
if (e.nativeInference && i === "adaptive") throw new Error("Adaptive thinking is not supported by runtime-local worker inference");
const a = e.nativeInference ? i === "adaptive" ? "off" : i ?? "off" : "medium";
if (e.nativeInference && !getSupportedThinkingLevels(r).includes(a)) throw new Error("Requested thinking level is not supported by the node-local model");
if (e.nativeInference && (e.inferenceOptions?.maxTokens !== void 0 && e.inferenceOptions.maxTokens !== r.maxTokens || Object.values(e.inferenceOptions?.thinkingBudgets ?? {}).some((e) => e !== void 0 && e > r.maxTokens))) throw new Error("Worker inference options exceed or override the node-local model budget");
const o = AuthStorage.inMemory({});
const s = ModelRegistry.inMemory(o);
const c = SettingsManager.inMemory({
compaction: { enabled: false },
retry: { enabled: false }
});
const l = new DefaultResourceLoader({
cwd: e.cwd,
agentDir: e.stateDir
});
const u = SessionManager.inMemory(e.cwd);
for (const t of e.initialMessages ?? []) await u.appendMessageAsync(structuredClone(t));
const d = createWorkerTranscriptRuntime(e.transcript, e.signal);
const f = guardSessionManager(u, {
suppressNextUserMessagePersistence: e.suppressPromptTranscript,
onMessagePersisted: d.onMessagePersisted
});
const p = f.appendCustomMessageEntryAsync.bind(f);
f.appendCustomMessageEntryAsync = async (e, t, n, r) => {
const i = await p(e, t, n, r);
const a = f.getEntry(i);
const o = a && projectSessionEntryMessage(a);
if (!o) throw new Error("Worker custom message was not committed");
d.onMessagePersisted(o);
return i;
};
const m = new Set(e.allowedToolNames);
for (const e of n.tools) if (e.execution === "placement" && !m.has(e.definition.name)) throw new Error(`Worker tool surface exceeds launch authority: ${e.definition.name}`);
const h = new Set(n.tools.map(({ definition: e }) => e.name));
const g = projectMemoryFlushTools(createWorkerPlacementTools({
...e,
policy: n.policy,
containmentRoot: e.workerContainmentRoot,
skillsSnapshot: t?.snapshot
}), n.policy.memoryFlushWritePath ? {
root: e.workerContainmentRoot,
relativePath: n.policy.memoryFlushWritePath
} : void 0);
const _ = e.browser && h.has("browser") ? await createWorkerBrowserToolRuntime({
descriptor: e.browser,
sessionKey: toAgentStoreSessionKey({
agentId: e.agentId,
requestKey: e.sessionKey
}),
stateDir: e.stateDir,
workspaceDir: e.cwd,
...e.browserRuntime ? { runtime: e.browserRuntime } : {}
}) : void 0;
const v = new AbortController();
const y = e.signal ? AbortSignal.any([e.signal, v.signal]) : v.signal;
let b;
let x;
async function disposeTools(e) {
v.abort();
const t = b;
b = void 0;
const n = e ? [e] : [];
const r = await Promise.allSettled([
() => x?.cleanup(),
() => t?.("Worker turn finished"),
() => _?.dispose(),
disposeAllCodeModeRuns
].map(async (e) => await e()));
for (const e of r) if (e.status === "rejected") {
const t = toWorkerAgentError(e.reason, "Worker tool cleanup failed.");
recordModelFallbackStop(t);
n.push(t);
}
return n.length > 1 ? new AggregateError(n, "Worker turn failed") : n[0];
}
const { session: S } = await (async () => {
try {
const i = e.computer && h.has("computer") ? createWorkerComputerTool({
...e.computer,
runId: e.runId,
registerRunCleanup: (e) => {
b = e;
}
}) : void 0;
const o = new Map([
...g,
..._ ? [_.tool] : [],
...i ? [i] : []
].map((e) => [e.name, e]));
const u = new Map(createWorkerGatewayToolProxies(n, e.gatewayTools).map((e) => [e.name, e]));
const p = n.tools.map((t) => {
if (t.execution === "gateway") return wrapToolWithAbortSignal(u.get(t.definition.name), y);
const n = o.get(t.definition.name);
if (!n) throw new Error(`Worker placement tool unavailable: ${t.definition.name}`);
const r = copyAgentToolMetadata(n, {
...n,
...t.definition
});
if (t.plugin) setPluginToolMeta(r, t.plugin);
return wrapToolWithGatewayCallerIdentity(wrapToolWithAbortSignal(wrapToolWithBeforeToolCallHook(r, {
agentId: e.agentId,
config: WORKER_TOOL_CONFIG,
cwd: e.cwd,
workspaceDir: e.cwd,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
runId: e.runId,
requester: { senderIsOwner: true }
}), y), {
agentId: e.agentId,
sessionKey: e.sessionKey,
operationalRunInstance: e.operationalRunInstance,
signedAgentRuntimeIdentityToken: e.agentRuntimeIdentityToken
});
});
x = createAgentHarnessToolSurfaceRuntimeCore({
agentId: e.agentId,
sessionId: e.sessionId,
sessionKey: e.sessionKey,
runId: e.runId,
abortSignal: y,
presentation: n.presentation,
supportsDeferredToolCalls: false,
modelToolsEnabled: p.length > 0,
model: r
});
const m = x.compactTools(p, { prepared: {
abortSignal: y,
preserveToolNames: []
} }).promptToolPolicy.apply();
await l.reload();
const v = completeSystemPromptRuntime(e.systemPrompt ?? "", {
host: await getMachineDisplayName(),
os: resolveRuntimeOsLabel(),
arch: os.arch(),
node: process.version,
shell: detectRuntimeShell() ?? path.basename(getShellConfig().shell),
repoRoot: await resolveSystemPromptRepoRoot({
workspaceDir: e.cwd,
cwd: e.cwd
})
});
return await createAgentSession({
systemPrompt: t?.rewriteReferences(v) ?? v,
cwd: e.cwd,
modelRegistry: s,
model: r,
thinkingLevel: a,
tools: m.tools.map((e) => e.name),
customTools: toToolDefinitions(m.tools),
sessionManager: f,
settingsManager: c,
resourceLoader: l,
withSessionWriteSettlement: d.withSessionWriteSettlement
});
} catch (e) {
throw await disposeTools(toWorkerAgentError(e, "Worker agent setup failed."));
}
})();
S.agent.sessionId = e.sessionId;
const C = e.nativeInference ? createNativeInferenceStreamGuard(e.nativeInference) : void 0;
S.agent.streamFn = async (t, n, i) => {
if (e.nativeInference && C) {
const t = e.nativeInference;
return C(() => t.streamFn(r, n, {
...e.inferenceOptions,
reasoning: a,
signal: i?.signal
}), i?.signal);
}
const o = toWorkerInferenceContext(n);
if (o.kind === "provider-replay-unavailable") throw new Error(`${WORKER_PROVIDER_REPLAY_LOCAL_RETRY_MESSAGE} (${o.details.reason})`);
return e.inference.stream({
modelRef: e.modelRef,
context: o.context,
options: e.inferenceOptions,
...i?.signal ? { signal: i.signal } : {}
});
};
const w = createWorkerLiveRuntime(e.live);
const T = subscribeEmbeddedAgentSession({
session: S,
runId: e.runId,
sessionKey: e.sessionKey,
terminalLifecyclePhase: "finishing",
codeModeExecToolNames: new Set(x?.codeModeControlsEnabled ? ["exec"] : [])
});
const E = S.subscribe(w.handleSessionEvent);
const D = new Set(listRunningSessions().map(({ id: e }) => e));
const abortTurn = () => S.agent.abort();
e.signal?.addEventListener("abort", abortTurn, { once: true });
let O;
try {
const n = typeof e.prompt === "string" ? [{
type: "text",
text: e.prompt
}] : [...e.prompt];
if (t) {
for (const [e, r] of n.entries()) if (r.type === "text") n[e] = {
...r,
text: t.rewriteReferences(r.text)
};
}
const i = e.runtimeContext ? [...await buildExecutionHostRuntimeFacts({
...e,
capabilityToolNames: h
}), ...e.runtimeContext] : [];
const a = buildRuntimeContextCustomMessage(projectRuntimeContextFragments(i), i, e.inHistorySystemUpdates);
e.signal?.throwIfAborted();
let o = true;
if (e.admitTurn) {
const t = toWorkerInferenceContext({ messages: convertToLlm(S.agent.state.messages) });
if (t.kind !== "complete") throw new Error(WORKER_PROVIDER_REPLAY_LOCAL_RETRY_MESSAGE);
o = await e.admitTurn({
systemPrompt: S.agent.state.systemPrompt,
prompt: n.filter((e) => e.type === "text").map((e) => e.text).join("\n"),
messages: t.context.messages
});
e.signal?.throwIfAborted();
}
if (!o) w.handleSessionEvent({
type: "agent_end",
messages: [],
willRetry: false
});
else {
await S.agent.prompt([{
role: "user",
content: n,
timestamp: Date.now()
}, ...a ? [a] : []]);
await T.waitForPendingEvents();
e.signal?.throwIfAborted();
let t = T.getCurrentAttemptAssistant();
const i = listRunningSessions().filter(({ id: t, scopeKey: n }) => n === e.sessionKey && !D.has(t));
const o = {
...readSubscriptionCompletionEvidence(T),
currentAttemptAssistant: t,
messagesSnapshot: S.agent.state.messages,
terminal: { kind: "ok" }
};
const s = classifyAssistantTurn({
attempt: o,
payloadCount: 0
});
const c = resolveSettledToolTerminalContinuation({
provider: r.provider,
modelId: r.id,
modelApi: r.api,
terminalReplyExpectation: "result-required",
replyDeliveryState: T.getSourceReplyDeliveryState() ?? "missing",
aborted: false,
timedOut: false,
attempt: o,
allowEmptyStopContinuation: !s.silent,
payloadCount: s.visibleText || i.length ? 1 : 0
});
if (c && t?.stopReason === "stop") {
if (c.disableTools) S.agent.state.tools = [];
await S.sendCustomMessage({
customType: "openclaw.settled-tool-finalization",
content: c.instruction,
display: false
}, { triggerTurn: true });
t = T.getCurrentAttemptAssistant();
assertSettledTurnFinalizationResult({ assistant: t });
}
e.signal?.throwIfAborted();
if (t?.stopReason === "error" || t?.stopReason === "aborted") throw new Error(t.errorMessage ?? `Worker inference ${t.stopReason}.`);
if (i.length > 0) {
const e = buildAssistantMessage({
model: r,
stopReason: "stop",
usage: buildUsageWithNoCost({}),
content: [{
type: "text",
text: `Background commands are still running (process sessions: ${i.map(({ id: e }) => e).join(", ")}). This turn has ended before their results were available.`
}]
});
w.handleSessionEvent({
type: "message_start",
message: e
});
w.handleSessionEvent({
type: "message_end",
message: e
});
await f.appendMessageAsync(e);
}
}
} catch (t) {
O = e.signal?.aborted ? toWorkerAgentError(e.signal.reason, "Worker agent turn aborted.") : toWorkerAgentError(t, "Worker agent turn failed.");
}
try {
const [t, n] = await Promise.all([disposeTools(O), d.withSessionWriteSettlement(() => void 0).catch((e) => toWorkerAgentError(e, "Worker transcript flush failed."))]);
O = t;
if (O) w.enqueueRunFailure({
aborted: e.signal?.aborted === true,
error: O
});
if (n) throw O ?? n;
await w.emitTerminal();
} finally {
v.abort();
e.signal?.removeEventListener("abort", abortTurn);
E();
T.unsubscribe();
S.dispose();
}
if (O !== void 0) throw O;
} finally {
await t?.cleanup();
}
}
//#endregion
export { runWorkerEmbeddedTurn };