UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

430 lines (429 loc) • 15.6 kB
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; 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 { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { a as hasExecutionSettlement } from "./agent-run-terminal-outcome-CurjWZiA.mjs"; import "./agent-run-registry-D7vkrqFT.mjs"; import { m as onAgentEvent } from "./agent-events-BdfWYmot.mjs"; import { r as getAgentRunLifecycleGeneration } from "./agent-run-registry-state-BFfw9a4W.mjs"; import { c as mergeAgentRunTerminalOutcome, i as buildAgentRunTerminalOutcomeFromLifecycleEvent, n as buildAgentRunTerminalOutcome, o as isStickyAgentRunTerminalOutcome, t as AGENT_RUN_TERMINAL_RETRY_GRACE_MS } from "./agent-run-terminal-outcome-wduf2occ.mjs"; import { l as normalizeAgentRunTerminalReceipt, n as mergeAgentRunTerminalReplySnapshot, r as normalizeAgentRunTerminalReplySnapshot } from "./agent-run-terminal-reply-DXju8G9G.mjs"; import { r as formatErrorMessageForDisplay } from "./error-diagnostics-CD3FocGA.mjs"; import { t as setSafeTimeout } from "./timer-delay-DMmvi2s2.mjs"; import { t as isNonTerminalAgentRunStatus } from "./agent-run-status-nnt-rii7.mjs"; import { t as normalizeAgentRunTerminalDeliverySnapshot } from "./agent-run-terminal-delivery-BnDa4QGt.mjs"; //#region src/gateway/agent-turn/agent-job.ts const AGENT_RUN_CACHE_TTL_MS = 6e5; const AGENT_RUN_CACHE_MAX_ENTRIES = 5e3; const agentJobState = resolveGlobalSingleton(Symbol.for("openclaw.agentJobState"), () => ({ jobs: /* @__PURE__ */ new Map(), oldestCachedAt: Infinity, runStarts: /* @__PURE__ */ new Map(), pendingTerminals: /* @__PURE__ */ new Map(), waiters: /* @__PURE__ */ new Map(), version: 0 }), (e) => { for (const t of e.pendingTerminals.values()) clearTimeout(t.timer); e.jobs.clear(); e.oldestCachedAt = Infinity; e.runStarts.clear(); e.pendingTerminals.clear(); const t = Array.from(e.waiters.values()).flatMap((e) => Array.from(e)); e.waiters.clear(); for (const e of t) e(true); }); const agentJobs = agentJobState.jobs; const agentRunStarts = agentJobState.runStarts; const pendingAgentRunTerminals = agentJobState.pendingTerminals; const agentRunWaiters = agentJobState.waiters; let agentRunListenerStarted = false; function captureAgentJobSession(e) { if (!e?.sessionKey || !e.sessionId || !e.lifecycleGeneration) return; return { sessionKey: e.sessionKey, sessionId: e.sessionId, agentId: e.agentId, lifecycleGeneration: e.lifecycleGeneration }; } /** Retained routing locates a current sharing check; it never keeps execution authority alive. */ function getAgentJobSession(e, t) { pruneAgentRunCache(); const n = agentJobs.get(e); const r = (n && getCanonicalAgentRunSnapshot(n.snapshotsBySource, t)?.session) ?? (t ? void 0 : pendingAgentRunTerminals.get(e)?.snapshot.session); return r?.lifecycleGeneration === getAgentRunLifecycleGeneration() ? r : void 0; } function nextAgentRunVersion() { agentJobState.version += 1; return agentJobState.version; } function pruneAgentRunCache(e = Date.now()) { if (e - agentJobState.oldestCachedAt <= AGENT_RUN_CACHE_TTL_MS) return; let t = Infinity; for (const [n, r] of agentJobs) { if (e - r.cachedAt <= AGENT_RUN_CACHE_TTL_MS) { t = Math.min(t, r.cachedAt); continue; } agentJobs.delete(n); } agentJobState.oldestCachedAt = t; } function enforceAgentRunCacheMaxEntries() { if (agentJobs.size <= AGENT_RUN_CACHE_MAX_ENTRIES) return; const e = agentJobs.size - AGENT_RUN_CACHE_MAX_ENTRIES; let t = 0; for (const n of agentJobs.keys()) { if (t >= e) break; if ((agentRunWaiters.get(n)?.size ?? 0) > 0) continue; agentJobs.delete(n); t += 1; } } function shouldPreserveTerminalSnapshot(e, t) { const n = buildAgentRunTerminalOutcome(e); const r = buildAgentRunTerminalOutcome(t); return mergeAgentRunTerminalOutcome(n, r) === n; } function sameAgentJobSession(e, t) { return e?.sessionKey === t?.sessionKey && e?.sessionId === t?.sessionId && e?.agentId === t?.agentId && e?.lifecycleGeneration === t?.lifecycleGeneration; } function mergeSnapshot(e, t) { if (!e) return t; const n = shouldPreserveTerminalSnapshot(e, t) ? e : t; if (!sameAgentJobSession(e.session, t.session)) return n; const r = mergeAgentRunTerminalReplySnapshot(e.terminalReply, t.terminalReply); const i = t.terminalDelivery ?? e.terminalDelivery; const a = t.terminalReceipt ?? e.terminalReceipt; return { ...n, ...i ? { terminalDelivery: i } : {}, ...a ? { terminalReceipt: a } : {}, ...r ? { terminalReply: r } : {}, cachedAt: t.cachedAt, recordedAt: t.recordedAt, version: t.version }; } function recordAgentRunSnapshot(e, t = nextAgentRunVersion()) { const n = { ...e, cachedAt: Date.now(), version: t }; pruneAgentRunCache(n.cachedAt); const r = agentJobs.get(n.runId)?.snapshotsBySource ?? /* @__PURE__ */ new Map(); const i = mergeSnapshot(r.get(n.source), n); r.set(n.source, i); agentJobs.set(n.runId, { cachedAt: n.cachedAt, snapshotsBySource: r }); agentJobState.oldestCachedAt = Math.min(agentJobState.oldestCachedAt, n.cachedAt); enforceAgentRunCacheMaxEntries(); for (const e of agentRunWaiters.get(n.runId) ?? []) e(); } function clearPendingAgentRunTerminals(e) { clearTimeout(pendingAgentRunTerminals.get(e)?.timer); pendingAgentRunTerminals.delete(e); } function beginAgentJob(e, t) { nextAgentRunVersion(); clearPendingAgentRunTerminals(e); agentJobs.delete(e); if (t !== void 0) agentRunStarts.set(e, t); } function mergePendingAgentRunTerminal(e) { const t = pendingAgentRunTerminals.get(e.runId)?.snapshot; return t && shouldPreserveTerminalSnapshot(t, e) ? t : e; } function schedulePendingAgentRunTerminal(e, t) { const n = mergePendingAgentRunTerminal(t); if (n !== t) { n.version = t.version; return; } const r = pendingAgentRunTerminals.get(t.runId)?.phase === "end"; clearPendingAgentRunTerminals(t.runId); const i = setSafeTimeout(() => { const e = pendingAgentRunTerminals.get(t.runId); if (!e || e.timer !== i) return; if (e.phase === "error" && !r && buildAgentRunTerminalOutcome(e.snapshot).reason === "failed" && agentRunWaiters.has(t.runId)) { e.timer = void 0; return; } pendingAgentRunTerminals.delete(t.runId); recordAgentRunSnapshot(e.snapshot, e.snapshot.version); }, AGENT_RUN_TERMINAL_RETRY_GRACE_MS).unref(); pendingAgentRunTerminals.set(t.runId, { phase: e, snapshot: t, timer: i }); } function createPendingErrorTimeoutSnapshot(e) { return { status: "timeout", startedAt: e.startedAt, error: e.error, pendingError: true, session: e.session, ...e.providerStarted !== void 0 ? { providerStarted: e.providerStarted } : {}, ...e.terminalDelivery ? { terminalDelivery: e.terminalDelivery } : {} }; } function createSnapshotFromLifecycleEvent(e) { const { runId: t, phase: n, data: r } = e; const i = typeof r?.startedAt === "number" ? r.startedAt : agentRunStarts.get(t); const a = typeof r?.endedAt === "number" ? r.endedAt : void 0; const o = buildAgentRunTerminalOutcomeFromLifecycleEvent({ phase: n, data: r, startedAt: i, endedAt: a }); const s = !hasExecutionSettlement(r) && o.reason === "aborted" && r?.stopReason == null && r?.status == null; const c = normalizeAgentRunTerminalDeliverySnapshot(r?.terminalDelivery); const l = normalizeAgentRunTerminalReplySnapshot(r?.terminalReply); const u = normalizeAgentRunTerminalReceipt(r?.terminalReceipt); const d = u?.runId === t ? u : void 0; return { runId: t, source: "lifecycle", session: e.session, recordedAt: Date.now(), status: s ? "timeout" : o.status, startedAt: i, endedAt: a, error: s ? void 0 : o.error, stopReason: s ? void 0 : o.stopReason, livenessState: o.livenessState, ...r?.yielded === true ? { yielded: true } : {}, ...o.timeoutPhase ? { timeoutPhase: o.timeoutPhase } : {}, ...o.providerStarted !== void 0 ? { providerStarted: o.providerStarted } : {}, ...c ? { terminalDelivery: c } : {}, ...l ? { terminalReply: l } : {}, ...d ? { terminalReceipt: d } : {}, version: nextAgentRunVersion() }; } function ensureAgentRunListener() { if (agentRunListenerStarted) return; agentRunListenerStarted = true; onAgentEvent((e) => { if (!e || e.stream !== "lifecycle") return; const t = e.data?.phase; if (t === "start") { const t = typeof e.data?.startedAt === "number" ? e.data.startedAt : Date.now(); beginAgentJob(e.runId, t); return; } if (t !== "end" && t !== "error") return; const n = createSnapshotFromLifecycleEvent({ runId: e.runId, phase: t, data: e.data, session: captureAgentJobSession(e) }); agentRunStarts.delete(e.runId); if (!hasExecutionSettlement(e.data) && (t === "error" ? e.data?.fallbackExhaustedFailure !== true : n.status === "timeout")) { schedulePendingAgentRunTerminal(t, n); return; } const r = mergePendingAgentRunTerminal(n); clearPendingAgentRunTerminals(e.runId); recordAgentRunSnapshot(r, n.version); }); } function parseDedupeObservation(e, t) { const n = asOptionalRecord(e.payload); const r = typeof n?.status === "string" ? n.status : void 0; if (isNonTerminalAgentRunStatus(r)) return { state: "active" }; const i = r === "completed" ? "ok" : r === "ok" || r === "timeout" || r === "error" ? r : e.ok ? void 0 : "error"; if (!i) return { state: "untracked" }; const a = asOptionalRecord(asOptionalRecord(n?.result)?.meta); const o = normalizeAgentRunTerminalReplySnapshot(n?.terminalReply ?? a?.terminalReply); const s = asFiniteNumber(n?.startedAt) ?? t?.startedAt; const c = asFiniteNumber(n?.endedAt) ?? (i === "ok" && t?.status === "ok" ? t.endedAt : void 0) ?? e.ts; const l = readNonBlankString(n?.stopReason) ?? readNonBlankString(a?.stopReason); const u = readNonBlankString(n?.livenessState) ?? readNonBlankString(a?.livenessState); const d = typeof n?.error === "string" ? n.error : typeof n?.summary === "string" ? n.summary : e.error?.message; const f = buildAgentRunTerminalOutcome({ status: i, startedAt: s, endedAt: c, error: d === void 0 ? void 0 : formatErrorMessageForDisplay(e.error, d), stopReason: l, livenessState: u, timeoutPhase: n?.timeoutPhase ?? a?.timeoutPhase, providerStarted: n?.providerStarted ?? a?.providerStarted }); return { state: "terminal", snapshot: { status: f.status, startedAt: s, endedAt: c, error: f.status === "ok" ? void 0 : f.error, stopReason: l, livenessState: u, ...n?.yielded === true || a?.yielded === true ? { yielded: true } : {}, ...f.timeoutPhase ? { timeoutPhase: f.timeoutPhase } : {}, ...f.providerStarted !== void 0 ? { providerStarted: f.providerStarted } : {}, ...o ? { terminalReply: o } : {} } }; } function parseDedupeKey(e) { const t = e.indexOf(":"); if (t === -1) return; const n = e.slice(0, t); const r = e.slice(t + 1); if (n !== "agent" && n !== "chat" || !r) return; return { runId: r, source: n }; } function setGatewayDedupeEntry(e) { pruneAgentRunCache(); const t = parseDedupeKey(e.key); const n = t && agentJobs.get(t.runId)?.snapshotsBySource.get("lifecycle"); const r = n && sameAgentJobSession(n.session, e.session) ? n : void 0; const i = e.dedupe.get(e.key); const a = i ? parseDedupeObservation(i) : void 0; const o = parseDedupeObservation(e.entry, r); const s = a?.state === "terminal" ? buildAgentRunTerminalOutcome(a.snapshot) : void 0; const c = o.state === "terminal" ? buildAgentRunTerminalOutcome(o.snapshot) : void 0; if (s && isStickyAgentRunTerminalOutcome(s) && !(e.startNewAttempt && o.state === "active") && (!c || mergeAgentRunTerminalOutcome(s, c) === s)) return; const l = i?.requestIdentity ? { ...e.entry, requestIdentity: i.requestIdentity } : e.entry; e.dedupe.set(e.key, l); if (!t) return; if (o.state === "active") { beginAgentJob(t.runId); for (const e of agentRunWaiters.get(t.runId) ?? []) e(); return; } if (o.state === "terminal") { if (t.source === "chat" && o.snapshot.status === "ok" && n?.status === "ok" && n.yielded === true) { o.snapshot.yielded = true; o.snapshot.livenessState = n.livenessState; } recordAgentRunSnapshot({ ...o.snapshot, runId: t.runId, source: t.source, session: e.session ? { ...e.session } : void 0, recordedAt: e.entry.ts }); } } function mergeAgentRunSnapshotsByFreshness(e, t, n) { if (!e || !t) return e ?? t; return t[n] > e[n] ? mergeSnapshot(e, t) : mergeSnapshot(t, e); } function getCanonicalAgentRunSnapshot(e, t) { const n = t ? e.get(t) : mergeAgentRunSnapshotsByFreshness(e.get("agent"), e.get("chat"), "recordedAt"); if (t && !n) return; return mergeAgentRunSnapshotsByFreshness(e.get("lifecycle"), n, "version"); } function getAgentRunSnapshot(e) { pruneAgentRunCache(); const t = agentJobs.get(e.runId); return t ? getCanonicalAgentRunSnapshot(t.snapshotsBySource, e.source) : void 0; } function addAgentRunWaiter(e, t) { const n = agentRunWaiters.get(e) ?? /* @__PURE__ */ new Set(); n.add(t); agentRunWaiters.set(e, n); return () => { n.delete(t); if (n.size === 0) { agentRunWaiters.delete(e); const t = pendingAgentRunTerminals.get(e); if (t?.phase === "error" && !t.timer) { pendingAgentRunTerminals.delete(e); recordAgentRunSnapshot(t.snapshot, t.snapshot.version); } } }; } function projectAgentJobObservation(e) { return { session: e.session, status: e.status, startedAt: e.startedAt, endedAt: e.endedAt, error: e.error, stopReason: e.stopReason, livenessState: e.livenessState, yielded: e.yielded, pendingError: e.pendingError, timeoutPhase: e.timeoutPhase, providerStarted: e.providerStarted, ...e.terminalDelivery ? { terminalDelivery: e.terminalDelivery } : {}, terminalReceipt: e.terminalReceipt, terminalReply: e.terminalReply }; } async function waitForAgentJob(e) { ensureAgentRunListener(); const t = getAgentRunSnapshot(e); if (t) return projectAgentJobObservation(t); const n = getAsyncWorkSignal(); if (e.timeoutMs <= 0 || n?.aborted) return null; return await new Promise((t) => { let r = false; let removeWaiter = () => {}; const finish = (e) => { if (r) return; r = true; clearTimeout(i); n?.removeEventListener("abort", onClose); removeWaiter(); t(e); }; const onClose = () => finish(null); const onWake = (t = false) => { if (t) { finish({ status: "timeout", timeoutPhase: "gateway_draining" }); return; } if (e.stopWaiting?.()) { finish(null); return; } const n = getAgentRunSnapshot(e); if (n) finish(projectAgentJobObservation(n)); }; removeWaiter = addAgentRunWaiter(e.runId, onWake); const i = setSafeTimeout(() => { if (!e.source) { const t = pendingAgentRunTerminals.get(e.runId); const n = t?.snapshot; if (t?.phase === "error") { finish(!t.timer || isStickyAgentRunTerminalOutcome(buildAgentRunTerminalOutcome(t.snapshot)) ? projectAgentJobObservation(t.snapshot) : createPendingErrorTimeoutSnapshot(t.snapshot)); return; } if (n && buildAgentRunTerminalOutcome(n).reason === "hard_timeout") { finish(projectAgentJobObservation(n)); return; } } finish(null); }, e.timeoutMs).unref(); n?.addEventListener("abort", onClose, { once: true }); if (n?.aborted) onClose(); else onWake(); }); } ensureAgentRunListener(); //#endregion export { waitForAgentJob as a, setGatewayDedupeEntry as i, getAgentJobSession as n, projectAgentJobObservation as r, captureAgentJobSession as t };