UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

293 lines (292 loc) • 11.2 kB
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { s as resolveIncognitoOpenClawAgentSqlitePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { i as isSessionDeliveryGenerationRevokedError, r as prepareSessionGenerationFacts } from "./session-delivery-generation-CUS9yuZM.mjs"; //#region src/plugins/memory-audience.ts const MAX_LINEAGE_HOPS = 64; const SESSION_ID_PATTERN = /^[a-f0-9-]{36}$/; const audienceRecords = /* @__PURE__ */ new WeakMap(); const audienceSessionKeys = /* @__PURE__ */ new WeakMap(); function releaseRecordLeases(e) { for (const t of e.leases.splice(0)) t.release(); } const collectedAudienceRecords = new FinalizationRegistry((e) => { for (let t = e; t; t = t.parent) { t.holders -= 1; if (t.holders > 0) return; releaseRecordLeases(t); } }); function isAgentSessionKey(e, t) { return parseAgentSessionKey(e)?.agentId === t; } function isSessionId(e) { return typeof e === "string" && SESSION_ID_PATTERN.test(e); } function resolveGenerationStorePath(e, t, n) { return isIncognitoSessionKey(t) ? resolveIncognitoOpenClawAgentSqlitePath({ agentId: e }) : n; } async function readEntryInWorker(e) { const t = await withSessionEntryReadOnlyInWorker({ agentId: e.agentId, sessionKey: e.sessionKey, storePath: e.storePath }, e.assertCallerCurrent, async (e) => e); if (!t.ok) throw t.error; return t.value; } async function leaseSessionGeneration(e) { try { return await prepareSessionGenerationFacts({ agentId: e.agentId, sessionKey: e.sessionKey, storePath: resolveGenerationStorePath(e.agentId, e.sessionKey, e.storePath), sessionId: e.entry?.sessionId ?? null, exactTranscript: true, lifecycleRevision: e.entry?.lifecycleRevision ?? null }); } catch (e) { if (isSessionDeliveryGenerationRevokedError(e)) return; throw e; } } function assertRecordCurrent(e) { for (let t = e; t; t = t.parent) { if (t.state === "released") throw new Error("memory audience was released by its owner"); if (t.state === "stale") throw new Error("memory audience is no longer current"); for (const e of t.leases) try { e.assertCurrent(); } catch (e) { if (isSessionDeliveryGenerationRevokedError(e)) { t.state = "stale"; releaseRecordLeases(t); throw new Error("memory audience is no longer current", { cause: e }); } throw new Error("memory audience currency is unavailable; retry the operation", { cause: e }); } } } function mintMemoryAudience(e, t, n) { const r = Object.freeze(e); audienceRecords.set(r, n); audienceSessionKeys.set(r, t); for (let e = n; e; e = e.parent) e.holders += 1; collectedAudienceRecords.register(r, n); return { audience: r, release: () => { if (n.state !== "current") return; n.state = "released"; releaseRecordLeases(n); } }; } /** * Resolve from the current entry already admitted by the host turn owner. * Parent rows are read on the read-only worker; every hop holds a session * generation lease that is rechecked after the final await, before minting. */ async function resolveMemoryAudienceFromEntry(e, t) { let { sessionKey: n, sessionId: r, senderIsOwner: i } = e; const { agentId: a } = e; let o = a; let s = false; const c = e.assertCallerCurrent ?? (() => {}); const l = /* @__PURE__ */ new Set(); const u = { leases: [], state: "current", holders: 0 }; let d; let f = false; const p = e.scheduledParent?.senderIsOwner; const deny = (e, t) => { releaseRecordLeases(u); return { status: "denied", kind: e, reason: t }; }; try { for (let m = 0; m < MAX_LINEAGE_HOPS; m += 1) { if (!isAgentSessionKey(n, o) || !isSessionId(r) || l.has(n)) return deny("ineligible", `session lineage at ${n} is malformed or cyclic`); l.add(n); const h = o === a ? e.storePath : e.resolveAgentStorePath(o); const g = m === 0 ? t : await readEntryInWorker({ agentId: o, sessionKey: n, storePath: h, assertCallerCurrent: c }); if (!g || g.sessionId !== r || m > 0 && !f && g.lifecycleRevision !== d) { if (m === 0) return deny("unverified", `session ${n} no longer matches its admitted turn`); return deny("stale-lineage", `session ${e.sessionKey} has stale lineage: ancestor ${n} was reset or removed after its child was spawned. Respawn or recreate it from a current session to restore memory access; resetting it keeps the stale lineage.`); } const _ = await leaseSessionGeneration({ agentId: o, sessionKey: n, storePath: h, entry: g }); if (!_) return deny("unverified", `session ${n} changed while its memory audience was resolved`); u.leases.push(_); f = false; const v = m === 0 ? e.scheduledParent : void 0; if (v?.sessionKey === n) { if (g.sessionId !== v.sessionId || v.lifecycleRevision !== void 0 && g.lifecycleRevision !== v.lifecycleRevision) return deny("stale-lineage", `scheduled run session ${n} was reset or replaced after its automation was linked to it`); i = v.senderIsOwner; } else if (v && g.spawnedBy === void 0) { n = v.sessionKey; r = v.sessionId; d = v.lifecycleRevision; f = v.lifecycleRevision === void 0; i = v.senderIsOwner; continue; } if (g.spawnedBy !== void 0) { if (typeof g.spawnedBySenderIsOwner !== "boolean") return deny("stale-lineage", `spawned session ${n} predates memory lineage receipts (spawnedBySenderIsOwner), so it has no inherited memory audience. Respawn it from its parent session to restore memory access.`); if (!g.spawnedBy || g.parentSessionKey !== void 0 && g.parentSessionKey !== g.spawnedBy || !isSessionId(g.spawnedBySessionId) || g.parentSessionLifecycleRevision === "") return deny("ineligible", `spawned session ${n} has malformed lineage receipts`); const t = parseAgentSessionKey(g.spawnedBy)?.agentId; if (t && t !== o) { if (!e.resolveAgentStorePath || !g.spawnedBySenderIsOwner) return deny("ineligible", `session lineage at ${n} crosses agents without an owner spawn`); s = true; o = t; } n = g.spawnedBy; r = g.spawnedBySessionId; d = g.parentSessionLifecycleRevision; i = g.spawnedBySenderIsOwner; continue; } c(); assertRecordCurrent(u); if (g.chatType === "direct" && i === true && p !== false) return { status: "granted", ...mintMemoryAudience({ kind: "owner-private", agentId: a }, e.sessionKey, u) }; if (s) return deny("ineligible", `cross-agent lineage grants only owner-private memory; root session ${n} is not an owner direct chat`); if (g.chatType === "direct" || g.chatType === "group" || g.chatType === "channel") return { status: "granted", ...mintMemoryAudience({ kind: "conversation", agentId: a, sessionKey: n, sessionId: r }, e.sessionKey, u) }; return deny("ineligible", `root session ${n} has no durable chat type`); } return deny("ineligible", `session lineage exceeds ${MAX_LINEAGE_HOPS} hops`); } catch (e) { releaseRecordLeases(u); c(); return deny("unverified", `session storage could not verify the lineage: ${formatErrorMessage(e)}`); } } /** Return whether a memory audience was minted by this host process. */ function isHostMemoryAudience(e) { return typeof e === "object" && e !== null && audienceRecords.has(e); } /** Reject an audience presented outside its host-bound invocation session. */ function assertMemoryAudienceSession(e, t) { if (!isHostMemoryAudience(e)) throw new Error("memory audience was not minted by this host"); if (audienceSessionKeys.get(e) !== t) throw new Error("memory audience is bound to a different session"); } /** * Bind a child audience to the child session's current incarnation and to the * parent's lineage, so a child reset or reassignment rejects it before provider I/O. * A detached child has no row; its grant binds that absence instead. */ async function delegateMemoryAudience(e, t) { assertMemoryAudienceCurrent(e); const n = audienceRecords.get(e); const { agentId: r } = e; const i = t.assertCallerCurrent ?? (() => {}); if (!isAgentSessionKey(t.sessionKey, r)) throw new Error("memory audience delegation requires a session for the same agent"); const a = await readEntryInWorker({ agentId: r, sessionKey: t.sessionKey, storePath: t.storePath, assertCallerCurrent: i }); if (a ? typeof a.sessionId !== "string" || a.sessionId.length === 0 : t.detached !== true) throw new Error(`memory audience delegation requires an existing child session: ${t.sessionKey}`); const o = await leaseSessionGeneration({ agentId: r, sessionKey: t.sessionKey, storePath: t.storePath, entry: a }); if (!o) throw new Error(`child session changed during memory audience delegation: ${t.sessionKey}`); const s = { parent: n, leases: [o], state: "current", holders: 0 }; try { i(); assertRecordCurrent(s); } catch (e) { releaseRecordLeases(s); throw e; } return mintMemoryAudience({ ...e }, t.sessionKey, s); } /** Join admitted session publications without weakening the synchronous final guard. */ function prepareMemoryAudienceRead(e) { const t = audienceRecords.get(e); if (!t) throw new Error("memory audience was not minted by this host"); const n = []; try { for (let e = t; e; e = e.parent) { if (e.state !== "current") assertRecordCurrent(e); for (const t of e.leases) { const e = t.prepareRead(); if (e) n.push(e); } } } catch (e) { Promise.all(n).catch(() => {}); throw e; } if (n.length > 0) return Promise.all(n).then(() => prepareMemoryAudienceRead(e)); assertRecordCurrent(t); } /** Prepare only the host-owned audience; callers still recheck their full authority after await. */ function prepareMemoryCallerRead(e) { e.signal?.throwIfAborted(); const { authority: t } = e; if (t.kind === "session" && t.audience) { assertMemoryAudienceSession(t.audience, t.sessionKey); return prepareMemoryAudienceRead(t.audience); } } /** Reject a retained audience after any captured session incarnation changes. */ function assertMemoryAudienceCurrent(e) { const t = audienceRecords.get(e); if (!t) throw new Error("memory audience was not minted by this host"); assertRecordCurrent(t); } /** * Check a memory caller's whole authority: its own currency, its audience's * session binding and currency, and its abort signal. Final guards before * provider I/O or prompt publication use this, never the caller's check alone. */ function assertMemoryCallerCurrent(e) { e.assertCurrent(); const { authority: t } = e; if (t.kind === "session" && t.audience) { assertMemoryAudienceSession(t.audience, t.sessionKey); assertMemoryAudienceCurrent(t.audience); } e.signal?.throwIfAborted(); } //#endregion export { isHostMemoryAudience as a, resolveMemoryAudienceFromEntry as c, delegateMemoryAudience as i, assertMemoryAudienceSession as n, prepareMemoryAudienceRead as o, assertMemoryCallerCurrent as r, prepareMemoryCallerRead as s, assertMemoryAudienceCurrent as t };