UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,412 lines (1,411 loc) • 45.7 kB
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import "./session-key-CqAyZeVk.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { m as readDatabasePathIdentitySync } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs"; import "./sqlite-worker-contract--dxXkOty.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { u as resolveRuntimeFacadeModuleLocation } from "./facade-loader-08DBXZOS.mjs"; import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs"; import { n as captureSessionStoreCandidateIdentities, t as assertSessionStoreReadCandidate } from "./session-store-read-candidates-BjEE1iTg.mjs"; import { c as withSessionEntriesFromStoresInWorker, l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { a as normalizeStoreSessionKey, s as resolveSessionEntryCandidates, t as collectSessionEntryLookupKeys } from "./store-entry-BTUJi0xl.mjs"; import { n as captureSessionStoreReadCandidates } from "./session-store-target-inventory-Cf7beBnr.mjs"; import "./session-accessor-CizTbDQj.mjs"; import { F as bindNativeSessionDeletionParticipant, M as getSessionInitializationUpstreamLinkCurrent } from "./session-accessor.sqlite-entry-store-DmqxH0lm.mjs"; import { a as loadSessionEntryReadOnly } from "./session-accessor.sqlite-exact-read-CbvqUmsG.mjs"; import { n as captureSessionEntryCurrentRead, t as captureNativeSessionEntryCurrentRead } from "./session-entry-current-runtime-Csc_-WE9.mjs"; import { o as capturePreparedToolAuthorityReads } from "./host-private-capabilities-DDumj0c_.mjs"; import { _ as registerPluginStateIfAbsentInWorker, h as observePluginStateInWorker, r as comparePluginStateDeleteInWorker } from "./plugin-state-worker-client-CMavS4MT.mjs"; import { n as capturePluginStateNativeBindingStore } from "./plugin-state-store.native-binding-DP2rO8Qs.mjs"; import { a as prepareRegisterParams, s as validateKey } from "./plugin-state-store.validation-raTPI4hA.mjs"; import { t as assertLegacyPreparedToolAuthority } from "./tool-authority-preparation-BOURfTvP.mjs"; import { t as capturePluginStateNativeBindingFacts } from "./plugin-state-native-binding-facts-yC6smnLc.mjs"; import { t as captureSessionEntryCurrentCheckAsyncInternal } from "./session-entry-current-check-F4LSgnxb.mjs"; import { i as upsertSessionUpstreamLink, n as deleteSessionUpstreamLinkAsync, o as upsertSessionUpstreamLinkWithCurrentSource } from "./session-upstream-links-CrKTma32.mjs"; import { randomUUID } from "node:crypto"; import { AsyncLocalStorage } from "node:async_hooks"; import { isDeepStrictEqual } from "node:util"; //#region src/agents/harness/native-session/binding-leases.ts /** Legacy adapter for released native binding stores. */ function createNativeSessionBindingLeases(e, t) { if (!e.withCurrent) throw new Error(t.errors.atomicUpdatesRequired); const n = createNativeSessionBindingLeasesV2({ withCurrent: (t) => e.withCurrent(t), assertLeaseCurrent(n, r) { const i = e.lookup(n); const a = t.readRecord(i); if (i !== void 0 && !a) throw t.errors.invalidRow(n); if (a?.lease?.token !== r || a.lease.expiresAt <= Date.now()) throw t.errors.lostLease(n); } }, t); return { ...n, captureLeaseAssertion(e) { const t = n.captureLeaseAssertion(e); t(); return t; } }; } /** Worker-owned mutations publish the facts used by synchronous native effect guards. */ function createNativeSessionBindingLeasesV2(e, t) { if (!e.withCurrent) throw new Error(t.errors.atomicUpdatesRequired); const n = new AsyncLocalStorage(); const r = /* @__PURE__ */ new Map(); const assertSettled = (e) => { const t = r.get(e); if (t) throw t.error; }; const assertLeaseCurrent = (n, r) => { if (!r.facts) { if (!e.assertLeaseCurrent) throw new Error(t.errors.atomicUpdatesRequired); warnPluginSdkDeprecation({ family: "native-session-binding", method: "NativeSessionBindingStateStoreV2.assertLeaseCurrent", replacement: "withCurrent backed by api.runtime.state.openKeyedStoreV2" }); e.assertLeaseCurrent(n, r.token); return; } const i = readRecord(n, r.facts.read()); if (i?.lease?.token !== r.token || i.lease.expiresAt <= Date.now()) throw t.errors.lostLease(n); }; const update = async (t, n, r, i = []) => { const a = []; for (const e of new Set(i)) a.push(await e.prepareMutation()); const o = a.flatMap(({ sessionEntryCurrent: e }) => e ? [e] : []); const s = o.length ? { sources: o.flatMap(({ sources: e }) => e), assertCurrent: (e) => { let t = 0; for (const n of o) { n.assertCurrent(e.slice(t, t + n.sources.length)); t += n.sources.length; } } } : void 0; const c = e.withCurrent({ sessionEntryCurrent: s, assertCurrent: () => { r?.(); for (const e of a) e.assertCurrent(); } }); let l = await c.observe(t); while (true) { const e = n(l.value); const r = await c.compareAndApply(t, l.comparison, e.next === void 0 ? { operation: "update", action: "keep" } : { operation: "update", action: "set", value: e.next, ...e.ttlMs === void 0 ? {} : { ttlMs: e.ttlMs } }); if (r.status !== "conflict") return e.next !== void 0; l = r.current; } }; const transact = async (e, r, i, a, o) => { const s = performance.now() + t.lease.waitMs; while (true) { assertSettled(e); let c = false; let l = false; let u; const d = n.getStore()?.get(e); if (d && d.phase !== "held") throw t.errors.lostLease(e); if (d?.failure) throw d.failure; const f = d?.token; const assertOwnerCurrent = () => { a?.(); d?.assertCurrent?.(); assertSettled(e); if (d && (d.phase !== "held" || d.failure)) throw d.failure ?? t.errors.lostLease(e); }; assertOwnerCurrent(); await update(e, (t) => { c = false; l = false; const n = readRecord(e, t); const a = n?.lease; const o = Date.now(); if (f && (!a || a.token !== f || a.expiresAt <= o)) { l = true; return {}; } if (a && a.token !== f && a.expiresAt > o) { c = true; return {}; } const s = r(n, f); u = s.result; return { next: s.next, ttlMs: typeof i === "function" ? s.next && i(s.next) : i }; }, assertOwnerCurrent, [o, d?.authority].filter((e) => e !== void 0)); if (l) { const n = t.errors.lostLease(e); if (d) { materializeErrorStack(n); d.failure = n; } throw n; } if (!c) return u; if (performance.now() >= s) throw t.errors.leaseTimeout(e); await sleep(t.lease.retryIntervalMs); } }; const withLease = async (i, a, o) => { assertSettled(i); o.assertCurrent?.(); const s = n.getStore(); const c = s?.get(i); if (c) { if (c.phase !== "held") throw t.errors.lostLease(i); const e = c.failure; if (e) throw e; const n = await a(); o.assertCurrent?.(); const r = c.failure; if (r) throw r; return n; } const l = randomUUID(); const u = { token: l, phase: "held", assertCurrent: o.assertCurrent, authority: o.authority, renewalPending: () => d !== void 0, joinRenewal: async () => { await d; }, quiesce() { if (d || u.phase !== "held" || u.failure) throw u.failure ?? t.errors.lostLease(i); u.phase = "settling"; }, block(e, t) { materializeErrorStack(e); u.phase = "unknown"; u.failure = e; r.set(i, { error: e, custody: t }); } }; let d; let f; try { const r = await transact(i, (e) => { const n = o.prepareLease(e, { token: l, expiresAt: Date.now() + t.lease.staleMs }); return { result: n !== void 0, next: n }; }, void 0, o.assertCurrent, o.authority); o.assertCurrent?.(); if (!r) throw t.errors.acquisitionRejected(i); const c = capturePluginStateNativeBindingStore(e.withCurrent({ assertCurrent() {} })); if (c) u.facts = await capturePluginStateNativeBindingFacts(c, i); assertLeaseCurrent(i, u); const p = new Map(s); p.set(i, u); f = setInterval(() => { if (!d && u.phase === "held") d = renew(i, u).finally(() => { d = void 0; }); }, t.lease.renewIntervalMs); f.unref(); const m = await n.run(p, a); clearInterval(f); await d; o.assertCurrent?.(); if (u.failure) throw u.failure; return m; } finally { clearInterval(f); const e = u.phase === "unknown"; if (!e) u.phase = "closed"; try { await d; if (!e) try { await update(i, (e) => { const n = readRecord(i, e); if (n?.lease?.token !== l) return {}; const { lease: r, ...a } = n; return { next: readRecord(i, a), ttlMs: t.releaseTtlMs(i, n) }; }); } catch (e) { t.onReleaseFailure?.(i, e); } } finally { u.facts?.release(); } } }; const readRecord = (e, n) => { const r = t.readRecord(n); if (n !== void 0 && !r) throw t.errors.invalidRow(e); return r; }; const renew = async (e, n) => { if (n.failure || n.phase !== "held") return; try { if (!await update(e, (r) => { const i = readRecord(e, r); const a = i?.lease; const o = Date.now(); if (!i || !a || a.token !== n.token || a.expiresAt <= o) return {}; return { next: { ...i, lease: { token: n.token, expiresAt: o + t.lease.staleMs } } }; }, () => { n.assertCurrent?.(); if (n.phase !== "held" || n.failure) throw n.failure ?? t.errors.lostLease(e); }, n.authority ? [n.authority] : []) && n.phase === "held") { n.failure = t.errors.lostLease(e); materializeErrorStack(n.failure); } } catch (r) { if (n.phase === "held") { n.failure = t.errors.lostLease(e, r); materializeErrorStack(n.failure); } } }; const captureLeaseAssertion = (e) => { const r = n.getStore()?.get(e); if (!r || r.phase !== "held") throw t.errors.lostLease(e); const assertCurrent = () => { if (r.phase !== "held") throw t.errors.lostLease(e); try { assertLeaseCurrent(e, r); } catch (e) { throw r.failure ?? e; } }; return assertCurrent; }; return { captureLeaseAssertion, transact, withLease, hasLease: (e) => n.getStore()?.has(e) === true, owner: (e) => n.getStore()?.get(e), assertSettled, block(e, t, n) { materializeErrorStack(t); r.set(e, { error: t, custody: n }); } }; } //#endregion //#region src/agents/harness/native-session/binding-memory-settlement.ts /** Memory's FIFO awaits the shared writer, including compensation before releasing the queue. */ function createNativeSessionBindingMemorySettlement(e) { const { plan: t, participant: n } = e; const r = { pluginId: t.pluginId, namespace: t.namespace, key: t.key, maxEntries: t.maxEntries, overflowPolicy: t.overflowPolicy, context: e.context, env: e.env }; let i; const recordUnknown = (e) => { if (hasSqliteWorkerOutcomeUnknown(e)) n.settle("unknown", e instanceof Error ? e : void 0); throw e; }; return { async commit(a) { await n.joinRenewal(); n.quiesce(); const o = await observePluginStateInWorker({ ...r, assertCurrent: a }); const s = e.readRecord(o.value); const { lease: c, ...l } = s ?? {}; const assertBindingCurrent = () => { a(); if (t.predicate.kind === "absent" ? o.value !== void 0 : !s || c?.token !== t.predicate.token || c.expiresAt <= Date.now() || !isDeepStrictEqual(l, t.predicate.value)) throw new Error(t.deletionChanged); }; try { if ((await comparePluginStateDeleteInWorker({ ...r, assertCurrent: assertBindingCurrent, comparison: o.comparison, operation: "delete", action: t.predicate.kind === "absent" ? "keep" : "delete" })).status === "conflict") throw new Error(t.deletionChanged); i = asOptionalRecord(o.value); n.settle("committed"); } catch (e) { recordUnknown(e); } }, async rollback(e) { if (n.unknown) return; if (i && t.predicate.kind === "leased") try { const n = { ...i, lease: { token: t.predicate.token, expiresAt: Date.now() + t.staleMs } }; if (!await registerPluginStateIfAbsentInWorker({ ...r, assertCurrent: e, ...prepareRegisterParams(t.key, n, t.ttlMs) })) throw new Error(t.rollbackChanged); i = void 0; } catch (e) { recordUnknown(e); } n.settle("rolled-back"); } }; } //#endregion //#region src/agents/harness/native-session/binding-lifecycle.ts /** * @deprecated Use createNativeSessionBindingLifecycleV2. Supported through 2026-12-31. Removal in the first January 2027 stable release. */ function createNativeSessionBindingLifecycle(e, t) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "createNativeSessionBindingLifecycle", replacement: "createNativeSessionBindingLifecycleV2", compatibility: "The legacy adapter retains synchronous transaction-local mutation and settlement." }); return createNativeSessionBindingLifecycleOwner({ version: 1, state: e }, t); } /** Worker-owned binding coordination with an audited native deletion participant. */ function createNativeSessionBindingLifecycleV2(e, t) { return createNativeSessionBindingLifecycleOwner({ version: 2, state: e }, t); } function createNativeSessionBindingLifecycleOwner(e, t) { const { state: n } = e; const r = e.version === 1 ? createNativeSessionBindingLeases(e.state, t) : createNativeSessionBindingLeasesV2(e.state, t); const i = new AsyncLocalStorage(); let a = 0; let o = 0; let s = Promise.resolve(); let c; const waitForMutations = async () => { if (a === 0) return; await new Promise((e) => { c = e; }); }; const withMutation = async (e) => { if (i.getStore() === true) return await e(); if (o > 0) throw new Error(t.errors.mutationBlocked); a += 1; try { return await e(); } finally { a -= 1; if (a === 0) { const e = c; c = void 0; e?.(); } } }; const withExclusiveMutationFence = async (e) => { o += 1; const t = s.then(async () => { await waitForMutations(); return await i.run(true, e); }); s = t.then(() => void 0, () => void 0); try { return await t; } finally { o -= 1; } }; const withDeletion = async (i, a, o) => { r.assertSettled(i); const s = t.workerCodec ? capturePluginStateNativeBindingStore(n.withCurrent({ assertCurrent: a.assertCurrent })) : void 0; const c = (t.workerCodec === "codex" || t.workerCodec === "agentsapi") && s?.options.pluginId === t.workerCodec ? t.workerCodec : void 0; const l = c && s ? captureOpenClawStateWorkerContext({ env: s.options.env }) : void 0; const u = c ? resolveRuntimeFacadeModuleLocation({ dirName: c, artifactBasename: "native-session-binding-api.js" }) : void 0; if (u === null) throw new Error(`Native session binding codec is unavailable: ${c}`); const bindParticipant = (n, o, d) => { if (!s || !l || !c || !l.admission.identity.key.startsWith("file:")) return n; const f = /* @__PURE__ */ new Set(); const p = { binding: { codec: c, codecSource: u ? { rootDir: u.boundaryRoot, source: u.modulePath, origin: u.origin ?? "global" } : void 0, pluginId: s.options.pluginId, namespace: s.options.namespace, key: validateKey(i, "delete"), maxEntries: s.options.maxEntries, overflowPolicy: s.options.overflowPolicy, ttlMs: s.options.defaultTtlMs, staleMs: t.lease.staleMs, deletionChanged: t.errors.deletionChanged, rollbackChanged: t.errors.rollbackChanged, predicate: d ? { kind: "leased", token: d.token, value: o } : { kind: "absent" } }, source: l.admission.identity, assertCurrent() { l.admission.assertCurrent(); l.maintenanceScope?.assertAdmission(); s.assertCurrent?.(); a.assertCurrent(); if (d?.failure || d?.phase === "closed") throw d.failure ?? t.errors.lostLease(i); }, renewalPending: () => d?.renewalPending() ?? false, joinRenewal: async () => { await d?.joinRenewal(); }, quiesce: () => d?.quiesce(), retain: (e) => { f.add(e); }, unknown: false, settle(e, t) { if (e === "unknown") { p.unknown = true; const e = t ?? /* @__PURE__ */ new Error("Native binding settlement is unknown"); if (d) d.block(e, p); else r.block(i, e, p); } else if (d) d.phase = e === "committed" ? "deleted" : "held"; } }; if (e.version === 2) p.memoryMutation = createNativeSessionBindingMemorySettlement({ plan: p.binding, context: l, env: s.options.env, readRecord: t.readRecord, participant: p }); return bindNativeSessionDeletionParticipant(n, p); }; if (e.version === 2 && (!s || !l || !l.admission.identity.key.startsWith("file:"))) throw new Error("Native session binding deletion requires a worker-owned plugin-state store"); const d = e.version === 1 ? e.state : void 0; const f = d?.deleteIf?.bind(d); if (d && !f) throw new Error(t.errors.conditionalDeletionRequired); const p = { commit() { throw new Error("Native session binding deletion must commit through its worker participant"); }, rollback() { throw new Error("Native session binding deletion must roll back through its worker participant"); } }; return await withMutation(async () => { a.assertCurrent(); const e = await n.lookup(i); a.assertCurrent(); if (e === void 0) { if (!d) return await o(void 0, bindParticipant(p)); let e = true; try { return await o(void 0, bindParticipant({ commit() { a.assertCurrent(); if (!e || d.lookup(i) !== void 0) throw new Error(t.errors.deletionChanged); }, rollback() {} })); } finally { e = false; } } return await r.withLease(i, async () => { const e = r.owner(i); const s = t.readRecord(await n.lookup(i)); a.assertCurrent(); a.assertRecordCurrent(s); if (!s) throw new Error(t.errors.deletionChanged); const { lease: c, ...l } = s; if (!d) return await o(s, bindParticipant(p, l, e)); let u; let m = true; const assertActive = () => { a.assertCurrent(); if (!m || e.phase === "closed" || e.failure) throw e.failure ?? t.errors.lostLease(i); }; try { return await o(s, bindParticipant({ commit() { assertActive(); if (u) return; let n; if (!f(i, (r) => { const { lease: i, ...a } = t.readRecord(r) ?? {}; if (i?.token !== e.token || i.expiresAt <= Date.now() || !isDeepStrictEqual(a, l)) return false; n = r; return true; }) || !n) throw new Error(t.errors.deletionChanged); u = n; e.phase = "deleted"; }, rollback() { assertActive(); if (!u) return; const n = { ...u, lease: { token: e.token, expiresAt: Date.now() + t.lease.staleMs } }; if (!d.registerIfAbsent(i, n)) throw new Error(t.errors.rollbackChanged); u = void 0; e.phase = "held"; } }, l, e)); } finally { m = false; } }, a); }); }; return { captureLeaseAssertion: r.captureLeaseAssertion.bind(r), transact: r.transact, withLease: r.withLease, hasLease: r.hasLease, withMutation, withExclusiveMutationFence, withDeletion }; } //#endregion //#region src/agents/harness/native-session/binding-generation.ts /** @deprecated Use resolvePreparedNativeSessionBinding. Supported through 2026-12-31. Removal in the first January 2027 stable release. */ async function resolveNativeSessionBinding(e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "resolveNativeSessionBinding", replacement: "resolvePreparedNativeSessionBinding" }); let t = e.assertCurrent ?? (() => {}); const assertAdmissionCurrent = () => { t(); e.signal?.throwIfAborted(); }; assertAdmissionCurrent(); e.assertBinding?.(readOwnershipBinding(e)); const n = e.target?.sessionKey?.trim() ? captureNativeSessionGenerationAuthority({ ...e, target: e.target, assertCurrent: t }) : void 0; t = n?.assertCurrent ?? t; assertAdmissionCurrent(); let r = e.readBinding(); if (!r && n && e.target && e.generation) { if (!await reclaimPreparedGeneration$1({ ...e, generation: e.generation, reclaimStale: e.reclaimStale === true }, n, assertAdmissionCurrent) && e.reclaimStale) throw e.createSupersededError(e.target.sessionId); r = e.readBinding(); } assertAdmissionCurrent(); e.assertBinding?.(r); return { binding: r, assertCurrent: t }; } /** @deprecated Use reclaimNativeSessionGenerationWithAuthority. Supported through 2026-12-31. Removal in the first January 2027 stable release. */ async function reclaimNativeSessionGeneration(e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "reclaimNativeSessionGeneration", replacement: "reclaimNativeSessionGenerationWithAuthority" }); e.assertCurrent?.(); if (!e.target.sessionKey?.trim()) return true; const t = captureNativeSessionGenerationAuthority(e); if (t.state === "superseded") return false; return reclaimPreparedGeneration$1(e, t); } /** @deprecated Await retainNativeSessionGenerationAuthority. Supported through 2026-12-31. Removal in the first January 2027 stable release. */ function captureNativeSessionGenerationAuthority(e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "captureNativeSessionGenerationAuthority", replacement: "await retainNativeSessionGenerationAuthority()" }); const readEntry = () => { try { return readBindingSessionEntry(e); } catch { return null; } }; const t = readEntry(); const n = t?.sessionId === e.target.sessionId; const r = t === void 0 ? "ephemeral" : n ? "current" : "superseded"; const i = n ? t.previousSessionId : void 0; const assertHostCurrent = () => { if (r === "ephemeral") return; const t = readEntry(); if (r !== "current" || !t || t.sessionId !== e.target.sessionId || t.previousSessionId !== i) throw e.createSupersededError(e.target.sessionId); }; return { state: r, previousSessionId: i, assertHostCurrent, assertCurrent() { e.assertCurrent?.(); assertHostCurrent(); } }; } async function reclaimPreparedGeneration$1(e, t, n = t.assertCurrent) { const r = await e.generation.prepareReclaim(); n(); if (r.kind === "resolved") return r.result; if (t.state !== "current") return false; e.onHostGenerationVerified?.(t.assertHostCurrent); if (t.previousSessionId === r.expectedPreviousSessionId) { const r = await e.generation.adopt(t.previousSessionId, n); if (r !== "absent") return r !== "conflict"; } if (e.reclaimStale === false) return false; return e.generation.reclaim(r.expectedPreviousSessionId, n); } function readOwnershipBinding(e) { const t = e.readBinding(); if (t || !e.target) return t; const n = readBindingSessionEntry({ ...e, target: e.target }); return n?.sessionId === e.target.sessionId && n.previousSessionId ? e.readBinding(n.previousSessionId) : void 0; } function readBindingSessionEntry(e) { const { target: t } = e; return t.sessionKey?.trim() ? loadSessionEntryReadOnly({ agentId: t.agentId, sessionKey: t.sessionKey.trim(), storePath: e.storePath?.trim() || resolveSessionStorePathCore(e.config?.session?.store, { agentId: t.agentId }), hydrateSkillPromptRefs: false, readConsistency: "latest" }) : void 0; } //#endregion //#region src/agents/harness/native-session/binding-authority.ts async function captureNativePolicies(e, t) { const n = []; for (const r of e) { t?.(); try { n.push({ preparation: r, ...await capturePreparedToolAuthorityReads(r) }); } catch (e) { if (r.onRefused?.(e) !== "discarded") throw e; } } return n; } function assertLegacyNativePolicies(e) { const t = []; for (const n of e) try { n.preparation.assertCurrent(); t.push(n); } catch (e) { if (n.preparation.onRefused?.(e) !== "discarded") throw e; } for (const e of t) assertLegacyPreparedToolAuthority(e.preparation, e.reads); for (const e of t) e.preparation.assertCurrent(); } /** Bind live owner checks without acquiring any session lineage or storage. */ function createNativeSessionBindingScope(e) { return createPreparedNativeSessionBindingAuthority({ lineage: [], source: composeSessionSourceAssertion([]), entryChecks: [], assertCurrent: e }); } /** Prepared lineage stays current through the session entry owner's write publications. */ function createPreparedNativeSessionBindingAuthority(e) { const { lineage: t, source: n, entryChecks: r, assertCurrent: i } = e; const a = composeSessionSourceAssertion([n], (e) => { i(); e(); }); return { lineage: t, prepared: { source: n, entryChecks: r }, assertCurrent: a, assertLegacyCurrent: a, withLiveness: (t) => createPreparedNativeSessionBindingAuthority({ ...e, assertCurrent: t }), async withCurrent(e) { a(); return e(); }, async withPreparedCurrent(e, t) { i(); const n = await captureNativePolicies(t); if (n.some((e) => e.assertCompatibility)) return withSessionEntriesFromStoresInWorker([], () => { assertLegacyNativePolicies(n); a(); return e(); }); return readNativeSessionBindingEntries([], () => { a(); return e(); }, n); }, async prepareMutation() { a(); return { assertCurrent: a, sessionEntryCurrent: r.length ? { sources: r.map((e) => e.source), assertCurrent: (e) => { i(); r.forEach((t, n) => t.assertCurrent(e[n])); } } : void 0 }; } }; } function readNativeSessionBindingEntries(e, t, n = []) { const sameRead = (e, t) => e.agentId === t.agentId && e.sessionKey === t.sessionKey && e.storePath === t.storePath && e.env === t.env; const r = e.filter((t, n) => e.findIndex((e) => sameRead(e, t)) === n); const i = new Map(r.filter((e) => isIncognitoSessionKey(e.sessionKey)).map((e) => [e, captureNativeSessionEntryCurrentRead(e)])); const a = r.filter((e) => !i.has(e)); const o = a.map((e) => ({ ...e, snapshotFields: [], sessionKeys: [.../* @__PURE__ */ new Set([normalizeStoreSessionKey(e.sessionKey), ...collectSessionEntryLookupKeys(e.sessionKey)])] })); return withSessionEntriesFromStoresInWorker([...o, ...n.flatMap(({ reads: e }) => e.flatMap((e) => e.reads))], (o) => { const s = r.map((e) => { const t = a.indexOf(e); return t < 0 ? readNativeBindingLineage(i.get(e)) : resolveSessionEntryCandidates({ entries: o[t].result.entries, sessionKey: e.sessionKey, canonicalKeys: true }).existing?.entry; }); for (const e of o) e.assertCurrent(); let c = a.length; const l = []; for (const { preparation: e, reads: t } of n) { const n = c; c += t.reduce((e, t) => e + t.reads.length, 0); const assertPolicyCurrent = () => { let r = n; e.assertCurrent(); for (const e of t) { e.assertPrepared(o.slice(r, r + e.reads.length)); r += e.reads.length; } e.assertCurrent(); }; try { if (t.length) assertPolicyCurrent(); else e.assertCurrent(); l.push(assertPolicyCurrent); } catch (t) { if (e.onRefused?.(t) !== "discarded") throw t; } } for (const e of l) e(); for (const e of o) e.assertCurrent(); return t(e.map((e) => s[r.findIndex((t) => sameRead(t, e))])); }, { ordered: true }); } /** @deprecated Use createPreparedNativeSessionBindingAuthority with retained lineage or createNativeSessionBindingScope; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */ function createNativeSessionBindingAuthority(e, t) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "createNativeSessionBindingAuthority", replacement: "createPreparedNativeSessionBindingAuthority or createNativeSessionBindingScope" }); return createNativeSessionBindingAuthorityInternal(e, t); } function createNativeSessionBindingAuthorityInternal(e, t) { const assertEntry = (e, t) => { if (!t || t.sessionId !== e.sessionId || t.previousSessionId !== e.previousSessionId) throw e.createSupersededError(e.sessionId); }; const assertLegacyCurrent = () => { t(); for (const t of e) { let e; try { e = isIncognitoSessionKey(t.read.sessionKey) ? readNativeBindingLineage(captureNativeSessionEntryCurrentRead(t.read)) : loadSessionEntryReadOnly({ ...t.read, readConsistency: "latest", hydrateSkillPromptRefs: false }); } catch { throw t.createSupersededError(t.sessionId); } assertEntry(t, e); } }; const n = { lineage: e, assertCurrent: t, withCurrent: async (n) => { t(); return readNativeSessionBindingEntries(e.map(({ read: e }) => e), (r) => { t(); e.forEach((e, t) => assertEntry(e, r[t])); return n(); }); }, withPreparedCurrent: async (n, r) => { t(); const i = e.map(({ read: e }) => { if (isIncognitoSessionKey(e.sessionKey)) return captureNativeSessionEntryCurrentRead(e).assertSourceCurrent; const t = captureSessionStoreReadCandidates(e.storePath); const n = captureSessionStoreCandidateIdentities(t); return () => { for (const e of t) assertSessionStoreReadCandidate(e.path, t); for (const [e, t] of n) { const n = readDatabasePathIdentitySync(e); if (n.key !== t.key || n.canonicalPath !== t.canonicalPath || n.birthtime !== t.birthtime) throw new Error("Native session lineage source changed during tool preparation"); } }; }); const a = await captureNativePolicies(r, t); for (const e of i) e(); if (a.some((e) => e.assertCompatibility)) return withSessionEntriesFromStoresInWorker([], () => { assertLegacyNativePolicies(a); for (const e of i) e(); assertLegacyCurrent(); return n(); }); return readNativeSessionBindingEntries(e.map(({ read: e }) => e), (r) => { t(); for (const e of i) e(); e.forEach((e, t) => assertEntry(e, r[t])); return n(); }, a); }, prepareMutation: async () => { t(); const n = []; const r = []; const i = []; const a = new Map(e.filter(({ read: e }) => isIncognitoSessionKey(e.sessionKey)).map((e) => [e, captureNativeSessionEntryCurrentRead(e.read)])); for (const o of e) { const e = a.get(o); if (e) { const check = () => assertEntry(o, readNativeBindingLineage(e)); check(); i.push(check); continue; } await withSessionEntryReadOnlyInWorker(o.read, t, async (e, t) => { if (!e.ok) throw o.createSupersededError(o.sessionId); assertEntry(o, e.value); const a = captureSessionEntryCurrentRead(o.read, t); if (a.kind !== "file") { i.push(() => assertEntry(o, a.readCurrent())); return; } n.push({ source: a.source, assertCurrent: (e) => { a.assertSourceCurrent(); assertEntry(o, e); } }); r.push({ predicate: { source: a.source, sessionKey: a.source.sessionKey, fields: ["sessionId", "previousSessionId"], expected: { sessionId: o.sessionId, previousSessionId: o.previousSessionId } }, refuse: () => { throw o.createSupersededError(o.sessionId); } }); }); } const assertMutationCurrent = () => { t(); for (const e of i) e(); }; assertMutationCurrent(); return { assertCurrent: assertMutationCurrent, sessionEntryCurrent: n.length ? { sources: n.map((e) => e.source), assertCurrent: (e) => { n.forEach((t, n) => t.assertCurrent(e[n])); } } : void 0, sessionSource: { assertCurrent: assertMutationCurrent, assertPreparedCurrent: t, checks: r, nativeSource: i.length > 0 } }; }, assertLegacyCurrent }; Object.assign(n.assertLegacyCurrent, { nativeSource: e.some(({ read: e }) => isIncognitoSessionKey(e.sessionKey)), prepareSessionSource: async () => (await n.prepareMutation()).sessionSource }); return n; } function readNativeBindingLineage(e) { const t = e.readCurrent(); if (!t) return; const n = t.previousSessionId; if (n !== void 0 && typeof n !== "string") throw new Error("Native session lineage has an invalid predecessor"); return { sessionId: t.sessionId, previousSessionId: n }; } /** Combine borrowed owner facts without acquiring another lineage read. */ function combinePreparedNativeSessionBindingAuthority(...e) { const t = [...new Set(e.filter((e) => e !== void 0))]; if (t.length === 1) return t[0]; return createPreparedNativeSessionBindingAuthority({ lineage: t.flatMap(({ lineage: e }) => e), source: composeSessionSourceAssertion(t.map(({ prepared: e }) => e.source)), entryChecks: t.flatMap(({ prepared: e }) => e.entryChecks), assertCurrent: () => { for (const e of t) e.assertCurrent(); } }); } /** @deprecated Use combinePreparedNativeSessionBindingAuthority; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */ function combineNativeSessionBindingAuthority(...e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "combineNativeSessionBindingAuthority", replacement: "combinePreparedNativeSessionBindingAuthority" }); return combineNativeSessionBindingAuthorityInternal(...e); } function combineNativeSessionBindingAuthorityInternal(...e) { const t = [...new Set(e.filter((e) => e !== void 0))]; return createNativeSessionBindingAuthorityInternal(t.flatMap(({ lineage: e }) => e), () => { for (const e of t) e.assertCurrent(); }); } //#endregion //#region src/agents/harness/native-session/binding-generation-authority.ts /** * @deprecated Use resolvePreparedNativeSessionBinding and release its capture; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */ async function resolveNativeSessionBindingWithAuthority(e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "resolveNativeSessionBindingWithAuthority", replacement: "resolvePreparedNativeSessionBinding", compatibility: "The legacy binding callback retains its synchronous authority frame." }); return resolveNativeSessionBindingOwner(e, (t, n) => t.withCurrent(() => { const t = e.readBinding(); e.assertBinding?.(t ?? (n ? e.readBinding(n) : void 0)); return t; })); } /** The caller releases its captured lineage after the binding's final use and cleanup. */ async function resolvePreparedNativeSessionBinding(e) { const assertAdmissionCurrent = () => { e.assertCurrent?.(); e.signal?.throwIfAborted(); }; let t = e.generationAuthority; let n = true; const release = () => { n = false; t?.release(); }; try { assertAdmissionCurrent(); t ??= e.target?.sessionKey?.trim() ? await retainNativeSessionGenerationAuthority({ ...e, target: e.target, assertCurrent: assertAdmissionCurrent }) : void 0; const r = combinePreparedNativeSessionBindingAuthority(e.authority, t?.authority, createPreparedNativeSessionBindingAuthority({ lineage: [], source: composeSessionSourceAssertion([], () => { if (!n) throw new Error("Native session binding scope was released"); }), entryChecks: [], assertCurrent: assertAdmissionCurrent })); const readBinding = async (t) => { r.assertCurrent(); const n = await e.readBinding(); const i = n ?? (t ? await e.readBinding(t) : void 0); return r.withCurrent(() => { e.assertBinding?.(i); return n; }); }; let i = await readBinding(t?.previousSessionId); if (!i && t && e.target && e.generation) { if (!await reclaimPreparedGeneration({ ...e, generation: e.generation, reclaimStale: e.reclaimStale === true }, { ...t, authority: r }, assertAdmissionCurrent) && e.reclaimStale) throw e.createSupersededError(e.target.sessionId); i = await readBinding(); } else if (!i) e.assertBinding?.(i); return { binding: i, authority: r, release }; } catch (e) { release(); throw e; } } async function resolveNativeSessionBindingOwner(e, t) { const assertAdmissionCurrent = () => { e.assertCurrent?.(); e.signal?.throwIfAborted(); }; assertAdmissionCurrent(); const n = e.target?.sessionKey?.trim() ? await prepareNativeSessionGenerationAuthorityInternal({ ...e, target: e.target, assertCurrent: assertAdmissionCurrent }) : void 0; const r = combineNativeSessionBindingAuthorityInternal(e.authority, n?.authority ?? createNativeSessionBindingAuthorityInternal([], assertAdmissionCurrent)); let i = await t(r, n?.previousSessionId); if (!i && n && e.target && e.generation) { if (!await reclaimPreparedGeneration({ ...e, generation: e.generation, reclaimStale: e.reclaimStale === true }, { ...n, authority: r }, assertAdmissionCurrent) && e.reclaimStale) throw e.createSupersededError(e.target.sessionId); i = await t(r); } else if (!i) e.assertBinding?.(i); return { binding: i, authority: r }; } /** Let the authoritative OpenClaw generation adopt its predecessor or reclaim a stale row. */ async function reclaimNativeSessionGenerationWithAuthority(e) { e.assertCurrent?.(); if (!e.target.sessionKey?.trim()) return true; const t = await retainNativeSessionGenerationAuthority(e); try { if (t.state === "superseded") return false; return await reclaimPreparedGeneration(e, t); } finally { t.release(); } } /** Select lineage once; the session owner publishes every in-process change until release. */ async function retainNativeSessionGenerationAuthority(e) { e.assertCurrent?.(); const t = resolveGenerationRead(e); let n; try { if (t.sessionKey) n = await captureSessionEntryCurrentCheckAsyncInternal({ ...t, matchGeneration: false, fields: ["sessionId", "previousSessionId"] }); e.assertCurrent?.(); } catch (t) { n?.release(); e.assertCurrent?.(); throw t; } const r = n?.entry; const i = r?.sessionId === e.target.sessionId; const a = r === void 0 ? "ephemeral" : i ? "current" : "superseded"; const o = i ? r?.previousSessionId : void 0; if (a !== "current") { n?.release(); n = void 0; } let s = true; const refuse = () => { throw e.createSupersededError(e.target.sessionId); }; const c = composeSessionSourceAssertion([n?.source], (e) => { if (!s || a === "superseded") refuse(); try { e(); } catch { refuse(); } }); const l = n?.entryCurrent; return { state: a, previousSessionId: o, authority: createPreparedNativeSessionBindingAuthority({ lineage: i ? [{ read: t, sessionId: e.target.sessionId, previousSessionId: o, createSupersededError: e.createSupersededError }] : [], source: c, entryChecks: l ? [{ source: l.source, assertCurrent: (e) => { if (!s) refuse(); try { l.assertCurrent(e); } catch { refuse(); } } }] : [], assertCurrent: () => { e.assertCurrent?.(); if (a === "superseded") refuse(); } }), release() { if (s) { s = false; n?.release(); } } }; } /** @deprecated Use retainNativeSessionGenerationAuthority and release its capture; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */ async function prepareNativeSessionGenerationAuthority(e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "prepareNativeSessionGenerationAuthority", replacement: "retainNativeSessionGenerationAuthority" }); return prepareNativeSessionGenerationAuthorityInternal(e); } async function prepareNativeSessionGenerationAuthorityInternal(e) { const t = resolveGenerationRead(e); const n = await (async () => { try { return t.sessionKey ? await readNativeSessionBindingEntries([t], ([t]) => { e.assertCurrent?.(); return t; }) : void 0; } catch { e.assertCurrent?.(); return null; } })(); const r = n?.sessionId === e.target.sessionId; const i = n === void 0 ? "ephemeral" : r ? "current" : "superseded"; const a = r ? n?.previousSessionId : void 0; return { state: i, previousSessionId: a, authority: createNativeSessionBindingAuthorityInternal(i === "current" ? [{ read: t, sessionId: e.target.sessionId, previousSessionId: a, createSupersededError: e.createSupersededError }] : [], () => { e.assertCurrent?.(); if (i === "superseded") throw e.createSupersededError(e.target.sessionId); }) }; } async function reclaimPreparedGeneration(e, t, n = t.authority.assertCurrent) { const r = await e.generation.prepareReclaim(); await t.authority.withCurrent(n); if (r.kind === "resolved") return r.result; if (t.state !== "current") return false; if (t.previousSessionId === r.expectedPreviousSessionId) { const n = await e.generation.adopt(t.previousSessionId, t.authority); if (n !== "absent") return n !== "conflict"; } if (e.reclaimStale === false) return false; return e.generation.reclaim(r.expectedPreviousSessionId, t.authority); } function resolveGenerationRead(e) { return { agentId: e.target.agentId, sessionKey: e.target.sessionKey?.trim() ?? "", storePath: e.storePath?.trim() || resolveSessionStorePathCore(e.config?.session?.store, { agentId: e.target.agentId }) }; } //#endregion //#region src/agents/harness/native-session/initialization.ts /** Backend binding ownership redeems the existing host initializer's exact creation handle. */ function createNativeSessionInitializationOwner(e) { const t = /* @__PURE__ */ new WeakMap(); return { /** Capture cleanup ownership before any potentially committing binding or link write. */ prepare(n) { const { initialization: r, bindingStore: i, identity: a } = n; r.assertCurrent(); const o = getSessionInitializationUpstreamLinkCurrent(r); const s = o?.context ?? captureOpenClawStateWorkerContext(); const c = { path: s.admission.databasePath, env: s.environment }; const assertCurrent = () => { s.admission.assertCurrent(); r.assertCurrent(); }; const assertRollbackCurrent = () => { s.admission.assertCurrent(); r.assertRollbackCurrent(); }; let l; const u = { store: i, identity: structuredClone(a), assertCleanupAllowed: n.assertCleanupAllowed, cleanup: async () => { r.assertRollbackCurrent(); if (l && await deleteSessionUpstreamLinkAsync(l.sessionKey, l.agentId, { ...c, expected: l, assertCommitAllowed: assertRollbackCurrent }) === "changed") throw new Error(e.errors.linkChanged); r.assertRollbackCurrent(); await d?.(r.assertRollbackCurrent); r.assertRollbackCurrent(); } }; t.set(r, u); const d = n.prepareCleanup?.(); const prepareLink = (e) => { const t = Date.now(); l = structuredClone({ ...e, createdAt: t, updatedAt: t }); return { ...c, now: t, ifAbsent: true, assertCommitAllowed: assertCurrent }; }; const acceptLink = (t) => { if (!t) { l = void 0; throw new Error(e.errors.linkWriteFailed); } }; return { assertCurrent: r.assertCurrent, async bind(t) { r.assertCurrent(); u.binding = e.validateBinding(t); if (!await e.writeBinding(i, a, u.binding, r.assertCurrent)) { u.binding = void 0; throw new Error(e.errors.bindingChanged); } r.assertCurrent(); }, /** @deprecated Await linkAsync; removed in the first January 2027 stable release, after the final compatibility day 2026-12-31. */ link(e) { warnPluginSdkDeprecation({ family: "native-session-binding", method: "createNativeSessionInitializationOwner.prepare.link", replacement: "createNativeSessionInitializationOwner.prepare.linkAsync" }); r.assertCurrent(); const t = prepareLink(e); acceptLink(upsertSessionUpstreamLink(e, t)); r.assertCurrent(); }, async linkAsync(e) { assertCurrent(); const t = prepareLink(e); acceptLink(await upsertSessionUpstreamLinkWithCurrentSource(e, t, o)); assertCurrent(); } }; }, getRollback(n, r, i, a) { const o = r.initialization; if (!o) return; o.assertRollbackCurrent(); const s = t.get(o); if (!s && !a) return; if (!s || s.store !== n || !isDeepStrictEqual(s.identity, i) || a && !isDeepStrictEqual(s.binding, a)) throw new Error(e.errors.ownerChanged); s.assertCleanupAllowed?.(); return s.cleanup; } }; } //#endregion export { resolvePreparedNativeSessionBinding as a, combinePreparedNativeSessionBindingAuthority as c, createPreparedNativeSessionBindingAuthority as d, captureNativeSessionGenerationAuthority as f, createNativeSessionBindingLifecycleV2 as g, createNativeSessionBindingLifecycle as h, resolveNativeSessionBindingWithAuthority as i, createNativeSessionBindingAuthority as l, resolveNativeSessionBinding as m, prepareNativeSessionGenerationAuthority as n, retainNativeSessionGenerationAuthority as o, reclaimNativeSessionGeneration as p, reclaimNativeSessionGenerationWithAuthority as r, combineNativeSessionBindingAuthority as s, createNativeSessionInitializationOwner as t, createNativeSessionBindingScope as u };