UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

367 lines (366 loc) • 13.1 kB
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { c as resolveOpenClawAgentSqlitePath, o as resolveExplicitIncognitoAgentSqliteTarget } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { n as getSessionActorStorageBinding, o as runWithSessionActorStorage, t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { n as captureOpenClawAgentDatabaseExecution } from "./openclaw-agent-execution-C4FyHhb0.mjs"; import "./session-accessor-CizTbDQj.mjs"; import { n as openOpenClawAgentSqliteWorkerStore } from "./openclaw-agent-worker-store-Do41NaPe.mjs"; import { i as rethrowIncognitoSessionError, n as IncognitoSessionMissingError } from "./incognito-session-error-BxQdjUZa.mjs"; import { t as readSessionActorStorageResult } from "./session-actor-storage-result-BkDuCjds.mjs"; import { r as resolveSessionTranscriptDatabasePath } from "./session-accessor.transcript-target-njOktg4F.mjs"; import { o as supportsContextEngineDurableTurnAdvancement } from "./host-compat-D2mUtPDd.mjs"; import { t as drainContextEngineTurnOutbox } from "./context-engine-turn-outbox-BIFi2Z96.mjs"; import { t as runContextEngineMaintenance } from "./context-engine-maintenance-DsWc3w5M.mjs"; //#region src/agents/harness/context-engine-turn-outbox-memory.ts /** Plugin callbacks run outside the FIFO; only their intent acknowledgments reenter it. */ function openMemoryContextEngineTurnOutboxStore(e, t) { const { authority: n } = t; const r = e.sessionKey ?? (e.sessionId ? t.owner?.readSessionById(e.sessionId, n)?.sessionKey : void 0); const selected = () => { const e = getSessionActorStorageBinding({}) ?? t.binding; return e?.agentId === t.agentId && e.path === t.path && e.actor.target.sessionKey === r ? e : void 0; }; const run = async (e) => { const i = selected(); if (i) return e(i); const a = r ? await t.owner?.acquireExisting(r, { assertCurrent: () => n.assertCurrent(), assertReadable: () => n.assertCurrent() }) : void 0; if (!a) throw new IncognitoSessionMissingError(); try { return await e({ actor: a, authority: n, agentId: t.agentId, path: t.path }); } finally { await a.release(); } }; const mutate = (e, t) => run(async ({ actor: r }) => readSessionActorStorageResult(await r.storage.mutate({ type: e, input: t }, n))); const read = (e, t) => run(({ actor: r }) => r.storage.read({ type: e, input: t }, n)); return { retain: (e) => run(({ actor: r }) => r.withPhase("context-engine-outbox", n, ({ actor: r }) => runWithSessionActorStorage({ actor: r, authority: n, agentId: t.agentId, path: t.path }, e))), assertReadable() { const e = selected(); if (e) { e.actor.snapshot(n); return; } if (!r || !t.owner?.readSession(r, n)) throw new IncognitoSessionMissingError(); }, prepareRun: (e) => mutate("session.outbox.prepareRun", e), enqueueIntent: (e) => mutate("session.outbox.enqueueIntent", e), acceptIntent: (e) => mutate("session.outbox.acceptIntent", e), publishClosedTurn: (e) => mutate("session.outbox.publishClosedTurn", e), discardIntent: (e) => mutate("session.outbox.discardIntent", e), listPendingSessions: (e) => read("session.outbox.listPendingSessions", e), readNextPending: (e) => read("session.outbox.readNextPending", e), hasPending: (e) => read("session.outbox.hasPending", e), complete: async (e) => { await mutate("session.outbox.complete", { advancementKey: e }); }, recordFailure: async (e, t, n) => { await mutate("session.outbox.recordFailure", { advancementKey: e, message: t, attemptedAt: n }); } }; } //#endregion //#region src/agents/harness/context-engine-turn-outbox-store.ts /** * Runs one outbox command in the agent database worker. The host thread only * awaits it, so a worker transaction waiting on this thread for its commit * grant is never blocked by synchronous SQLite here. */ async function runContextEngineTurnOutboxCommand(e, t) { if (resolveExplicitIncognitoAgentSqliteTarget(e.path, { agentId: e.agentId })) throw new IncognitoSessionMissingError(); const n = cloneEnvWithPlatformSemantics(process.env); n.OPENCLAW_STATE_DIR = resolveStateDir(n); const r = { agentId: e.agentId, env: n, path: resolveOpenClawAgentSqlitePath({ agentId: e.agentId, env: n, path: e.path }) }; const i = captureOpenClawAgentDatabaseExecution(r); try { const e = await openOpenClawAgentSqliteWorkerStore(r, { execution: i }, { moduleUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.contextEngineTurnOutbox), input: void 0 }); try { return await e.execute(t, () => i.assertCurrent()); } finally { await e.close(); } } finally { await i.release(); } } function openContextEngineTurnOutboxWorkerStore(e) { const t = { ...e, storePath: e.path }; const n = captureSessionActorStorageOwner(t, { assertCurrent() {}, authorize() {} }); if (n) return openMemoryContextEngineTurnOutboxStore(t, n); const r = { ...e }; const run = (e) => { return runContextEngineTurnOutboxCommand(r, e); }; return { prepareRun: (e) => run({ type: "prepareRun", input: e }), listPendingSessions: (e) => run({ type: "listPendingSessions", input: e }), readNextPending: (e) => run({ type: "readNextPending", input: e }), complete: async (e) => { await run({ type: "complete", input: { advancementKey: e } }); }, recordFailure: async (e, t, n) => { await run({ type: "recordFailure", input: { advancementKey: e, message: t, attemptedAt: n } }); }, hasPending: (e) => run({ type: "hasPending", input: e }), enqueueIntent: (e) => run({ type: "enqueueIntent", input: e }), acceptIntent: (e) => run({ type: "acceptIntent", input: e }), publishClosedTurn: (e) => run({ type: "publishClosedTurn", input: e }), discardIntent: (e) => run({ type: "discardIntent", input: e }) }; } //#endregion //#region src/agents/harness/context-engine-turn-attempt.ts const ACCEPTED_TURN_MAX_EVENTS = 2e4; const ACCEPTED_TURN_MAX_BYTES = 8388608; async function drainPendingContextEngineTurnsBeforeRun(e) { if (!e.admission && !e.recorder || e.lease.degraded || !supportsContextEngineDurableTurnAdvancement(e.lease.engine)) return; const t = e.warn ?? console.warn; try { const n = e.admission ?? e.sessionTarget; if (!n?.agentId || !n.sessionId || !n.sessionKey || !n.storePath) { e.lease.degradeBeforeStart("durable transcript target is unavailable before context assembly"); return; } const r = e.admission ? e.admission.storePath : resolveSessionTranscriptDatabasePath({ agentId: n.agentId, sessionId: n.sessionId, sessionKey: n.sessionKey, storePath: n.storePath }); const i = openContextEngineTurnOutboxWorkerStore({ agentId: n.agentId, path: r, sessionKey: n.sessionKey, sessionId: n.sessionId }); const a = { engineId: e.lease.effectiveEngineId, ownerPluginId: e.lease.effectiveEnginePluginId }; const retainAdmission = (n, o) => { const s = new Promise((c) => { e.lease.onDispose(JSON.stringify([r, n.logicalTurnId]), async () => { await s.catch(() => {}); if (await i.discardIntent({ ...a, admission: n })) t(`[context-engine] discarded unaccepted turn advancement: ${n.logicalTurnId}: run ended without host acceptance`); }); c(o()); }); return s; }; const o = n.sessionId; const prepare = () => i.prepareRun({ ...a, admission: e.admission, sessionId: o }); const s = await (e.admission ? retainAdmission(e.admission, prepare) : prepare()); for (const e of s.warnings) t(e); if (s.pending) { if ((await drainContextEngineTurnOutbox({ store: i, engine: e.lease.engine, ...a, sessionId: n.sessionId, warn: t })).pending) { e.lease.degradeBeforeStart("pending durable turn advancement could not be completed before the next turn"); return; } } const enqueueAdmission = async (t) => { if (e.lease.disposed) return; if (t.agentId !== n.agentId || t.sessionId !== n.sessionId || t.sessionKey !== n.sessionKey || t.storePath !== r) throw new Error("context-engine transcript target changed before provider dispatch"); await retainAdmission(t, () => i.enqueueIntent({ ...a, admission: t })); }; if (e.admission) { if (!s.admitted) await enqueueAdmission(e.admission); return; } if (!e.recorder?.setAdmissionHandler) { e.lease.degradeBeforeStart("current-turn transcript admission cannot be recorded for durable advancement"); return; } e.recorder.setAdmissionHandler(enqueueAdmission); } catch (n) { rethrowIncognitoSessionError(n); t(`[context-engine] failed to retry pending turn advancement: ${n instanceof Error ? n.message : String(n)}`); e.lease.degradeBeforeStart("pending durable turn advancement could not be checked before the next turn"); } } function assertAcceptedTranscriptTarget(e) { const { admission: t, terminal: n } = e.boundary; if (e.sessionIdUsed !== t.sessionId || n.agentId !== t.agentId || n.sessionId !== t.sessionId || n.sessionKey !== t.sessionKey || n.storePath !== t.storePath || e.sessionKey !== void 0 && e.sessionKey !== t.sessionKey || e.sessionTarget?.agentId !== void 0 && e.sessionTarget.agentId !== t.agentId || e.sessionTarget?.sessionId !== void 0 && e.sessionTarget.sessionId !== t.sessionId || e.sessionTarget?.sessionKey !== void 0 && e.sessionTarget.sessionKey !== t.sessionKey) throw new Error("accepted context-engine transcript target changed after admission"); } /** Commit the accepted transcript range and offer acknowledged turns to host-owned maintenance. */ async function finalizeAcceptedContextEngineTurn(e) { const t = e.lease.engine.info.transcriptSemantics?.turnAdvancementIdempotency !== void 0; const n = supportsContextEngineDurableTurnAdvancement(e.lease.engine); if (!t && !n) return; const r = e.warn ?? console.warn; if (e.facts.promptError || e.facts.aborted || e.facts.yieldAborted) return; try { assertAcceptedTranscriptTarget(e.facts); if (e.lease.degraded || !t || !n) throw new Error("accepted context engine does not support durable turn advancement"); const i = e.facts.boundary.admission; const a = openContextEngineTurnOutboxWorkerStore({ agentId: i.agentId, path: i.storePath, sessionKey: i.sessionKey, sessionId: i.sessionId }); const o = { boundary: e.facts.boundary, engineId: e.lease.effectiveEngineId, ownerPluginId: e.lease.effectiveEnginePluginId, runtimeContext: e.facts.runtimeContext }; await a.acceptIntent(o); const s = await a.publishClosedTurn({ ...o, maxBytes: ACCEPTED_TURN_MAX_BYTES, maxEvents: ACCEPTED_TURN_MAX_EVENTS }); if (s !== "ok") throw new Error(`accepted context-engine transcript range is ${s}`); const c = /* @__PURE__ */ new Map(); const onCommitted = (t) => { c.set(t.sessionId, { contextEngine: e.lease.engine, sessionId: t.sessionId, sessionKey: t.sessionKey, sessionTarget: t.sessionTarget, sessionFile: t.admission.sessionKey, reason: "turn", runtimeContext: t.runtimeContext, runtimeSettings: t.runtimeSettings, config: e.config, onDeferredMaintenance: (t) => e.lease.deferDisposalUntil(t) }); }; const drainSession = (t, n) => drainContextEngineTurnOutbox({ store: a, engine: e.lease.engine, engineId: e.lease.effectiveEngineId, ownerPluginId: e.lease.effectiveEnginePluginId, sessionId: t, ...n === void 0 ? {} : { limit: n }, onCommitted, warn: r }); await drainSession(i.sessionId); const l = await a.listPendingSessions({ engineId: e.lease.effectiveEngineId, ownerPluginId: e.lease.effectiveEnginePluginId, limit: 16 }); for (const e of l) { if (e === i.sessionId) continue; await drainSession(e, 1); } for (const e of c.values()) await runContextEngineMaintenance(e); } catch (e) { rethrowIncognitoSessionError(e); r(`[context-engine] skipped accepted turn advancement: ${e instanceof Error ? e.message : String(e)}`); } } //#endregion //#region src/agents/harness/context-engine-turn-begin.ts async function beginContextEngineLogicalTurn(e) { const { host: t, ...n } = e; await n.lease.rebind(); const r = n.recorder?.getAdmissionReceipt(); if (n.recorder && !r && n.recorder.hasPersisted()) n.lease.degradeBeforeStart("current-turn transcript admission receipt is unavailable"); else n.lease.selectForHost({ host: t, operation: "agent-run", requiresDurableCommit: n.recorder !== void 0 }); await drainPendingContextEngineTurnsBeforeRun({ ...n, admission: n.recorder?.getAdmissionReceipt() }); return n.lease.begin(); } //#endregion export { finalizeAcceptedContextEngineTurn as n, beginContextEngineLogicalTurn as t };