UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

349 lines (348 loc) • 13.3 kB
import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { i as createAbortError } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { A as tryResolveLegacyCompatibilityAgentId, z as resolvePersistedSessionStoreOwnerForKey } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs"; import "./legacy.default-agent-owner-DpmHgK0A.mjs"; import { b as describeAgentsWaitTool } from "./tool-catalog-C1ALpCJD.mjs"; import { o as getGatewayToolCallerIdentity, t as captureGatewayToolCallerAssertion } from "./gateway-caller-context-BNidAW8G.mjs"; import { n as jsonResult } from "./tool-results-CcV0sxnb.mjs"; import { n as ToolInputError } from "./tool-input-error-B1hgavSw.mjs"; import "./common-njQNtpnW.mjs"; import { T as subscribeSubagentRunChanges } from "./subagent-registry-memory-lc6LBIFb.mjs"; import { P as matchesSubagentRequesterSession } from "./subagent-registry-state-CMZQXOjY.mjs"; import { v as capFrozenResultText } from "./subagent-completion-admission.store-u2yW_zMh.mjs"; import { _ as prepareSubagentRunsByRunIds } from "./subagent-registry-DXsif7FR.mjs"; import { m as resolveSubagentCompletionResultText } from "./subagent-announce-output-C5bKV6T0.mjs"; import { t as resolveSwarmConfig } from "./swarm-config-Dp8TTyRG.mjs"; import { s as markCollectorReaderTool } from "./swarm-collector-capability-BSHCyIjQ.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; import { setImmediate } from "node:timers/promises"; import { Value } from "typebox/value"; import { Type } from "typebox"; //#region src/agents/tools/agents-wait-tool.ts const MAX_WAIT_IDS = 1e3; const finalAnswerLoader = createLazyImportLoader(() => import("./subagent-announce-output-C6v66dMD.mjs")); const UNAVAILABLE_ANSWER_NOTICE = "\n\n[truncated: the complete child answer is unavailable; this is its 4,096-character preview]"; const AgentsWaitToolSchema = Type.Object({ ids: Type.Array(Type.String({ minLength: 1 }), { minItems: 1, maxItems: MAX_WAIT_IDS }), timeoutSeconds: Type.Optional(Type.Number({ minimum: 0 })), awaitResults: Type.Optional(Type.Boolean({ description: "Join required collector results until settlement or cancellation, without polling; mutually exclusive with timeoutSeconds. Child and agent budgets still apply." })) }); const CollectorCompletionSchema = Type.Object({ runId: Type.String(), status: Type.Union([ Type.Literal("done"), Type.Literal("failed"), Type.Literal("killed"), Type.Literal("timeout") ]), result: Type.String(), resultTruncated: Type.Optional(Type.Literal(true)), structured: Type.Optional(Type.Unknown()), error: Type.Optional(Type.String()), schemaError: Type.Optional(Type.String()), reason: Type.Optional(Type.Literal("yielded_without_result")), sessionKey: Type.String(), label: Type.Optional(Type.String()), groupId: Type.Optional(Type.String()), runtimeMs: Type.Optional(Type.Number({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })), usage: Type.Optional(Type.Object({ inputTokens: Type.Number(), outputTokens: Type.Number() }, { additionalProperties: false })) }, { additionalProperties: false }); const AgentsWaitOutputSchema = Type.Object({ completed: Type.Array(CollectorCompletionSchema), pending: Type.Array(Type.String()), errors: Type.Optional(Type.Array(Type.Object({ runId: Type.String(), error: Type.Union([Type.Literal("not_found"), Type.Literal("not_owner")]) }, { additionalProperties: false }))), success: Type.Optional(Type.Literal(false)) }, { additionalProperties: false }); const NATIVE_COLLECTOR_IDENTITY = Symbol.for("openclaw.nativeCollectorIdentity"); const nativeCollectorOwner = resolveGlobalSingleton(Symbol.for("openclaw.nativeSubagentCollectorOwner"), () => new AsyncLocalStorage()); function withNativeSubagentCollectorOwner(e, t, n, r) { const i = e[NATIVE_COLLECTOR_IDENTITY]; if (!i) throw new ToolInputError("Native collection requires its original collector tool."); return nativeCollectorOwner.run({ identity: i, toolCallId: t, owner: n }, r); } /** The finalized tool may return a policy denial instead of its declared output. */ function readNativeSubagentCollection(e) { if (!Value.Check(AgentsWaitOutputSchema, e)) { const t = asOptionalRecord(e); const n = t?.reason ?? t?.error; throw new ToolInputError(typeof n === "string" ? n : "Native subagent collection was not accepted."); } return e; } function ownsRun(e, { currentSessionKeys: t, currentAgentId: n, config: r, expectedRequester: i }) { if (i && !matchesSubagentRequesterSession(e, i)) return false; const a = e.swarmRequesterSessionKey?.trim(); if (!a) return false; return (e.swarmWaitOwnerSessionKeys && e.swarmWaitOwnerSessionKeys.length > 0 ? e.swarmWaitOwnerSessionKeys : [a]).some((i) => { if (!t.has(i)) return false; const a = parseAgentSessionKey(i)?.agentId ?? e.requesterAgentId ?? paramsOwner(r, i); return Boolean(a && (!n || a === n)); }); } function paramsOwner(e, t) { if (!e) return; const n = resolvePersistedSessionStoreOwnerForKey(e, t); return n.kind === "configured" ? n.agentId : n.kind === "none" ? tryResolveLegacyCompatibilityAgentId(e) : void 0; } function completionResult(e) { const t = e.collectorCompletion; if (!t) return; const n = (e.execution.endedAt ?? NaN) - (e.execution.startedAt ?? NaN); const r = Number.isFinite(n) && n >= 0 && n <= Number.MAX_SAFE_INTEGER ? n : void 0; return { runId: e.swarmRunId ?? e.runId, status: t.status, result: resolveSubagentCompletionResultText(e) ?? "", ...t.structured !== void 0 ? { structured: t.structured } : {}, ...e.execution.outcome?.status === "error" ? { error: e.execution.outcome.error } : {}, ...t.schemaError ? { schemaError: t.schemaError } : {}, ...t.reason ? { reason: t.reason } : {}, sessionKey: e.childSessionKey, ...e.label ? { label: e.label } : {}, ...e.groupId ? { groupId: e.groupId } : {}, ...r !== void 0 ? { runtimeMs: r } : {}, ...t.usage ? { usage: t.usage } : {} }; } /** * Lifecycle evidence keeps a 4,096-character reply preview. Return the run's complete * recorded answer instead, within the 100 KB bound frozen collector results already use. */ async function completeCollectorResult(e, t) { const n = t.completion?.terminalReply; if (n?.disposition !== "visible" || e.result !== n.text || !n.text.endsWith("…")) return e; const r = t.execution.outcome?.status === "ok" ? await finalAnswerLoader.load().then((e) => e.readSubagentRunFinalAnswer(t)).catch(() => void 0) : void 0; if (!r?.trim()) return { ...e, result: `${e.result}${UNAVAILABLE_ANSWER_NOTICE}`, resultTruncated: true }; const i = capFrozenResultText(r); return i === r.trim() ? { ...e, result: i } : { ...e, result: i, resultTruncated: true }; } /** Park one host bridge until its collector completes; registry writes wake it without polling. */ async function waitForCollectorCompletion(e) { const t = await waitForCollector({ ...e, ids: [e.runId], abortError: () => new ToolInputError("agents.run wait aborted.") }); const n = t.errors?.[0]; if (n) throw new ToolInputError(`agents.run ${n.error}: ${n.runId}`); return expectDefined(t.completed[0], "collector completion"); } function readWaitState(e, t, n) { const r = []; const i = []; const a = []; const o = []; for (const [s, c] of t.entries()) { const t = e.get(c); if (!t?.collect) { if (t?.expectsCompletionMessage && t.spawnMode !== "session" && n.currentSessionKeys.has(t.requesterSessionKey)) o.push(c); r.push({ runId: c, error: "not_found" }); continue; } if (!ownsRun(t, n)) { r.push({ runId: c, error: "not_owner" }); continue; } const l = completionResult(t); if (l) i.push({ result: l, entry: t, completedAt: t.completion?.capturedAt ?? t.execution.endedAt ?? Number.MAX_SAFE_INTEGER, inputIndex: s }); else a.push(c); } if (o.length === t.length) throw new ToolInputError(`agents_wait only collects runs started with collect=true. ${o.join(", ")} will report back to this session as a completion message; continue other work or end the turn instead of waiting.`); i.sort((e, t) => e.completedAt - t.completedAt || e.inputIndex - t.inputIndex); return { completed: i.map(({ result: e, entry: t }) => ({ result: e, entry: t })), pending: a, ...r.length > 0 ? { errors: r } : {} }; } async function waitForCollector(e) { const t = await waitForCollectorState(e); const n = await Promise.all(t.completed.map(({ result: e, entry: t }) => completeCollectorResult(e, t))); e.assertCurrent?.(); if (e.signal?.aborted) throw e.abortError(); return { ...t, completed: n }; } async function waitForCollectorState(e) { const t = getGatewayToolCallerIdentity()?.watchdogAttempt; const n = captureGatewayToolCallerAssertion(); const r = e.timeoutMs === void 0 ? void 0 : performance.now() + e.timeoutMs; let i; let a; let o; let s; const wake = () => { i = true; a?.(); }; const assertNotAborted = () => { e.assertCurrent?.(); if (e.signal?.aborted) throw e.abortError(); }; const c = subscribeSubagentRunChanges("persistence", wake); e.signal?.addEventListener("abort", wake, { once: true }); try { for (;;) { assertNotAborted(); i = false; let c; let l; try { c = (await prepareSubagentRunsByRunIds(e.ids)).consume((t) => { if (e.signal?.aborted) { l = e.abortError(); throw l; } e.assertCurrent?.(); return readWaitState(t, e.ids, e); }); } catch (t) { if (e.signal?.aborted && t !== l) { const n = e.abortError(); n.cause = t; throw n; } throw t; } assertNotAborted(); if (!c.ready) { await setImmediate(); continue; } const u = c.value; if (!e.waitForAll && u.completed.length > 0 || u.pending.length === 0 || r !== void 0 && performance.now() >= r) return u; if (i) { await setImmediate(); continue; } await new Promise((c) => { a = c; s = t?.beginWait({ kind: "runtime_owned", isCurrent: () => { if (a === void 0 || i || e.signal?.aborted) return false; e.assertCurrent?.(); n?.(); return true; } }); if (r !== void 0) o = setTimeout(c, Math.max(0, r - performance.now())); }); s?.close(); s = void 0; clearTimeout(o); o = void 0; a = void 0; } } finally { s?.close(); clearTimeout(o); c(); e.signal?.removeEventListener("abort", wake); } } function createAgentsWaitTool(e) { const t = Symbol("nativeCollector"); return markCollectorReaderTool({ [NATIVE_COLLECTOR_IDENTITY]: t, label: "Wait for Agents", name: "agents_wait", displaySummary: "Wait for collector children.", description: describeAgentsWaitTool(false), parameters: AgentsWaitToolSchema, outputSchema: AgentsWaitOutputSchema, execute: async (n, r, i) => { const a = r; if (!Array.isArray(a?.ids) || a.ids.some((e) => typeof e !== "string")) throw new ToolInputError("agents_wait ids must be an array of run id strings."); const o = nativeCollectorOwner.getStore(); return jsonResult(await collectNativeSubagentResults({ ...a, currentSessionKeys: new Set([e.runSessionKey, e.agentSessionKey].filter((e) => Boolean(e?.trim()))), currentAgentId: e.agentId, config: e.config, ...o?.identity === t && o.toolCallId === n ? o.owner : void 0, signal: i })); } }); } /** Native event-driven collector, with optional exact requester and effect-time authority. */ async function collectNativeSubagentResults(e) { e.assertCurrent?.(); const t = resolveSwarmConfig(e.config, e.currentAgentId); if (e.awaitResults !== void 0 && typeof e.awaitResults !== "boolean") throw new ToolInputError("agents_wait awaitResults must be a boolean."); if (e.awaitResults && e.timeoutSeconds !== void 0) throw new ToolInputError("agents_wait with awaitResults=true cannot also specify timeoutSeconds."); if (e.ids.length > MAX_WAIT_IDS) throw new ToolInputError(`agents_wait supports at most ${MAX_WAIT_IDS} ids.`); const n = [...new Set(e.ids.map((e) => e.trim()).filter(Boolean))]; if (n.length === 0) throw new ToolInputError("agents_wait requires at least one non-empty run id."); const r = e.currentSessionKeys; const i = asFiniteNumber(e.timeoutSeconds) ?? 30; const a = Math.min(Math.max(0, i), t.waitTimeoutSecondsMax); const o = await waitForCollector({ ids: n, currentSessionKeys: r, currentAgentId: e.currentAgentId, config: e.config, timeoutMs: e.awaitResults ? void 0 : a * 1e3, waitForAll: e.awaitResults, signal: e.signal, assertCurrent: e.assertCurrent, expectedRequester: e.expectedRequester, abortError: () => createAbortError("agents_wait aborted.") }); return o.completed.length === 0 && o.pending.length === 0 && Boolean(o.errors?.length) ? { ...o, success: false } : o; } //#endregion export { withNativeSubagentCollectorOwner as i, readNativeSubagentCollection as n, waitForCollectorCompletion as r, createAgentsWaitTool as t };