openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,209 lines (1,208 loc) • 48.1 kB
JavaScript
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs";
import { M as resolveExpiresAtMsFromDurationSeconds, f as asPositiveInteger, y as isFutureDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord, t as asNonArrayRecord, u as isStringArray } from "./record-coerce-CVPuDqcc.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { i as clampNumber } from "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { o as throwSettledAggregate } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as PluginRuntimeCloseRetainedError } from "./runtime-close-error-Ak-r7PLO.mjs";
import { r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { i as createLazyRuntimeNamedExport } from "./lazy-runtime-zGjszCtt.mjs";
import { r as normalizeAgentModelRefForConfig } from "./model-input-DrM4DWHG.mjs";
import { h as onAgentEventForRun } from "./agent-events-BdfWYmot.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import { c as NODE_FS_LIST_DIR_COMMAND } from "./node-commands-BfMJIlXP.mjs";
import { a as formatToolExecutionGatedMessage, o as isToolExecutionAllowed } from "./tool-policy-shared-BHvBopvF.mjs";
import { n as CODE_MODE_WAIT_TOOL_NAME, t as CODE_MODE_EXEC_TOOL_NAME } from "./code-mode-control-tools-2pBIuXDg.mjs";
import { n as ToolInputError, r as isTrustedToolInputError } from "./tool-input-error-B1hgavSw.mjs";
import "./common-njQNtpnW.mjs";
import { r as getBeforeToolCallFailureDisposition } from "./agent-tools.before-tool-call.wrapper-Dh3maIc2.mjs";
import { t as createPendingPromiseTracker } from "./pending-promises-DNsYFS1E.mjs";
import { c as resolveSafeTimeoutDelayMs } from "./timeouts-nwfOzsiL.mjs";
import { t as captureAgentPluginRuntimeRefresh } from "./plugin-runtime-refresh-DCHb6kdS.mjs";
import { t as resolveEligibleNodeFromList } from "./node-resolve-CkGq9hyv.mjs";
import { n as formatSkillInstructions } from "./skill-instruction-result-RZ7WPgCg.mjs";
import { l as recordCodeModeToolOutcome } from "./tool-loop-detection-CR_Hr4G6.mjs";
import "./agent-tools.before-tool-call-CCkSq-k3.mjs";
import { r as readToolOutputSchemaVariants } from "./tool-output-schema-Cs8aYtff.mjs";
import "./code-mode-worker-types-DkuJ9oOv.mjs";
import { o as stringifyCodeModeJsonSafe, r as boundCodeModeError } from "./code-mode-json-rc1Zn-6x.mjs";
import { t as consumeMcpCodeModeGuestResult } from "./mcp-content-CYbca1LN.mjs";
import { t as raceWithAbortSignal } from "./agent-tools.abort-BN-GwRlX.mjs";
import { t as resolveSwarmConfig } from "./swarm-config-Dp8TTyRG.mjs";
import { o as isCollectorSpawnTool } from "./swarm-collector-capability-BSHCyIjQ.mjs";
import { d as createCodeModeSessionStoreAccess, f as isCodeModeSessionStoreRequest, o as toolSchemaDeclaration, r as MAX_TOOL_SCHEMA_DECLARATION_CHARS, s as createCodeModeResultsAccess, t as getToolContractFailureCode } from "./tool-contract-error-CJHmBmJj.mjs";
import { t as parseNodeList } from "./node-list-parse-DT6NmnCE.mjs";
import { i as logCodeModeFailure } from "./code-mode-diagnostic-CA-TPnkt.mjs";
import { createHash, randomUUID } from "node:crypto";
import { isDeepStrictEqual } from "node:util";
import { setTimeout as setTimeout$1 } from "node:timers/promises";
import { tokTypes } from "acorn";
//#region src/agents/code-mode-catalog.ts
const RESERVED_GLOBAL_NAMES = new Set("ALL_TOOLS API MCP agents catalog clearTimeout globalThis json load log namespaces nodes phase results setTimeout skills store text tools yield_control AggregateError Array ArrayBuffer Atomics BigInt BigInt64Array BigUint64Array Boolean DataView Date Error EvalError FinalizationRegistry Float32Array Float64Array Function Infinity Int16Array Int32Array Int8Array Intl JSON Map Math NaN Number Object Promise Proxy RangeError ReferenceError Reflect RegExp Set SharedArrayBuffer String Symbol SyntaxError TextDecoder TextEncoder TypeError URIError Uint16Array Uint32Array Uint8Array Uint8ClampedArray WeakMap WeakRef WeakSet WebAssembly console decodeURI decodeURIComponent encodeURI encodeURIComponent escape eval isFinite isNaN parseFloat parseInt undefined unescape".split(" "));
const RESERVED_WORDS = /* @__PURE__ */ new Set([
...Object.values(tokTypes).flatMap((e) => e.keyword ? [e.keyword] : []),
"await",
"enum",
"implements",
"interface",
"package",
"private",
"protected",
"public",
"static",
"yield"
]);
function normalizedCallableBase(e) {
const t = e.replace(/[^A-Za-z0-9_$]/g, "_");
return /^[A-Za-z_$]/.test(t) && !t.startsWith("__openclaw") ? t : `tool_${t}`;
}
function suffixedCallableName(e, t, n) {
const r = createHash("sha256").update(t).digest("hex");
for (let t = 8; t <= r.length; t += 2) {
const i = `${e}_${r.slice(0, t)}`;
if (!n.has(i) && !RESERVED_WORDS.has(i)) return i;
}
throw new Error("could not allocate a unique code mode callable name");
}
function selectEffectiveEntries(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) {
if (n.source === "mcp") continue;
const e = t.get(n.name);
if (!e || n.source === "client" && e.source !== "client") t.set(n.name, n);
}
return [...t.values()];
}
/** Canonical callable names shared by the prompt, guest bindings, and bridge routing. */
function createCodeModeCatalogBindings(e, t) {
const n = /* @__PURE__ */ new Set([...RESERVED_GLOBAL_NAMES, ...t?.reservedNames ?? []]);
const r = selectEffectiveEntries(e).map((e) => {
const t = normalizedCallableBase(e.name);
return {
entry: e,
base: t,
canKeepExactName: e.name === t && !RESERVED_WORDS.has(e.name) && !n.has(e.name)
};
}).toSorted((e, t) => Number(t.canKeepExactName) - Number(e.canKeepExactName) || e.base.localeCompare(t.base) || e.entry.id.localeCompare(t.entry.id));
const i = [];
for (const e of r) {
let t = e.base;
if (RESERVED_WORDS.has(t) || n.has(t)) t = suffixedCallableName(e.base, e.entry.id, n);
n.add(t);
const { id: r, source: a, name: o, label: s, description: c, input: l, output: u } = e.entry;
i.push({
id: r,
source: a,
name: o,
label: s,
description: c,
input: l,
output: u,
callableName: t
});
}
i.sort((e, t) => e.callableName.localeCompare(t.callableName));
return i;
}
/** Execution owns guest copies and routing maps; prompt construction needs only bindings. */
function createCodeModeCatalogProjection(e, t) {
const n = createCodeModeCatalogBindings(e, t);
return {
bindings: n,
guestBindings: n.map(({ id: e, ...t }) => t),
byCallableName: new Map(n.map((e) => [e.callableName, e])),
byId: new Map(n.map((e) => [e.id, e])),
searchableIds: /* @__PURE__ */ new Set([...n.map((e) => e.id), ...t?.mcpIds ?? []])
};
}
function redactCodeModeCatalogIds(e, t) {
let n = e;
for (const e of t.toSorted((e, t) => t.id.length - e.id.length)) n = n.replaceAll(e.id, e.callableName);
return n;
}
//#endregion
//#region src/agents/code-mode-results-api.ts
const content = `type CodeModeResultReference = {
id: string;
bytes: number;
/** Array length, object key count, or 1 for a scalar. */
count: number;
/** Observed, bounded sample shapes and nested array counts; not a schema. */
shape: string;
/** Small values: JSON. Larger values: a sampled view with array paths/counts/items
* and compact envelope fields. May be a JSON prefix; never substitute it for full data. */
preview: string;
previewTruncated: boolean;
};
/** Up to 64 references share min(memoryLimitBytes, maxSnapshotBytes) encoded JSON
* bytes (10 MiB by default), separately from the cell inbox. Full stores reject
* saves without evicting entries. References survive cells and wait, but expire
* when the current reply ends, or on abort, catalog replacement, permission
* changes, or restart. Never reuse reference ids from earlier turns; use store
* for small JSON values needed later.
* Saved data is a snapshot, not current external state.
* Oversized final objects/arrays are saved automatically in interactive exec/wait
* when possible: value is {truncated:true, reference:CodeModeResultReference, guidance:string}.
* Failed retention stays completed with a truncation marker explaining why it was not retained.
* No automatic references in headless execution.
* Array discovery visits at most 128 nodes, 5 levels, and 16 object keys per node;
* arrays sample first/middle/last, with the 8 largest discovered arrays shown first.
* Sample values visit 2 levels/6 fields, with bounded text. A descriptor is at most
* 768 encoded JSON bytes, and display fitting can shorten shape/preview further.
*/
declare const results: {
/** Save normalized JSON for later cells in this reply. Returns the descriptor above: emit it directly;
* its preview, shape, and count are already prepared. The full JSON stays stored.
* Example: return await results.save(await tool({}));
*/
save(value: unknown): Promise<CodeModeResultReference>;
/** Read a detached JSON copy. Inspect the saved preview before using unknown fields. */
load(id: string): Promise<unknown>;
/** Free capacity. Missing or expired references reject. */
delete(id: string): Promise<boolean>;
};
/** Keep a small JSON value across cells and turns in this session, including restarts.
* Keys must be non-empty strings of at most 256 characters (otherwise TypeError).
* Values use normal bridge JSON normalization. undefined deletes the key.
* Encoded JSON limits: 256 KiB per value, 1 MiB total; RangeError leaves the store unchanged.
* Writes are visible within this cell, including wait, but persist only on completed.
* Failed, timed-out, aborted, expired, or disposed cells discard their writes.
* A persistence failure leaves the cell completed with a warning and the run projection unchanged;
* verify the transcript before relying on the write, since its durable outcome may be uncertain.
* Available only in interactive cells bound to a session, never headless cells.
*/
declare function store(key: string, value: unknown): Promise<void>;
/** Read a detached JSON copy, or undefined when missing, including this cell's pending writes.
* Uses the same key and availability rules as store. Network-content provenance is preserved.
*/
declare function load(key: string): Promise<unknown>;`;
const CODE_MODE_RESULTS_API_FILE = {
path: "results.d.ts",
description: "Temporary results for this reply and small JSON values persisted in this session.",
bytes: Buffer.byteLength(content, "utf8"),
content
};
//#endregion
//#region src/agents/code-mode-runtime.ts
const DEFAULT_HEADLESS_WALL_CLOCK_MS = 3e4;
const MAX_HEADLESS_WALL_CLOCK_MS = 9e5;
function normalizeCodeModeRawConfig(e) {
if (typeof e === "boolean" || e === "auto") return { enabled: e };
return e;
}
function readCodeModeRawConfig(e, t, n) {
const r = normalizeCodeModeRawConfig(e?.tools?.codeMode) ?? { enabled: "auto" };
const i = e && t ? resolveAgentConfig(e, t) : void 0;
const a = normalizeCodeModeRawConfig(i?.tools?.codeMode);
const o = n ? normalizeAgentModelRefForConfig(modelKey(n.provider, n.modelId)) : void 0;
return {
...r,
...a,
enabled: (o ? i?.models?.[o]?.codeMode : void 0) ?? a?.enabled ?? (o ? e?.agents?.defaults?.models?.[o]?.codeMode : void 0) ?? r.enabled
};
}
function resolveCodeModeConfig(e, t, n) {
const r = readCodeModeRawConfig(e, t, n);
const limit = (e, t, n, i) => clampNumber(asPositiveInteger(r[e]) ?? t, n, i);
const i = limit("maxSearchLimit", 50, 1, 50);
return {
enabled: r.enabled ?? false,
executor: r.executor ?? "node",
mode: "only",
timeoutMs: limit("timeoutMs", 1e4, 100, 6e4),
memoryLimitBytes: limit("memoryLimitBytes", 67108864, 1048576, 1073741824),
maxOutputBytes: limit("maxOutputBytes", 65536, 1024, 10485760),
maxSnapshotBytes: limit("maxSnapshotBytes", 10485760, 1024, 268435456),
maxPendingToolCalls: limit("maxPendingToolCalls", 16, 1, 128),
snapshotTtlSeconds: limit("snapshotTtlSeconds", 900, 1, 86400),
searchDefaultLimit: limit("searchDefaultLimit", 8, 1, i),
maxSearchLimit: i
};
}
/**
* Resolves the effective activation policy against one model's catalog flag.
* `true`/`false` are absolute; `"auto"` engages only for models whose catalog
* compat declares `codeMode: "preferred"`. This gates the model-facing tool
* surface only; runs that route to a provider-native harness (for example the
* default OpenAI Codex surface) never reach this embedded-runtime gate.
*/
function isCodeModeEngagedForModel(e, t) {
if (e.enabled !== "auto") return e.enabled;
return (t?.compat && typeof t.compat === "object" ? t.compat : void 0)?.codeMode === "preferred";
}
function toToolSearchConfig(e) {
return {
enabled: true,
mode: "tools",
searchDefaultLimit: e.searchDefaultLimit,
maxSearchLimit: e.maxSearchLimit
};
}
function readCode(e) {
const t = asNonArrayRecord(e);
const n = readNonBlankString(t.code);
const r = readNonBlankString(t.command);
if (n !== void 0 && r !== void 0 && n !== r) throw new ToolInputError("code and command must match when both are provided.");
const i = r ?? n;
if (i === void 0) throw new ToolInputError("code or command must be a non-empty string.");
if (t.language !== void 0 || t.typecheck !== void 0) throw new ToolInputError("Code Mode accepts JavaScript only. Remove language and typecheck; use API.read(...) for tool types.");
const a = t.awaitResults;
if (a !== void 0 && typeof a !== "boolean") throw new ToolInputError("awaitResults must be a boolean.");
return {
code: i,
awaitResults: a === true
};
}
function readRunId(e) {
const t = asNonArrayRecord(e);
const n = t.runId ?? t.run_id;
if (typeof n !== "string" || !n.trim()) throw new ToolInputError("runId must be a non-empty string.");
return n.trim();
}
function createCodeModeApiFilesForRun(e, t) {
const { apiFiles: n } = e;
return [CODE_MODE_RESULTS_API_FILE, ...t ? n : n.filter((e) => e.path !== "agents.d.ts")];
}
//#endregion
//#region src/agents/code-mode-tool-api.ts
/** Generate only on API.read, from the same effective schemas as describe(). */
async function createCodeModeToolApiFile(e, t) {
const n = t.source === "openclaw";
const r = n ? toolSchemaDeclaration(t.parameters) : "unknown";
const i = n ? readToolOutputSchemaVariants(t.outputSchema) : void 0;
let a = false;
if (n) {
const { validateJsonSchemaValue: e } = await import("./schema-validator-ChWFyDdz.mjs");
try {
a = e({
schema: t.parameters ?? {},
value: {}
}).ok;
} catch {}
}
let o = i?.canNarrow ? createVariantDeclarations({
callableName: e,
input: r,
optional: a,
outputSchema: t.outputSchema,
variants: i
}) : void 0;
if (!o) {
const s = n ? toolSchemaDeclaration(t.outputSchema) : "unknown";
o = [...i ? [i.canNarrow ? "// Action declarations exceed the shared output allowance; using the complete union." : "// Reference-bearing or structurally complex schemas retain the complete output union."] : [], `declare function ${e}(input${a ? "?" : ""}: ${r}): Promise<${s}>;`];
}
const s = [
"// Generated from the effective tool contract. Unsupported shapes stay unknown.",
"// JSON Schema validation owns constraints; describe() exposes the original schema.",
"// Values enter the guest intact or reject when program-data admission is full.",
...o
].join("\n");
return {
path: "tools/" + e + ".d.ts",
content: s,
bytes: Buffer.byteLength(s, "utf8")
};
}
function readObjectDeclaration(e, t) {
if (!isRecord(t) || t.type !== "object" || t.additionalProperties !== false || !isRecord(t.properties) || Object.keys(t).some((e) => ![
"type",
"properties",
"required",
"additionalProperties"
].includes(e)) || t.required !== void 0 && !isStringArray(t.required)) return;
const n = t.properties;
const r = new Set(t.required ?? []);
if ([...r].some((e) => !Object.hasOwn(n, e))) return;
return {
name: e,
properties: n,
required: r
};
}
function factorObjectDeclaration(e, t, n, r) {
let i = r;
for (const r of t) {
if (!Object.entries(r.properties).every(([t, n]) => Object.hasOwn(e.properties, t) && r.required.has(t) === e.required.has(t) && isDeepStrictEqual(n, e.properties[t]))) continue;
const t = Object.fromEntries(Object.entries(e.properties).filter(([e]) => !Object.hasOwn(r.properties, e)));
const a = toolSchemaDeclaration({
...n,
anyOf: [{
type: "object",
properties: t,
required: [...e.required].filter((e) => Object.hasOwn(t, e)),
additionalProperties: false
}]
});
const o = Object.keys(t).length === 0 ? r.name : `${r.name} & ${a}`;
if (a !== "unknown" && o.length < i.length) i = o;
}
return i;
}
function createVariantDeclarations(e) {
const { callableName: t, input: n, optional: r, outputSchema: i, variants: a } = e;
const o = [];
let s = 0;
const append = (e, t = 0) => {
s += e.length + 1 - t;
if (s > 32768) return false;
o.push(e);
return true;
};
const c = `__OpenClaw_${t}_`;
const l = `${c}Input`;
if (!append(`type ${l} = ${n};`, n.length)) return;
const u = [];
const d = [];
for (const [e, t] of a.variants.entries()) {
const n = `${c}Output${e}`;
let r = toolSchemaDeclaration({
...i,
anyOf: [t]
});
const a = r === "unknown" ? void 0 : readObjectDeclaration(n, t);
if (a) {
r = factorObjectDeclaration(a, d, i, r);
d.push(a);
} else if (r !== "unknown" && isRecord(t) && Array.isArray(t.anyOf) && Object.keys(t).every((e) => e === "anyOf")) r = t.anyOf.map((e) => {
const t = toolSchemaDeclaration({
...i,
anyOf: [e]
});
const r = t === "unknown" ? void 0 : readObjectDeclaration(n, e);
return r ? factorObjectDeclaration(r, d, i, t) : t;
}).join(" | ");
if (!append(`type ${n} = ${r};`)) return;
u.push(n);
}
const f = `${c}OutputByInput`;
if (!append(`type ${f} = {`)) return;
for (const [e, t] of a.mapping) if (!append(`${JSON.stringify(e)}: ${u[t]};`)) return;
if (!append("};")) return;
const p = u.join(" | ");
if (!append(`declare function ${t}<const Input extends ${l}>(input: Input): Promise<Input extends { ${JSON.stringify(a.inputProperty)}: infer Value } ? Value extends keyof ${f} ? ${f}[Value] : ${p} : ${p}>;`) || !append(`declare function ${t}(input${r ? "?" : ""}: ${l}): Promise<${p}>;`)) return;
return o;
}
//#endregion
//#region src/agents/code-mode-bridge.ts
const loadSwarmHandlers = createLazyRuntimeNamedExport(() => import("./code-mode-swarm.runtime.js"), "codeModeSwarmHandlers");
const CODE_MODE_INSTRUCTIONS_HINT = "Call handle.describe() before invocation to load the complete server instructions.";
const CODE_MODE_NODES_TOOL_ID = "openclaw:core:nodes";
function projectCodeModeNode(e) {
return {
id: e.nodeId,
name: e.displayName?.trim() || e.nodeId,
...e.platform ? { platform: e.platform } : {},
connected: e.connected === true,
commands: Array.isArray(e.commands) ? e.commands.filter((e) => typeof e === "string") : []
};
}
async function runNodesBridge(e) {
const call = (t) => e.runtime.callValue(CODE_MODE_NODES_TOOL_ID, t, {
includeMcp: false,
parentToolCallId: e.parentToolCallId,
signal: e.signal,
onUpdate: e.onUpdate,
recoverySurface: "catalog"
});
const t = e.request.args;
const n = t[0];
if (n === "list") return parseNodeList(await call({ action: "status" })).filter((e) => e.paired === true).map(projectCodeModeNode);
if (n === "get") {
const e = t[1];
if (typeof e !== "string" || !e.trim()) throw new ToolInputError("nodes.get id or name must be a non-empty string.");
const n = projectCodeModeNode(resolveEligibleNodeFromList(parseNodeList(await call({ action: "status" })), e, (e) => e.paired === true, {
ineligibleExact: (e, t) => `node "${e}" is not paired (paired node ids: ${t})`,
nameResolveFailed: (e, t) => `${e} (paired node ids: ${t})`,
noneEligible: () => "no paired nodes",
multipleEligible: (e) => `multiple nodes paired: ${e.map((e) => e.nodeId).toSorted().join(", ")}`
}));
return {
id: n.id,
name: n.name,
...n.commands.includes("fs.listDir") ? { listDirCommand: NODE_FS_LIST_DIR_COMMAND } : {}
};
}
if (n === "invoke") {
const e = t[1];
const n = t[2];
if (typeof e !== "string" || !e.trim()) throw new ToolInputError("nodes.invoke node id must be a non-empty string.");
if (typeof n !== "string" || !n.trim()) throw new ToolInputError("nodes.invoke command must be a non-empty string.");
return await call({
action: "invoke",
node: e,
invokeCommand: n,
invokeParamsJson: JSON.stringify(t[3] ?? {})
});
}
throw new ToolInputError("unsupported nodes bridge action.");
}
function codeModeReplayIdForToolCall(e, t, n, r) {
const i = e.runId?.trim();
if (!i) return `cm_replay_${randomUUID()}`;
const a = JSON.stringify([
e.sessionKey ?? "",
e.sessionId ?? "",
i,
r?.trim() ?? "",
t,
n
]);
return `cm_replay_${createHash("sha256").update(a).digest("hex").slice(0, 24)}`;
}
function isCodeModeSwarmAvailable(e, t) {
return resolveSwarmConfig(e.runtimeConfig ?? e.config, e.agentId).enabled && (!e.toolExecutionAllow || isToolExecutionAllowed(e.toolExecutionAllow, "sessions_spawn")) && t?.some((e) => e.source === "openclaw" && e.name === "sessions_spawn") === true && e.catalogRef?.current?.entries.some((e) => e.name === "sessions_spawn" && isCollectorSpawnTool(e.tool)) === true && !e.catalogRef.current.entries.some((e) => e.source === "client" && e.name === "sessions_spawn");
}
function requireCodeModeSwarmEnabled(e) {
if (!resolveSwarmConfig(e.runtimeConfig ?? e.config, e.agentId).enabled) throw new ToolInputError("code mode swarm globals are disabled.");
if (e.toolExecutionAllow && !isToolExecutionAllowed(e.toolExecutionAllow, "sessions_spawn")) throw new ToolInputError(formatToolExecutionGatedMessage("sessions_spawn", e.toolExecutionAllow));
}
/** Recognize explicit required intent only on the authorized core tool bindings. */
function requiresCodeModeCompletion(e, t) {
return e.some((e) => {
if (e.method !== "callValue" || !isRecord(e.args[1]) || e.args[1].awaitResults !== true) return false;
const n = typeof e.args[0] === "string" ? t.byCallableName.get(e.args[0]) : void 0;
return n?.id === "openclaw:core:exec" || n?.id === "openclaw:core:agents_wait";
});
}
async function runBridgeRequest(e) {
const t = e.catalogProjection;
const n = isCodeModeSessionStoreRequest(e.request);
const catalogBinding = (e, n) => {
if (typeof e !== "string") throw new ToolInputError(`${n} callable name must be a string.`);
const r = t.byCallableName.get(e);
if (!r) throw new ToolInputError(`Unknown catalog function: ${e}.`);
return r;
};
const callOptions = () => ({
recoverySurface: "catalog",
parentToolCallId: e.parentToolCallId,
signal: e.signal,
onUpdate: e.onUpdate
});
try {
e.signal?.throwIfAborted();
const r = Array.isArray(e.request.args) ? e.request.args : [];
let i;
switch (e.request.method) {
case "resultSave":
case "resultLoad":
case "resultDelete": {
const t = n ? e.sessionStore : void 0;
if (n && !t) throw new ToolInputError("Code Mode store/load is unavailable in headless execution; use an interactive session-bound cell.");
if (e.request.method === "resultSave") {
if (t) await t.save(r[2], r[0], e.runtime.hasNetworkContent());
else i = e.results.save(r[0], e.runtime.hasNetworkContent());
} else if (e.request.method === "resultLoad") {
if (!t) {
const t = e.results.load(r[0]);
if (t.networkContent) e.runtime.observeNetworkContent(e.parentToolCallId);
e.reply.settleJson(true, t.json);
return;
}
const n = await t.load(r[0]);
if (n.networkContent) e.runtime.observeNetworkContent(e.parentToolCallId);
i = n.value === void 0 ? {} : { value: n.value };
} else if (t) await t.delete(r[0]);
else i = e.results.delete(r[0]);
break;
}
case "search": {
const n = r[0];
if (typeof n !== "string") throw new ToolInputError("search query must be a string.");
const a = isRecord(r[1]) ? r[1] : void 0;
const o = n.trim();
const s = o.toLowerCase();
const c = e.namespaceRuntime.mcpBindings;
const l = [...c];
const u = (l.find(([, e]) => e.callableName === o) ?? l.find(([, e]) => e.callableName.toLowerCase() === s))?.[0];
const d = u ? void 0 : t.byCallableName.get(o) ?? t.bindings.find((e) => e.name === o) ?? t.bindings.find((e) => e.name.toLowerCase() === s || e.callableName.toLowerCase() === s);
const f = await e.runtime.search(d?.id ?? u ?? n, {
limit: typeof a?.limit === "number" ? a.limit : void 0,
allowedIds: t.searchableIds,
parentToolCallId: e.parentToolCallId
});
i = d ? [d.callableName] : f.map((e) => {
const n = t.byId.get(e.id);
if (n) return n.callableName;
const r = c.get(e.id);
if (!r) throw new ToolInputError("Search result has no callable namespace route.");
return {
callableName: r.callableName,
namespaceId: r.namespaceId,
path: r.path,
apiPath: r.apiPath,
name: e.mcp?.toolName ?? e.name,
source: "mcp",
description: truncateUtf16Safe(e.description, 512),
instructions: e.mcp?.instructions,
instructionsHint: e.instructionsHint ? CODE_MODE_INSTRUCTIONS_HINT : void 0
};
});
break;
}
case "describe": {
const t = catalogBinding(r[0], "describe");
const { id: n, sourceName: a, mcp: o, ...s } = await e.runtime.describe(t.id, {
includeMcp: false,
recoverySurface: "catalog",
parentToolCallId: e.parentToolCallId
});
i = r[1] === "declaration" ? await createCodeModeToolApiFile(t.callableName, s) : {
...s,
callableName: t.callableName
};
break;
}
case "callValue": {
const t = catalogBinding(r[0], "catalog");
let n = r[1] ?? {};
if (t.id === "openclaw:core:exec" && isRecord(n) && n.background !== true && e.completionRequired) n = {
...n,
awaitResults: true
};
else if (t.source === "openclaw" && t.name === "exec" && t.input?.includes("yieldMs") === true && isRecord(n) && n.background !== true && n.yieldMs === void 0) n = {
...n,
yieldMs: Math.max(1, Math.floor(e.remainingMs) - 500)
};
if (t.id === "openclaw:core:agents_wait" && e.completionRequired && isRecord(n) && n.timeoutSeconds === void 0) n = {
...n,
awaitResults: true
};
i = await e.runtime.callExactValue(t.id, n, callOptions());
break;
}
case "nodes":
i = await runNodesBridge(e);
break;
case "yield":
i = {
status: "yielded",
reason: r[0] ?? null
};
break;
case "namespace": {
const t = r[0];
const n = r[1];
const a = r[2];
if (typeof t !== "string") throw new ToolInputError("namespace id must be a string.");
if (!Array.isArray(n) || !n.every((e) => typeof e === "string")) throw new ToolInputError("namespace path must be an array of strings.");
i = await e.namespaceRuntime.invoke(t, n, Array.isArray(a) ? a : [], async (t) => {
const n = await e.runtime.callExactId(t.catalogId, t.input, {
...callOptions(),
mcpNamespaceGuest: true
});
const r = consumeMcpCodeModeGuestResult(n.result);
if (r === void 0) throw new ToolInputError("MCP namespace tool result is missing its owned guest projection.");
return r;
});
if (t === "mcp" && n.at(-1) === "$api") e.runtime.observeNetworkContent(e.parentToolCallId);
break;
}
case "agentSpawn":
case "agentWait":
case "swarmNote": {
const { signal: t } = e;
requireCodeModeSwarmEnabled(e.ctx);
t?.throwIfAborted();
const n = await loadSwarmHandlers();
t?.throwIfAborted();
requireCodeModeSwarmEnabled(e.ctx);
i = await n[e.request.method](e);
break;
}
case "skillsList": {
if (!t.bindings.some((e) => e.source === "openclaw" && e.name === "skills_search")) throw new ToolInputError("skills_search is not available in this run.");
if (e.ctx.toolExecutionAllow && !isToolExecutionAllowed(e.ctx.toolExecutionAllow, "skills_search")) throw new ToolInputError(formatToolExecutionGatedMessage("skills_search", e.ctx.toolExecutionAllow));
const n = r[0] ?? 0;
if (typeof n !== "number" || !Number.isSafeInteger(n) || n < 0) throw new ToolInputError("skills.list offset must be a non-negative integer.");
i = (e.ctx.codeModeSkills ?? []).slice(n, n + 20).map(({ name: e, description: t, location: n }) => ({
name: e,
description: truncateUtf16Safe(t, 512),
location: n
}));
break;
}
case "skillsSearch":
case "skillsRead": {
const n = e.request.method === "skillsRead" ? "skills_read" : "skills_search";
const a = t.bindings.find((e) => e.source === "openclaw" && e.name === n);
if (!a) throw new ToolInputError(`${n} is not available in this run.`);
const o = (await e.runtime.callExactId(a.id, e.request.method === "skillsRead" ? { name: r[0] } : {
query: r[0],
...r[1] === void 0 ? {} : { limit: r[1] }
}, callOptions())).result;
if (!isRecord(o) || o.isError || !isRecord(o.details)) {
const e = isRecord(o) && isRecord(o.details) ? o.details : void 0;
const t = e?.error ?? e?.message;
const n = typeof t === "string" ? t : o.content.find((e) => e.type === "text")?.text;
throw new Error(`Installed skill request failed: ${truncateUtf16Safe(redactToolPayloadText(n || "missing structured result details"), 1024)}`);
}
if (e.request.method === "skillsRead") {
const { name: e, location: t, locationNote: n, content: r } = o.details;
if (typeof e !== "string" || typeof t !== "string" || typeof r !== "string" || n !== void 0 && typeof n !== "string") throw new ToolInputError("Installed skill instructions are unavailable.");
i = formatSkillInstructions({
name: e,
location: t,
locationNote: n,
content: r
});
} else i = o.details;
break;
}
case "sleep": {
const t = r[0];
if (typeof t !== "number" || !Number.isFinite(t) || t < 0) throw new ToolInputError("setTimeout delay must be a non-negative finite number.");
i = await setTimeout$1(resolveSafeTimeoutDelayMs(t, { minMs: 0 }), null, { signal: e.signal });
break;
}
}
e.reply.settle(true, i);
} catch (r) {
const i = getBeforeToolCallFailureDisposition(r) !== void 0 && r instanceof Error ? r.cause ?? r : r;
const a = n && r instanceof RangeError ? "store_range" : n && r instanceof TypeError ? "store_type" : getToolContractFailureCode(i) ?? (isTrustedToolInputError(i) ? "invalid_input" : "tool_error");
logCodeModeFailure(r, {
sessionId: e.ctx.sessionId,
sessionKey: e.ctx.sessionKey,
runId: e.ctx.runId,
toolCallId: e.parentToolCallId,
codeModeRunId: e.activeRunId,
workerId: e.workerId,
failurePhase: "bridge",
failureCode: a,
bridgeDispatchStarted: true,
bridgeRequestId: e.request.id,
bridgeMethod: e.request.method
});
e.reply.settle(false, {
message: redactCodeModeCatalogIds(formatErrorMessage(r), t.bindings),
code: a,
effectStatus: "unknown"
});
}
}
//#endregion
//#region src/agents/agent-run-approval-wait.ts
function observeAgentRunApprovalWait(e) {
const t = /* @__PURE__ */ new Set();
let n = 0;
let r = 0;
let unsubscribe = () => {};
const i = {
pending: false,
get pausedMs() {
return r + (i.pending ? performance.now() - n : 0);
},
dispose: () => {
unsubscribe();
i.onChange = void 0;
}
};
if (!e.runId) return i;
unsubscribe = onAgentEventForRun(e.runId, (a) => {
if (a.stream !== "lifecycle" || e.sessionId && a.sessionId && a.sessionId !== e.sessionId) return;
const o = a.data.approvalId;
if (typeof o !== "string" || !o) return;
if (a.data.phase === "waiting-approval") t.add(o);
else if (a.data.phase === "approval-resolved") t.delete(o);
else return;
const s = t.size > 0;
if (s === i.pending) return;
if (s) n = performance.now();
else r += performance.now() - n;
i.pending = s;
i.onChange?.(s);
});
return i;
}
//#endregion
//#region src/agents/code-mode-program-data.ts
const INBOX_FULL_JSON = JSON.stringify("Code Mode program-data budget exceeded. Paginate or narrow the tool request, or consume pending replies before requesting more data.");
const CANCELED_JSON = JSON.stringify("Code Mode tool canceled.");
/** Logical encoded-JSON allowance, not a bound on host RSS or guest memory. */
var CodeModeProgramDataInbox = class {
constructor(e) {
this.bytes = 0;
this.closed = false;
this.closers = /* @__PURE__ */ new Set();
this.maxBytes = Math.min(e.memoryLimitBytes, e.maxSnapshotBytes);
this.errorBytes = Math.min(e.maxOutputBytes, this.maxBytes);
}
createReply(e) {
let t = "pending";
let n;
let r = 0;
const clearPayload = () => {
if (n) n.json = "";
n = void 0;
this.bytes -= r;
r = 0;
};
const release = () => {
if (t === "released") return;
clearPayload();
t = "released";
this.closers.delete(close);
};
const close = () => {
if (t !== "delivering") release();
};
const i = {
settle: (e, n) => {
if (this.closed || t !== "pending") return;
i.settleJson(e, stringifyCodeModeJsonSafe(e ? n : normalizeReplyError(n, this.errorBytes)));
},
settleJson: (i, a) => {
if (this.closed || t !== "pending") return;
const o = Buffer.byteLength(a, "utf8");
if (o > this.maxBytes - this.bytes) n = {
id: e,
ok: false,
json: INBOX_FULL_JSON
};
else {
r = o;
this.bytes += r;
n = {
id: e,
ok: i,
json: a
};
}
t = "ready";
},
take: () => {
if (t !== "ready" && t !== "canceled" || !n) throw new Error("Code Mode reply is unavailable.");
t = "delivering";
return n;
},
release,
cancel: () => {
if (this.closed) {
close();
return;
}
if (t !== "pending" && t !== "ready") return;
clearPayload();
n = {
id: e,
ok: false,
json: CANCELED_JSON
};
t = "canceled";
}
};
if (this.closed) release();
else this.closers.add(close);
return i;
}
close() {
if (this.closed) return;
this.closed = true;
for (const e of this.closers) e();
}
};
function normalizeReplyError(e, t) {
if (e !== null && typeof e === "object" && "message" in e && "code" in e) return {
message: boundCodeModeError(String(e.message), t),
code: String(e.code),
effectStatus: "unknown"
};
return boundCodeModeError(String(e), t);
}
//#endregion
//#region src/agents/code-mode-state.ts
const MAX_ACTIVE_CODE_MODE_RUNS = 64;
const MAX_AGENT_WAIT_SNAPSHOT_TTL_WINDOWS = 4;
const BRIDGE_CLOSED_MESSAGE = "Code Mode tool canceled, expired, or owner lost; start a new run.";
const log = createSubsystemLogger("agents/code-mode");
const activeRuns = /* @__PURE__ */ new Map();
const resumingRunIds = /* @__PURE__ */ new Set();
const liveRunOwners = /* @__PURE__ */ new Set();
let activeRunReservations = 0;
let nextPendingBridgeSettlementSequence = 0;
let activeRunExpiryTimer;
/** Catalog ownership spans worker legs and continuations; parking never closes the cell. */
function createCodeModeRunOwner(e, t, n = false, r = false) {
let i = n;
const a = new CodeModeProgramDataInbox(t);
const o = captureAgentPluginRuntimeRefresh().hold();
const s = `cm_${randomUUID()}`;
const c = new AbortController();
const l = observeAgentRunApprovalWait(e);
const u = e.abortSignal ? AbortSignal.any([c.signal, e.abortSignal]) : c.signal;
const d = r ? createCodeModeSessionStoreAccess(e, u) : void 0;
const f = e.catalogRef ? e.catalogRef.onDispose ??= /* @__PURE__ */ new Set() : void 0;
let releaseCall = () => {};
let p;
let m;
const h = /* @__PURE__ */ new Set();
const g = createPendingPromiseTracker(h);
const _ = /* @__PURE__ */ new Map();
const v = /* @__PURE__ */ new Map();
const disposeContinuation = (e) => {
const t = _.get(e);
if (t) return t;
const n = Promise.resolve().then(() => e.dispose());
_.set(e, n);
n.then(() => {
_.delete(e);
v.delete(e);
}, (t) => {
v.set(e, t);
_.delete(e);
});
return n;
};
const retainContinuation = async (e) => {
const t = p;
p = u.aborted ? void 0 : e;
const n = [];
if (t && t !== p) n.push(disposeContinuation(t));
if (u.aborted && e && e !== t) n.push(disposeContinuation(e));
const r = await Promise.allSettled(n);
throwSettledAggregate(r, "Code Mode continuation cleanup failed");
};
const close = (e) => {
if (m) return m;
const t = createDeferredCore();
m = t.promise;
m.catch((e) => {
log.error("Code Mode cleanup failed", {
runId: s,
error: formatErrorMessage(e),
failures: [...v.values()].map(formatErrorMessage)
});
});
if (!c.signal.aborted) {
releaseCall();
l.dispose();
u.removeEventListener("abort", onLifetimeAbort);
f?.delete(onCatalogDispose);
c.abort(e);
a.close();
d?.close();
const t = activeRuns.get(s);
if (t?.owner === y) {
activeRuns.delete(s);
cancelPendingBridgeStates(t.pending);
}
scheduleActiveRunExpiry();
}
for (const e of v.keys()) disposeContinuation(e);
const n = p;
p = void 0;
if (n) disposeContinuation(n);
Promise.resolve().then(async () => {
await Promise.allSettled(h);
while (_.size) await Promise.allSettled(_.values());
if (v.size) throw new PluginRuntimeCloseRetainedError(new AggregateError(v.values(), "Code Mode continuation cleanup failed"));
o();
liveRunOwners.delete(y);
}).then(t.resolve, (e) => {
m = void 0;
t.reject(e);
});
return m;
};
const onLifetimeAbort = () => {
close(u.reason);
};
const onCatalogDispose = () => {
close();
};
const y = {
get completionRequired() {
return i;
},
requireCompletion() {
u.throwIfAborted();
i = true;
},
runId: s,
signal: u,
inbox: a,
results: createCodeModeResultsAccess(e, t),
sessionStore: d,
close,
retainContinuation,
runExecution(e) {
const t = Promise.resolve().then(() => {
u.throwIfAborted();
return e();
}).then(async (e) => {
await retainContinuation(e.status === "waiting" ? e.continuation : void 0);
return e;
});
return g(t);
},
approvalWait: l,
releaseCall() {
releaseCall();
},
bindCall(e) {
releaseCall();
if (u.aborted) return u;
const t = e ? AbortSignal.any([u, e]) : u;
const release = () => t.removeEventListener("abort", onAbort);
const onAbort = () => {
if (releaseCall === release) close(t.reason);
};
releaseCall = release;
t.addEventListener("abort", onAbort, { once: true });
if (t.aborted) onAbort();
return u;
}
};
liveRunOwners.add(y);
f?.add(onCatalogDispose);
u.addEventListener("abort", onLifetimeAbort, { once: true });
if (!e.catalogRef?.current || u.aborted) close(u.reason);
return y;
}
function scheduleActiveRunExpiry() {
if (activeRunExpiryTimer) {
clearTimeout(activeRunExpiryTimer);
activeRunExpiryTimer = void 0;
}
let e = Number.POSITIVE_INFINITY;
for (const t of activeRuns.values()) e = Math.min(e, t.expiresAt);
if (!Number.isFinite(e)) return;
activeRunExpiryTimer = runInDetachedAsyncContext(() => setTimeout(() => {
activeRunExpiryTimer = void 0;
removeExpiredRuns();
scheduleActiveRunExpiry();
}, Math.max(1, e - performance.now())));
activeRunExpiryTimer.unref();
}
function removeExpiredRuns(e = Math.floor(performance.now())) {
for (const [t, n] of activeRuns) if (!isFutureDateTimestampMs(n.expiresAt, { nowMs: e })) {
if (n.pending?.some((e) => e.method === "agentWait" && !e.settled) && n.agentWaitRetainUntil !== void 0 && isFutureDateTimestampMs(n.agentWaitRetainUntil, { nowMs: e })) {
const t = resolveExpiresAtMsFromDurationSeconds(n.config.snapshotTtlSeconds, { nowMs: e });
if (t !== void 0) {
n.expiresAt = Math.min(t, n.agentWaitRetainUntil);
continue;
}
}
disposeCodeModeRun(t);
}
}
function disposeCodeModeRun(e) {
const t = activeRuns.get(e);
activeRuns.delete(e);
t?.owner.close();
cancelPendingBridgeStates(t?.pending ?? []);
resumingRunIds.delete(e);
scheduleActiveRunExpiry();
}
/** Cancel every cell before its Gateway-owned runtimes disappear. */
async function disposeAllCodeModeRuns() {
const e = [...liveRunOwners].map((e) => e.close());
activeRuns.clear();
resumingRunIds.clear();
scheduleActiveRunExpiry();
const t = await Promise.allSettled(e);
throwSettledAggregate(t, "Code Mode runs failed to close");
}
/** Abort each bridge call whose result has not already reached its guest. */
function cancelPendingBridgeStates(e) {
for (const t of e) if (t.settled) t.reply.release();
else t.cancel?.();
}
/** Apply restored-guest cancellation to the parent-owned host operations. */
function cancelPendingBridgeStatesById(e, t) {
if (t.length === 0) return;
const n = new Set(t);
const r = e.filter((e) => n.has(e.id));
cancelPendingBridgeStates(r);
for (const e of r) e.reply.release();
e.splice(0, e.length, ...e.filter((e) => !n.has(e.id)));
}
/** Deliver bridge responses in actual settlement order, not request order. */
function takeSettledBridgeRequests(e) {
const t = e.filter((e) => e.settled).toSorted((e, t) => (e.settledSequence ?? 0) - (t.settledSequence ?? 0)).map((e) => e.reply);
const n = [];
const release = () => {
for (const e of t) e.release();
t.length = 0;
n.length = 0;
};
try {
for (const e of t) n.push(e.take());
return {
requests: n,
release
};
} catch (e) {
release();
throw e;
}
}
/** Keep every dispatched bridge call required until its guest has received the result. */
function pendingBridgeStatesForSettlement(e, t) {
if (t.kind === "awaiting") return e;
const n = new Set(t.requiredRequestIds);
return e.filter((e) => n.has(e.id));
}
/** Await the shared guest frontier without guessing native Promise ownership. */
function waitForPendingBridgeSettlement(e, t, n) {
const r = pendingBridgeStatesForSettlement(e, t);
const i = r.filter((e) => !e.settled);
if (n?.aborted || i.length === 0 || t.kind === "awaiting" && i.length !== r.length) return Promise.resolve();
return new Promise((e) => {
const finish = () => {
for (const e of i) e.onSettlement = void 0;
n?.removeEventListener("abort", finish);
e();
};
const onSettlement = () => {
if (t.kind === "awaiting" || i.every((e) => e.settled)) finish();
};
for (const e of i) e.onSettlement = onSettlement;
n?.addEventListener("abort", finish, { once: true });
});
}
function hasAvailableCodeModeRunSlot() {
removeExpiredRuns();
return activeRuns.size + activeRunReservations < MAX_ACTIVE_CODE_MODE_RUNS;
}
function reserveActiveRunSlot(e) {
if (e === void 0) {
if (!hasAvailableCodeModeRunSlot()) throw new ToolInputError("too many suspended code mode runs. Resume an existing run with wait, or use exec with awaitResults:true to collect an existing tool result without suspending. Do not repeat already-dispatched work.");
} else {
if (!activeRuns.get(e)) throw new ToolInputError("code mode run is unavailable or expired.");
activeRuns.delete(e);
scheduleActiveRunExpiry();
}
activeRunReservations += 1;
let t = false;
return () => {
if (t) return;
t = true;
activeRunReservations = Math.max(0, activeRunReservations - 1);
};
}
function createPendingBridgeStates(e, t) {
return e.map((e) => {
const n = t.inbox.createReply(e.id);
const r = new AbortController();
const i = r.signal;
const onAbort = () => {
n.cancel();
r.abort(t.signal.reason);
};
t.signal.addEventListener("abort", onAbort, { once: true });
if (t.signal.aborted) onAbort();
if (e.method !== "sleep") t.bridgeDispatch.started = true;
const a = runBridgeRequest({
activeRunId: t.activeRunId,
workerId: t.bridgeDispatch.workerId,
runtime: t.runtime,
results: t.results,
sessionStore: t.sessionStore,
catalogProjection: t.catalogProjection,
namespaceRuntime: t.namespaceRuntime,
parentToolCallId: t.parentToolCallId,
codeModeRunId: t.codeModeRunId,
reply: n,
remainingMs: Math.max(1, t.remainingMs),
completionRequired: t.completionRequired,
ctx: t.ctx,
request: e,
signal: i,
onUpdate: t.onUpdate
});
const o = raceWithAbortSignal(a, i).catch(() => {
n.settle(false, BRIDGE_CLOSED_MESSAGE);
});
const s = {
...e,
reply: n,
cancel: () => {
n.cancel();
r.abort(/* @__PURE__ */ new Error(BRIDGE_CLOSED_MESSAGE));
}
};
o.then(() => {
t.signal.removeEventListener("abort", onAbort);
s.settledSequence = ++nextPendingBridgeSettlementSequence;
s.settled = true;
s.cancel = void 0;
s.args = [];
if (s.method === "agentWait" && t.activeRunId) {
const e = activeRuns.get(t.activeRunId);
if (e?.pending.includes(s)) {
const t = resolveExpiresAtMsFromDurationSeconds(e.config.snapshotTtlSeconds, { nowMs: Math.floor(performance.now()) });
if (t !== void 0) {
e.expiresAt = t;
scheduleActiveRunExpiry();
}
}
}
s.onSettlement?.();
s.onSettlement = void 0;
});
return s;
});
}
function storeSuspendedRun(e, t) {
const n = e.owner.runId;
if (e.owner.completionRequired && t === void 0) throw new ToolInputError("Required Code Mode work cannot publish an unfinished continuation.");
if (e.owner.signal.aborted) {
cancelPendingBridgeStates(e.pending);
return codeModeAbortedResult(e);
}
const r = Math.floor(performance.now());
const i = resolveExpiresAtMsFromDurationSeconds(e.config.snapshotTtlSeconds, { nowMs: r });
if (i === void 0) throw new ToolInputError("code mode run expiry is unavailable.");
const a = e.pending.some((e) => e.method === "agentWait" && !e.settled) ? resolveExpiresAtMsFromDurationSeconds(e.config.snapshotTtlSeconds * MAX_AGENT_WAIT_SNAPSHOT_TTL_WINDOWS, { nowMs: r }) : void 0;
const o = {
...e,
runId: n,
expiresAt: i,
agentWaitRetainUntil: a,
remainingRequiredBudgetMs: t
};
const s = e.output.takeResult({
status: "waiting",
runId: n,
reason: t === void 0 ? codeModeWaitingReason(e.pending) : "steering",
pendingToolCalls: pendingToolCalls(e.pending),
telemetry: telemetry(e.runtime)
}, {}, e.runtime.hasNetworkContent());
activeRuns.set(n, o);
scheduleActiveRunExpiry();
const c = recordCodeModeToolOutcome(s, s, e.pending);
e.owner.releaseCall();
return c;
}
function codeModeAbortedResult(e) {
return e.output.takeResult({
status: "failed",
code: "aborted",
failurePhase: e.bridgeDispatch.started ? "bridge" : "host",
bridgeDispatchStarted: e.bridgeDispatch.started,
telemetry: telemetry(e.runtime)
}, { error: "code mode execution aborted" }, e.runtime.hasNetworkContent());
}
function codeModeWaitingReason(e) {
return e.length > 0 && e.every((e) => e.method === "yield") ? "yield" : "pending_tools";
}
function pendingToolCalls(e) {
return e.filter((e) => !e.settled).map((e) => ({
id: e.id,
method: e.method
}));
}
function telemetry(e) {
return {
...e.telemetry(),
visibleTools: [CODE_MODE_EXEC_TOOL_NAME, CODE_MODE_WAIT_TOOL_NAME]
};
}
//#endregion
export { createCodeModeCatalogBindings as A, MAX_HEADLESS_WALL_CLOCK_MS as C, readRunId as D, readCode as E, resolveCodeModeConfig as O, DEFAULT_HEADLESS_WALL_CLOCK_MS as S, isCodeModeEngagedForModel as T, observeAgentRunApprovalWait as _, createCodeModeRunOwner as a, isCodeModeSwarmAvailable as b, hasAvailableCodeModeRunSlot as c, reserveActiveRunSlot as d, resumingRunIds as f, waitForPendingBridgeSettlement as g, telemetry as h, codeModeAbortedResult as i, createCodeModeCatalogProjection as j, toToolSearchConfig as k, pendingBridgeStatesForSettlement as l, takeSettledBridgeRequests as m, cancelPendingBridgeStates as n, createPendingBridgeStates as o, storeSuspendedRun as p, cancelPendingBridgeStatesById as r, disposeAllCodeModeRuns as s, activeRuns as t, removeExpiredRuns as u, CODE_MODE_NODES_TOOL_ID as v, createCodeModeApiFilesForRun as w, requiresCodeModeCompletion as x, codeModeReplayIdForToolCall as y };