UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

452 lines (451 loc) • 14.6 kB
import { a as extractErrorCode, d as readErrorName, r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { c as resolveOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs"; import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { i as isSqliteWorkerError } from "./sqlite-worker-error-DEIJgRIz.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import "./sqlite-worker-contract--dxXkOty.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import "./io-4QsrsWTJ.mjs"; import { r as assertAgentDatabaseReadAdmitted } from "./agent-database-admission-CL6wHJ_N.mjs"; import { a as runOpenClawAgentWriteAdmission, n as runOpenClawAgentBoardReadAdmission } from "./session-worker-execution-source-H3bdawqM.mjs"; import "./openclaw-agent-db-CwXW4hGa.mjs"; import { t as captureSessionTranscriptStorageEnvironment } from "./transcript-target-binding-BvjuRqS9.mjs"; import { i as prepareSqliteTargetFromSessionStorePath } from "./session-sqlite-target-C8iD4yIo.mjs"; import { t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { v as targetDiscoveryLane } from "./session-transcript-worker-resources-B9oklCSm.mjs"; import { o as withSessionHistoryWorkerDatabase } from "./session-transcript-worker-runtime-DMpH3wlh.mjs"; import { r as BoardValidationError } from "./board-layout-C0d9b7cg.mjs"; import { n as withSessionActorStorage } from "./session-actor-storage-acquisition-bj-qIczw.mjs"; import { r as openOpenClawAgentSqliteWorkerStoreV2 } from "./openclaw-agent-worker-store-Do41NaPe.mjs"; import { n as IncognitoSessionMissingError } from "./incognito-session-error-BxQdjUZa.mjs"; import { t as readSessionActorStorageResult } from "./session-actor-storage-result-BkDuCjds.mjs"; import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs"; import { randomBytes } from "node:crypto"; import { AsyncLocalStorage } from "node:async_hooks"; import { isPromise } from "node:util/types"; //#region src/boards/board-store-errors.ts function restoreBoardError(e) { if (e instanceof Error && e.name === "BoardValidationError" && "code" in e && (e.code === "conflict" || e.code === "invalid_operation" || e.code === "not_found")) return new BoardValidationError(e.code, e.message); return e; } /** Invalidation never grants retries; transported post-execution failures are plain Errors. */ function hasUnknownBoardWriteOutcome(e) { return collectErrorGraphCandidates(e, (e) => e instanceof AggregateError ? [e.cause] : []).some((e) => isSqliteWorkerError(e, "outcome-unknown") || e instanceof Error && readErrorName(e) === "SqliteWorkerError" && extractErrorCode(e) === "outcome-unknown"); } //#endregion //#region src/boards/session-actor-board-store.ts /** The routing owner supplies the already-acquired actor; this store never acquires a backend. */ function createSessionActorBoardStore(e) { const write = async (e, t, n, r) => { r?.assertCurrent?.(); const i = await e.actor.storage.mutate({ type: t, input: n }, e.authority); if (i.kind === "rolled-back") throw restoreBoardError(Object.assign(new Error(i.error.message), i.error)); return readSessionActorStorageResult(i); }; const readSnapshot = async (t, n) => { const r = e(t); const i = await r.actor.storage.read({ type: "boards.snapshot", input: { sessionKey: r.actor.target.sessionKey } }, r.authority); r.actor.snapshot(r.authority); return await n(i); }; const readDocument = async (t, n, r, i) => { const a = e(t); const o = await a.actor.storage.read({ type: "boards.document", input: { sessionKey: a.actor.target.sessionKey, name: n, contentKind: i } }, a.authority); a.actor.snapshot(a.authority); return await r(o); }; const t = { useSnapshot(e, t) { return readSnapshot(e, ({ snapshot: e }) => t(e)); }, useWidgetDocument(e, t, n) { return readDocument(e, t, n); }, getSnapshot(e) { return readSnapshot(e, ({ snapshot: e }) => e); }, getSnapshotWithHtmlViewMetadata: (e) => readSnapshot(e, (e) => e), async applyOps(n, r, i) { if (!r.length) return t.getSnapshot(n); const a = e(n); return write(a, "boards.applyOps", { sessionKey: a.actor.target.sessionKey, ops: structuredClone(r) }, i); }, async putWidget(t, n) { const r = e(t); let i = structuredClone(t); const a = i.content; if (a.kind === "mcp-app" && a.interactive && n?.resolveMcpAppInteraction && !await n.resolveMcpAppInteraction()) i = { ...i, content: { ...a, interactive: false }, declared: void 0 }; return write(r, "boards.putWidget", { sessionKey: r.actor.target.sessionKey, params: i, viewGeneration: randomBytes(16).toString("hex") }, n); }, async grant(t, n, r, i, a, o) { const s = e(t); return write(s, "boards.grant", { sessionKey: s.actor.target.sessionKey, name: n, decision: r, revision: i, instanceId: a }, o); }, readWidgetMcpApp(e, t) { return readDocument(e, t, (e) => e && "descriptor" in e ? e : void 0, "mcp-app"); } }; return t; } //#endregion //#region src/boards/sqlite-board-authority.ts const log = createSubsystemLogger("boards/store"); function reportBoardCleanupFailure(e) { try { log.warn(`Board publication completed before cleanup failed: ${formatErrorMessage(e)}`); } catch {} } //#endregion //#region src/boards/sqlite-board-store.ts var SqliteBoardStore = class { constructor(e) { this.options = e; } async withSession(e, t, n, r) { const i = cloneEnvWithPlatformSemantics(this.options.env ?? process.env); i.OPENCLAW_STATE_DIR = resolveStateDir(i); const a = { ...await this.options.resolveSession({ ...e }), env: i }; const assertCurrent = () => a.assertCurrent?.(); const o = { assertCurrent, authorize: assertCurrent }; const s = { ...a, storePath: a.path, env: this.options.env ? a.env : void 0 }; const c = captureSessionActorStorageOwner(s, o); if (!c) return n(a); const l = await withSessionActorStorage(s, { authority: c.authority, lifetime: { assertCurrent, assertReadable: assertCurrent } }, async (e) => ({ value: await t(createSessionActorBoardStore(() => e)) })); if (l) return l.value; assertCurrent(); if (r) return r(); throw new BoardValidationError("not_found", `board session not found: ${a.sessionKey}`); } write(e, t, n, r) { if (e.absent) { t?.assertCurrent?.(); e.assertCurrent?.(); e.absent.assertCurrent(); throw new IncognitoSessionMissingError(); } const { env: i } = e; const a = { agentId: e.agentId, env: i, path: resolveOpenClawAgentSqlitePath({ ...e, env: i }) }; const assertCurrent = () => e.assertCurrent?.(); assertCurrent(); return runOpenClawAgentWriteAdmission(a, async (o, s) => { const c = await withSessionHistoryWorkerDatabase(a, (t) => t.readExactEntries({ env: i, sessionKeys: [e.sessionKey], projection: "exact", snapshotFields: [], expectedIdentity: o }), targetDiscoveryLane); s(); assertCurrent(); const l = c.entries[0]?.entry; if (!l) throw new BoardValidationError("not_found", `board session not found: ${e.sessionKey}`); const u = { sessionId: l.sessionId, lifecycleRevision: l.lifecycleRevision }; const assertPreparedCurrent = () => { s(); assertCurrent(); }; t?.assertCurrent?.(); if (r) await r(); assertPreparedCurrent(); const d = await openOpenClawAgentSqliteWorkerStoreV2(a, { version: 2, assertCurrent: assertPreparedCurrent }, { moduleUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.boardStore), input: { agentId: a.agentId, sessionKey: e.sessionKey, expectedSession: u } }); let f; try { f = { ok: true, value: await d.run(async (r) => { t?.assertCurrent?.(); let i; try { i = await n(r, e.sessionKey); } catch (t) { if (hasUnknownBoardWriteOutcome(t)) sessionChanges.emit({ sessionKey: e.sessionKey, storePath: o.canonicalPath }); throw t; } sessionChanges.emitBatch(i.changes); return i.value; }, assertPreparedCurrent) }; } catch (e) { f = { ok: false, error: restoreBoardError(e) }; } let p; try { await d.close(); p = { ok: true, value: void 0 }; } catch (e) { p = { ok: false, error: e }; } if (!f.ok) { if (!p.ok) throw new AggregateError([f.error, p.error], "Board publication and cleanup failed", { cause: f.error }); throw f.error; } if (!p.ok) reportBoardCleanupFailure(p.error); return f.value; }, true); } async getSnapshot(e) { return this.useSnapshot(e, (e) => e); } async getSnapshotWithHtmlViewMetadata(e) { return this.withSession(e, (t) => t.getSnapshotWithHtmlViewMetadata(e), (e) => this.consumeSnapshotWithHtmlViewMetadata(e, (e) => e, true), () => ({ snapshot: { sessionKey: e.sessionKey, revision: 0, tabs: [], widgets: [] }, htmlViewMetadata: /* @__PURE__ */ new Map() })); } async consumeRead(e, t, n, r = false) { if (e.absent) { e.assertCurrent?.(); e.absent.assertCurrent(); const t = await n(void 0, e.sessionKey); e.assertCurrent?.(); e.absent.assertCurrent(); return t; } const i = captureSessionTranscriptStorageEnvironment(e.env); const a = { agentId: e.agentId, sessionKey: e.sessionKey, env: i, path: resolveOpenClawAgentSqlitePath({ ...e, env: i }) }; const o = AsyncLocalStorage.snapshot(); const accept = (t) => { e.assertCurrent?.(); if (r) assertAgentDatabaseReadAdmitted(a.agentId, { env: i }); const s = o(n, t, a.sessionKey); if (isPromise(s)) s.catch(() => {}); return { value: s }; }; const s = readDatabasePathIdentitySync(a.path); if (!s.key.startsWith("file:")) return await (await runOpenClawAgentBoardReadAdmission(a, async () => accept(void 0))).value; return await (await withSessionHistoryWorkerDatabase({ ...a, path: s.canonicalPath, requestedPaths: [a.path] }, (n) => runOpenClawAgentBoardReadAdmission(a, async () => { e.assertCurrent?.(); const r = await t(n, a.sessionKey, i, s); n.assertCurrent(); return accept(r); }, r), targetDiscoveryLane).catch((e) => { throw restoreBoardError(e); })).value; } async useSnapshot(e, t) { return await this.withSession(e, (n) => n.useSnapshot(e, t), (e) => this.consumeSnapshotWithHtmlViewMetadata(e, ({ snapshot: e }) => t(e)), async () => t({ sessionKey: e.sessionKey, revision: 0, tabs: [], widgets: [] })); } async useWidgetDocument(e, t, n) { return await this.withSession(e, (r) => r.useWidgetDocument(e, t, n), (e) => this.consumeWidgetDocument(e, t, n), async () => n(void 0)); } consumeSnapshotWithHtmlViewMetadata(e, t, n = false) { return this.consumeRead(e, (e, t, n, r) => e.readBoardSnapshot({ sessionKey: t, env: n, expectedIdentity: r }), (e, n) => t(e ?? { snapshot: { sessionKey: n, revision: 0, tabs: [], widgets: [] }, htmlViewMetadata: /* @__PURE__ */ new Map() }), n); } async applyOps(e, t, n) { if (t.length === 0) return this.getSnapshot(e); const r = structuredClone(t); return this.withSession(e, (t) => t.applyOps(e, r, n), (e) => this.write(e, n, (e, t) => e.execute({ type: "boards.applyOps", input: { sessionKey: t, ops: r } }))); } async putWidget(e, t) { let n = structuredClone(e); return this.withSession(e, (e) => e.putWidget(n, t), (e) => { const r = randomBytes(16).toString("hex"); const i = n.content; const a = t?.resolveMcpAppInteraction; const o = i.kind === "mcp-app" && i.interactive && a ? async () => { if (!await a()) n = { ...n, content: { ...i, interactive: false }, declared: void 0 }; } : void 0; return this.write(e, t, (e, t) => e.execute({ type: "boards.putWidget", input: { sessionKey: t, params: n, viewGeneration: r } }), o); }); } async grant(e, t, n, r, i, a) { return this.withSession(e, (o) => o.grant(e, t, n, r, i, a), (e) => this.write(e, a, (e, a) => e.execute({ type: "boards.grant", input: { sessionKey: a, name: t, decision: n, revision: r, instanceId: i } }))); } consumeWidgetDocument(e, t, n, r) { return this.consumeRead(e, (e, n, i, a) => e.readBoardWidgetDocument({ sessionKey: n, name: t, contentKind: r, env: i, expectedIdentity: a }), n); } async readWidgetMcpApp(e, t) { return this.withSession(e, (n) => n.readWidgetMcpApp(e, t), (e) => this.consumeWidgetDocument(e, t, (e) => e && "descriptor" in e ? e : void 0, "mcp-app"), () => void 0); } }; //#endregion //#region src/gateway/board-store.ts function captureGatewaySessionStoreScope(e, t) { const n = readRuntimeConfig(); const { agentId: r, canonicalKey: i } = resolveSessionStoreIdentity({ cfg: n, sessionKey: e, agentId: t }); return { agentId: r, storePath: resolveSessionStorePathCore(n.session?.store, { agentId: r }), sessionKey: i }; } const boardStore = new SqliteBoardStore({ resolveSession: async ({ sessionKey: e, agentId: t }) => { const n = captureGatewaySessionStoreScope(e, t); const assertCurrent = () => { const r = captureGatewaySessionStoreScope(e, t); if (r.agentId !== n.agentId || r.storePath !== n.storePath || r.sessionKey !== n.sessionKey) throw new BoardValidationError("invalid_operation", "board session changed; retry"); }; const r = captureSessionActorStorageOwner(n, { assertCurrent, authorize: assertCurrent }) ?? await prepareSqliteTargetFromSessionStorePath(n.storePath, n); return { agentId: r.agentId ?? n.agentId, path: r.path, sessionKey: n.sessionKey, assertCurrent }; } }); //#endregion export { captureGatewaySessionStoreScope as n, boardStore as t };