UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

464 lines (463 loc) • 17.9 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { n as notifyListeners, r as registerListener } from "./listeners-Cb2-CnP8.mjs"; import { s as isDefinitiveRunLifecycle } from "./agent-run-terminal-outcome-CurjWZiA.mjs"; import { E as rotateAgentRunRegistryLifecycleGeneration, M as getAgentEventExecutionContext, N as recordAgentEventRouting, S as resetAgentRunRegistryForTest, g as recordAgentRunModel, k as recordAgentRunOutputTokens, l as getAgentRunContext, u as getAgentRunContextOwnership, y as registerAgentRunSequenceResetHandler } from "./agent-run-registry-D7vkrqFT.mjs"; import { t as createAgentRunStaleLifecycleError } from "./agent-lifecycle-error-C4eSNOaP.mjs"; import { r as getAgentRunLifecycleGeneration } from "./agent-run-registry-state-BFfw9a4W.mjs"; import { r as captureAgentRunTerminalPersistence } from "./agent-run-terminal-writes-eqeCFAOx.mjs"; //#region src/infra/agent-event-lifecycle.ts /** Returns true when a lifecycle start omits its producer-owned finite timestamp. */ function hasInvalidLifecycleStartTimestamp(e, t) { if (e !== "lifecycle" || !t || typeof t !== "object" || Array.isArray(t)) return false; const n = t; return n.phase === "start" && (typeof n.startedAt !== "number" || !Number.isFinite(n.startedAt)); } //#endregion //#region src/infra/agent-events.ts const AGENT_EVENT_ROUTING_FIELDS = [ ["controlUiVisible", "isControlUiVisible"], ["projectSessionLifecycle", "projectSessionLifecycle"], ["projectSessionMessages", "projectSessionMessages"], ["mainSessionRestartRecovery", "mainSessionRestartRecovery"], ["verboseLevel", "verboseLevel"], ["registeredAt", "registeredAt"] ]; function getAgentEventState() { return resolveGlobalSingleton(Symbol.for("openclaw.agentEvents.state"), () => ({ runs: /* @__PURE__ */ new Map(), listeners: { registrations: [] }, runListeners: /* @__PURE__ */ new Map(), nextListenerId: 0, auditListeners: /* @__PURE__ */ new Set() })); } /** Correlate copied model frames with their occurrence without changing transcript bytes. */ function bindAgentAssistantSource(e, t) { (getAgentEventState().assistantSources ??= /* @__PURE__ */ new WeakMap()).set(e, t); } function readAgentAssistantSource(e) { return e && typeof e === "object" ? getAgentEventState().assistantSources?.get(e) : void 0; } registerAgentRunSequenceResetHandler((e) => { getAgentEventState().runs.delete(e); }); /** Runs one execution with immutable ownership inherited by every emitted stream event. */ function withAgentRunLifecycleGeneration(e, t) { const n = getAgentEventExecutionContext(); const r = n.getStore(); const i = r?.lifecycleGeneration === e ? r.onceByRun : /* @__PURE__ */ new Map(); const a = new Map(r?.routingByRun); return n.run({ lifecycleGeneration: e, onceByRun: i, routingByRun: a }, t); } /** Reserves client terminal publication without advancing execution settlement. */ function reserveAgentTerminalEvent(e) { const { runId: t } = e; const n = getAgentRunContext(t); const r = captureAgentRunTerminalPersistence(t); return withAgentRunLifecycleGeneration(captureAgentRunLifecycleGeneration(t), () => { if (n) recordAgentEventRouting(t, n); const i = resolveAgentEventRouting(e); if (!i) return { publish: () => {}, release: () => {} }; const a = getAgentEventState(); const o = i.routing?.eventState ?? a.runs.get(t) ?? { seq: 0 }; const s = Symbol("agent terminal publication"); o.terminalPublication ??= s; if (!a.runs.has(t)) a.runs.set(t, o); const c = getAgentEventExecutionContext(); const l = c.getStore(); let u = true; return { publish: (t) => { if (u) { u = false; c.run(l, () => dispatchAgentEvent({ ...e, stream: "lifecycle", data: t }, void 0, void 0, s, void 0, void 0, r)); } }, release: () => { if (!u) return; u = false; if (o.terminalPublication === s) delete o.terminalPublication; } }; }); } /** Shares one operation across fallback attempts that belong to the same admitted run. */ function runOncePerAgentRun(e, t, n) { const r = getAgentEventExecutionContext().getStore(); if (!r) return n(); const i = `${t}:${e}`; const a = r.onceByRun.get(i); if (a) return a; const o = Promise.resolve().then(n); r.onceByRun.set(i, o); return o; } function getAgentEventLifecycleGeneration() { return getAgentRunLifecycleGeneration(); } function isAgentEventLifecycleGenerationCurrent(e) { return e === getAgentRunLifecycleGeneration(); } /** Registers process-local state cleanup at the gateway lifecycle boundary. */ function registerAgentEventLifecycleRotationHandler(e, t) { const n = getAgentEventState(); const r = n.lifecycleRotationHandlers ?? (n.lifecycleRotationHandlers = /* @__PURE__ */ new Map()); r.set(e, t); return () => { if (r.get(e) === t) r.delete(e); }; } /** Rejects work that no longer belongs to the active gateway lifecycle. */ function assertAgentRunLifecycleGenerationCurrent(e) { if (isAgentEventLifecycleGenerationCurrent(e)) return; throw createAgentRunStaleLifecycleError(); } /** Captures immutable lifecycle ownership for one admitted execution. */ function captureAgentRunLifecycleGeneration(e) { return getAgentEventExecutionContext().getStore()?.lifecycleGeneration ?? getAgentRunContext(e)?.lifecycleGeneration ?? getAgentRunLifecycleGeneration(); } /** Starts a new ownership generation before an in-process gateway restart. */ function rotateAgentEventLifecycleGeneration() { const e = getAgentEventState(); const t = rotateAgentRunRegistryLifecycleGeneration(); const n = []; notifyListeners(e.lifecycleRotationHandlers?.values() ?? [], t, (e) => n.push(e)); if (n.length > 0) throw new AggregateError(n, "Failed to retire stale agent lifecycle owners"); return t; } const MAX_EXECUTION_ACTIVITY_ITEMS = 64; const MAX_EXECUTION_ACTIVITY_ID_LENGTH = 256; const MAX_EXECUTION_TOOL_NAME_LENGTH = 120; function activityId(e) { if (typeof e !== "string") return; const t = e.trim(); return t && t.length <= MAX_EXECUTION_ACTIVITY_ID_LENGTH ? t : void 0; } function recordExecutionActivity(e, t) { if (t.sessionKey && e.sessionKey && t.sessionKey !== e.sessionKey || t.sessionId && e.sessionId && t.sessionId !== e.sessionId) return; const { stream: n, data: r } = t; if (n === "lifecycle" && (r.phase === "end" || r.phase === "error")) { e.executionActivity = void 0; return; } const i = n === "execution" && isRecord(r.approval) ? r.approval : void 0; const a = activityId(i?.id ?? (n === "lifecycle" ? r.approvalId : void 0)); const o = i?.state ?? (r.phase === "waiting-approval" ? "pending" : r.phase === "approval-resolved" ? "resolved" : void 0); if (a && (o === "pending" || o === "resolved")) { const t = e.executionActivity ??= { tools: [], pendingApprovalIds: [] }; if (o === "pending" && !t.pendingApprovalIds.includes(a)) { if (t.pendingApprovalIds.length < MAX_EXECUTION_ACTIVITY_ITEMS) t.pendingApprovalIds.push(a); else t.approvalOverflow = true; } else if (o === "resolved") t.pendingApprovalIds = t.pendingApprovalIds.filter((e) => e !== a); return; } if (n === "execution" && (r.state === "running" || r.state === "waiting" || r.state === "unknown")) { const t = activityId(r.sourceId); const n = e.executionActivity?.execution; if (r.invalidate === true && (!t || n?.sourceId !== t)) return; const i = e.executionActivity ??= { tools: [], pendingApprovalIds: [] }; const a = activityId(r.executionId); if (r.state === "unknown" || t && n?.sourceId !== t || a && n?.id !== a) i.tools = []; const o = isRecord(r.wait) ? r.wait.kind : void 0; const s = o === "approval" || o === "user_input" || o === "agent_messages" || o === "children" ? o : "external"; i.execution = { state: r.state, sourceId: t ?? n?.sourceId, id: a ?? n?.id, ...r.state === "waiting" ? { wait: s } : {} }; return; } if (n !== "tool") return; const s = activityId(r.toolCallId); if (!s) return; const c = e.executionActivity; if (r.phase === "result" || r.phase === "end") { if (c) c.tools = c.tools.filter((e) => e.id !== s); return; } if (r.phase !== "start" || typeof r.name !== "string" || !r.name.trim()) return; const l = e.executionActivity ??= { tools: [], pendingApprovalIds: [] }; const u = { id: s, name: truncateUtf16Safe(r.name.trim(), MAX_EXECUTION_TOOL_NAME_LENGTH) }; const d = l.tools.findIndex((e) => e.id === s); if (d >= 0) l.tools[d] = u; else if (l.tools.length < MAX_EXECUTION_ACTIVITY_ITEMS) l.tools.push(u); } function resolveAgentEventRouting(e, t, n) { const r = getAgentRunLifecycleGeneration(); const i = getAgentRunContextOwnership(e.runId); if (t !== void 0) { if (i?.lifecycleGeneration !== r || i.exclusiveClaimId !== t || !i.claimIds.has(t) || i.clearRequested) return; } else if (i?.lifecycleGeneration === r && i.exclusiveClaimId) return; const a = getAgentRunContext(e.runId); if (n && a !== n) return; const o = getAgentEventExecutionContext().getStore(); const s = e.lifecycleGeneration ?? o?.lifecycleGeneration; const c = s ?? a?.lifecycleGeneration; if (s && a?.lifecycleGeneration && s !== a.lifecycleGeneration) return; if (c && c !== r) return; const l = o?.routingByRun?.get(e.runId); const u = l?.routing.lifecycleGeneration === c ? l : void 0; const d = u?.owner.deref(); if (u && a && d !== a) return; return { context: a, routing: a ?? u?.routing, capturedOwner: d, ownedLifecycleGeneration: c, currentLifecycleGeneration: r }; } function enrichAgentEvent(e, t, n, r, i, a, o, s) { const c = resolveAgentEventRouting(t, n, r); if (!c || hasInvalidLifecycleStartTimestamp(t.stream, t.data)) return; const { context: l, routing: u, capturedOwner: d, ownedLifecycleGeneration: f, currentLifecycleGeneration: p } = c; if (t.stream === "lifecycle" && t.data.phase === "model") { if (!l || n === void 0 && (r ?? d) !== l) return; const { provider: e, model: i } = t.data; if (e === null && i === null) recordAgentRunModel(t.runId, void 0); else if (typeof e === "string" && e.trim() && typeof i === "string" && i.trim()) recordAgentRunModel(t.runId, { provider: e, model: i }); else return; } const m = u?.eventState ?? e.runs.get(t.runId) ?? { seq: 0 }; let h = t.data; if (u && t.stream === "lifecycle") { if (u.completionSource) h = { ...h, completionSource: u.completionSource }; if (h.phase === "start") { if (l) l.lifecycleStartedAt = h.startedAt; } else if ((h.phase === "end" || h.phase === "error") && h.startedAt === void 0 && u.lifecycleStartedAt !== void 0) h = { ...h, startedAt: u.lifecycleStartedAt }; } if (l) recordAgentEventRouting(t.runId, l); const g = Math.max(m.seq, e.runs.get(t.runId)?.seq ?? 0) + 1; m.seq = g; e.runs.set(t.runId, m); if (l) { l.lastActiveAt = Date.now(); recordExecutionActivity(l, t); } const _ = u?.isControlUiVisible ?? true; const v = typeof t.sessionKey === "string" && t.sessionKey.trim() ? t.sessionKey : void 0; const y = n !== void 0 ? v ?? u?.sessionKey : !_ && t.stream !== "lifecycle" ? u?.sessionKey : void 0; const b = _ || t.stream === "lifecycle" ? v ?? u?.sessionKey : void 0; const x = t.stream === "lifecycle" ? t.sessionId ?? u?.sessionId : t.sessionId; const S = t.stream === "lifecycle" ? f ?? p : f; const C = t.agentId ?? u?.agentId; const w = { ...t, data: h, sessionKey: b, ...x ? { sessionId: x } : {}, ...C ? { agentId: C } : {}, seq: g, ts: Date.now() }; if (t.stream === "lifecycle") { const e = i ?? Symbol("agent lifecycle publication"); let t = false; Object.defineProperty(w, "admitLifecyclePublication", { value: () => { if (t || m.terminalPublication && m.terminalPublication !== e) return false; t = true; if (isDefinitiveRunLifecycle({ phase: h.phase, data: h })) m.terminalPublication = e; return true; } }); } const T = { value: s ?? (t.stream === "lifecycle" && isDefinitiveRunLifecycle({ phase: h.phase, data: h }) ? captureAgentRunTerminalPersistence(t.runId, l ?? d) : void 0), enumerable: false }; Object.defineProperty(w, "terminalPersistence", T); T.value = a; Object.defineProperty(w, "assistantSource", T); T.value = o; Object.defineProperty(w, "assistantProjection", T); if (S) { T.value = S; Object.defineProperty(w, "lifecycleGeneration", T); } for (const [e, t] of AGENT_EVENT_ROUTING_FIELDS) { const n = u?.[t]; if (n !== void 0) { T.value = n; Object.defineProperty(w, e, T); } } if (n !== void 0) { T.value = n; Object.defineProperty(w, "contextClaimId", T); } if (y) { T.value = y; Object.defineProperty(w, "deliverySessionKey", T); } return w; } function dispatchAgentEvent(e, t, n, r, i, a, o) { const s = getAgentEventState(); const c = enrichAgentEvent(s, e, t, n, r, i, a, o); if (!c) return false; const l = s.listeners.registrations; const u = s.runListeners.get(c.runId)?.registrations; let d; for (const e of l) try { if (e.captureDelivery) { const t = e.captureDelivery(c); (d ??= /* @__PURE__ */ new Map()).set(e, t); } } catch {} let f = 0; let p = 0; while (true) { const e = l[f]; const t = u?.[p]; const n = e && (!t || e.id < t.id) ? e : t; if (!n) break; if (n === e) f++; else p++; try { if (!n.active) continue; const e = d?.get(n); if (!n.captureDelivery) n.listener(c); else if (e?.()) n.listener(c, e); } catch {} } return true; } /** Emits an event only when its run ownership is still current. */ function emitAgentEventIfCurrent(e) { return dispatchAgentEvent(e); } /** Bind the source occurrence only after ordinary event ownership admission. */ function emitAgentEventWithAssistantSourceIfCurrent(e, t, n) { return dispatchAgentEvent(e, void 0, void 0, void 0, t, n); } /** Adds one completed model call, returning its accepted run total for local callbacks. */ function emitAgentRunOutputTokens(e) { return recordAgentRunOutputTokens({ ...e, emit: (t) => emitAgentEventIfCurrent({ runId: e.runId, lifecycleGeneration: e.lifecycleGeneration, sessionKey: e.sessionKey, stream: "usage", data: t }) }); } /** Emits an agent event after assigning per-run sequence, timestamp, and context metadata. */ function emitAgentEvent(e) { emitAgentEventIfCurrent(e); } function emitAgentEventForOwner(e, t) { return dispatchAgentEvent(e, t); } /** Emits only while the exact run-context record captured by its producer remains current. */ function emitAgentEventForRunContext(e, t) { return dispatchAgentEvent(e, void 0, t); } /** Emits run metadata only to the Gateway-owned durable audit projection. */ function emitAgentAuditEvent(e) { const t = getAgentEventState(); const n = enrichAgentEvent(t, e); if (n) { notifyListeners(t.auditListeners, n); const r = e.stream === "lifecycle" ? e.data.phase : void 0; if ((r === "end" || r === "error") && !getAgentRunContext(e.runId)) t.runs.delete(e.runId); } } /** Subscribes to sequenced agent events; returns an unsubscribe callback. */ function onAgentEvent(e) { return registerAgentEventListener(e); } /** Subscribes Gateway internals that consume non-public ownership and routing metadata. */ function onAgentRuntimeEvent(e, t) { return registerAgentEventListener(e, void 0, t); } /** * Subscribes to one run's sequenced agent events; returns an unsubscribe callback. * Prefer this over `onAgentEvent` for a listener that discards other runs: those * listeners otherwise run on every concurrent run's events. */ function onAgentEventForRun(e, t) { return registerAgentEventListener(t, e); } function registerAgentEventListener(e, t, n) { const r = getAgentEventState(); const i = t === void 0 ? r.listeners : r.runListeners.get(t) ?? { registrations: [] }; if (!i.registrations.some((t) => t.listener === e)) { i.registrations = [...i.registrations, { listener: e, id: r.nextListenerId++, captureDelivery: n, active: true }]; if (t !== void 0) r.runListeners.set(t, i); } return () => { i.registrations = i.registrations.filter((t) => { if (t.listener !== e) return true; t.active = false; return false; }); if (t !== void 0 && i.registrations.length === 0 && r.runListeners.get(t) === i) r.runListeners.delete(t); }; } /** Subscribes to private audit-only agent events; returns an unsubscribe callback. */ function onAgentAuditEvent(e) { return registerListener(getAgentEventState().auditListeners, e); } /** Clears agent event state; test suites with a live Gateway can preserve its listeners. */ function resetAgentEventsForTest(e) { const t = getAgentEventState(); t.runs.clear(); resetAgentRunRegistryForTest(); if (!e?.preserveListeners) { for (const e of [t.listeners, ...t.runListeners.values()]) { for (const t of e.registrations) t.active = false; e.registrations = []; } t.runListeners.clear(); t.auditListeners.clear(); } } //#endregion export { withAgentRunLifecycleGeneration as C, runOncePerAgentRun as S, readAgentAssistantSource as _, emitAgentEvent as a, resetAgentEventsForTest as b, emitAgentEventIfCurrent as c, getAgentEventLifecycleGeneration as d, isAgentEventLifecycleGenerationCurrent as f, onAgentRuntimeEvent as g, onAgentEventForRun as h, emitAgentAuditEvent as i, emitAgentEventWithAssistantSourceIfCurrent as l, onAgentEvent as m, bindAgentAssistantSource as n, emitAgentEventForOwner as o, onAgentAuditEvent as p, captureAgentRunLifecycleGeneration as r, emitAgentEventForRunContext as s, assertAgentRunLifecycleGenerationCurrent as t, emitAgentRunOutputTokens as u, registerAgentEventLifecycleRotationHandler as v, hasInvalidLifecycleStartTimestamp as w, rotateAgentEventLifecycleGeneration as x, reserveAgentTerminalEvent as y };