UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

356 lines (355 loc) • 14.1 kB
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { i as assertExistingDatabaseIdentity } from "./sqlite-worker-identity-BH8ZkJU9.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { f as hasLiveAgentRunContext } from "./agent-run-registry-D7vkrqFT.mjs"; import { f as sessionEntryCommitGuardOptions, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { t as bindAgentRunTerminalWriteContext } from "./agent-run-terminal-writes-eqeCFAOx.mjs"; import { g as resolveAdmittedRunActiveAssertion, l as getAdmittedRunDelegatedAuthority } from "./admitted-run-context-D3Jvk_f_.mjs"; import { c as isKnownCliHistoryBoundary, l as runWithCliHistoryWriter, t as CLI_HISTORY_CHANGED_BEFORE_PREPARATION } from "./cli-history-boundary-TFiQsBFz.mjs"; import { t as captureSessionActorStorageOwner } from "./session-actor-storage-binding-DMwpDsij.mjs"; import { n as resolveSessionTranscriptReadFence } from "./session-transcript-read-fence-Bl-ZY3_t.mjs"; import "./session-accessor-CizTbDQj.mjs"; import { l as waitForSessionTranscriptProjection } from "./session-transcript-reconcile-CtdkqWN1.mjs"; import { i as patchSessionEntryCore } from "./session-accessor.sqlite-entry-Da3xxVPX.mjs"; import { i as captureOwnedTranscriptWriteAssertion } from "./transcript-write-context-_7rz2F7z.mjs"; import { t as withSessionTranscriptReadSource } from "./session-transcript-read-source-cqwUFa0e.mjs"; import { r as resolveSessionTranscriptDatabasePath } from "./session-accessor.transcript-target-njOktg4F.mjs"; import { n as readSessionTranscriptAnchorsAsync } from "./session-transcript-anchor-read-BUt-Wh3r.mjs"; import { l as resolveNativeCliLoginOwner, n as isNativeCliLoginAttestationEnabled, r as readAttestedNativeCliLoginOwner } from "./cli-credentials-BaPg7qWx.mjs"; import { n as applySkillEnvOverridesFromSnapshot } from "./env-overrides-CAhWtW9f.mjs"; import { n as buildSessionContext } from "./session-manager-codec-DTi9FkQE.mjs"; import { n as createCliRunCurrentAssertion, r as resolveCliExecutionTarget } from "./execution-target-whyiKvuS.mjs"; import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs"; import { t as resolveCliChildEnv } from "./execution-env-BmqW_atJ.mjs"; //#region src/agents/cli-runner/history-boundary.ts /** * Another writer or lifecycle owns the session history. Local session state, not a provider * failure: model fallback must stop instead of replaying the turn on another candidate. */ var CliHistoryOwnerChangedError = class extends Error { constructor() { super("CLI history owner changed before preparation"); this.name = "CliHistoryOwnerChangedError"; } }; /** * Execution layers the run's skill env overrides onto the process environment right before it * builds the child environment. Apply the same snapshot here, synchronously, so preparation * resolves the login the child will actually run under. */ function resolvePreparedChildEnv(e, t) { const n = e.skillsSnapshot && !e.controlOperation ? applySkillEnvOverridesFromSnapshot({ snapshot: e.skillsSnapshot, config: e.config }) : void 0; try { return resolveCliChildEnv(t, e).env; } finally { n?.(); } } /** The transcript a turn may read saved inputs from: none when it runs without saved history. */ function replayableTarget(e) { return e?.replaysHistory ? e.target : void 0; } /** * History belongs to the local transcript, not the latest native handle. Cover only * a proven-empty start or the contiguous events of the previously admitted CLI run. * An account transition, old-runtime write, import or unknown legacy prefix stays * unknown until an explicitly empty context starts a new history boundary. */ async function prepareCliHistoryBoundary(e, t) { try { return await prepareCliHistoryBoundaryOnce(e, t); } catch (t) { if (e.abortSignal?.aborted || !(t instanceof Error) || t.message !== "CLI history changed before preparation") throw t; } return prepareCliHistoryBoundaryOnce(e, t); } /** Compaction may rewrite a covered transcript, but cannot establish account provenance. */ async function prepareCliHistoryCompactionBoundary(e, t) { const n = composeSessionSourceAssertion([t, captureOwnedTranscriptWriteAssertion(e)]); await waitForSessionTranscriptProjection(e); n(); const r = (await readSessionTranscriptAnchorsAsync(e, { entryIds: [], contextAuthority: true })).contextAuthority; n(); const i = r?.entry; const a = i?.cliHistoryBoundary; if (!r || !i || i.sessionId !== e.sessionId || !isKnownCliHistoryBoundary(a) || a.sessionId !== e.sessionId || a.generation !== r.watermark.generation || a.maxSeq !== r.watermark.maxSeq) return; return async () => { n(); const t = (await readSessionTranscriptAnchorsAsync(e, { entryIds: [], contextAuthority: true })).contextAuthority; n(); if (!t) return; const r = sessionEntryCommitGuardOptions(n); await patchSessionEntryCore(e, (e) => { const n = e.cliHistoryBoundary; if (e.sessionId !== i.sessionId || e.lifecycleRevision !== i.lifecycleRevision || e.activeWriterRunId !== i.activeWriterRunId || !isKnownCliHistoryBoundary(n) || n.sessionId !== a.sessionId || n.authFingerprint !== a.authFingerprint || n.writerRunId !== a.writerRunId || n.generation !== a.generation || n.maxSeq !== a.maxSeq) return {}; return { cliHistoryBoundary: { ...a, ...t.watermark } }; }, { preserveActivity: true, skipMaintenance: true, ...r, workerGuard: { ...r.workerGuard, cliHistory: { sessionId: e.sessionId, watermark: t.watermark } } }); }; } async function prepareCliHistoryBoundaryOnce(e, t) { const n = e.sessionTarget; if (e.sessionManager || !n || n.sessionId !== e.sessionId || e.sessionKey !== void 0 && e.sessionKey !== n.sessionKey || !resolveAdmittedRunActiveAssertion(e.admittedRunContext, e.abortSignal)) return; const r = { ...n, storePath: resolveSessionTranscriptDatabasePath(n) }; const i = resolveSessionTranscriptReadFence(r); const a = i && structuredClone(i); const o = createCliRunCurrentAssertion(e); const s = captureOwnedTranscriptWriteAssertion(r); const { credential: c, preparedBackend: l } = t; const u = !c && l ? resolvePreparedChildEnv(e, l) : void 0; const d = normalizeProviderId(e.provider); const f = c || !u || !isNativeCliLoginAttestationEnabled(d, e.config) || resolveCliExecutionTarget({ params: e, backendId: d }).kind === "node" ? void 0 : await resolveNativeCliLoginOwner(d, u); if (f) o(); const p = f?.owner; const m = { credential: c, nativeLoginOwner: p }; const h = captureSessionActorStorageOwner(r, { assertCurrent: o, authorize() {} }); let assertPhysicalSource = () => { h?.owner?.assertCurrent(); h?.binding?.actor.assertReadable(); }; const g = h ? await planCliHistoryBoundary(e, m, { ...r, storePath: h.path }, a, o) : await withSessionTranscriptReadSource(r, ({ scope: t, expectedIdentity: n, assertCurrent: i }) => { const s = { ...r, storePath: t.storePath }; assertPhysicalSource = () => { if (n) assertExistingDatabaseIdentity(s.storePath, n.key, n.birthtime); }; return planCliHistoryBoundary(e, m, s, a, () => { i(); o(); }); }, e.abortSignal); if (!g) return; const { target: _, snapshot: v, watermark: y, boundary: b, allowed: x, writerRunId: S } = g; const C = composeSessionSourceAssertion([o], (e) => { e(); h?.authority.assertCurrent(); assertPhysicalSource(); }); C(); const w = sessionEntryCommitGuardOptions(composeSessionSourceAssertion([C, composeSessionSourceAssertion([s], (e) => { if (v.activeWriterRunId !== void 0 && v.activeWriterRunId !== S && hasLiveAgentRunContext(v.activeWriterRunId)) throw new CliHistoryOwnerChangedError(); e(); })])); if (!await patchSessionEntryCore(_, (t) => { if (t.sessionId !== _.sessionId || t.lifecycleRevision !== v.lifecycleRevision || t.activeWriterRunId !== v.activeWriterRunId || e.expectedLifecycleRevision !== void 0 && t.lifecycleRevision !== e.expectedLifecycleRevision) throw new CliHistoryOwnerChangedError(); return { activeWriterRunId: S, cliHistoryBoundary: b }; }, { preserveActivity: true, skipMaintenance: true, onCommitted: (t) => { const n = e.sessionEntry; if (n?.sessionId === v.sessionId && n.lifecycleRevision === v.lifecycleRevision && n.activeWriterRunId === v.activeWriterRunId) n.activeWriterRunId = t.activeWriterRunId; }, ...w, workerGuard: { ...w.workerGuard, cliHistory: { sessionId: _.sessionId, admission: a, watermark: y } } }) || !x || b.state !== "known") return; const T = resolveAdmittedRunActiveAssertion(e.admittedRunContext); const assertWriterCurrent = () => { e.assertCurrent?.(); if (!T) throw new Error("CLI history writer is no longer active"); T(); }; let E = u; let D = false; let O; const readNativeOwner = () => { if (E === void 0) return; try { return readAttestedNativeCliLoginOwner(d, E); } catch { return; } }; const nativeLoginMatches = () => !p || !D && !O && readNativeOwner() === p; const checkNativeLoginBoundary = (e, t) => { const n = !p || D ? void 0 : readNativeOwner(); if (!p || n === p) return; if (e) throw new Error(t ?? "CLI history authority changed before execution"); if (D || n !== void 0 || E === void 0) { D = true; return; } O ??= resolveNativeCliLoginOwner(d, E).then((e) => { D ||= e.owner !== p; }, () => { D = true; }).finally(() => { O = void 0; }); }; const refreshDue = () => p !== void 0 && f?.refreshDueAt !== void 0 && f.refreshDueAt <= Date.now(); const k = { target: { ..._ }, runId: S, authFingerprint: b.authFingerprint, lifecycleRevision: v.lifecycleRevision, bindsNativeLogin: p !== void 0, replaysHistory: !refreshDue(), assertCurrent: assertWriterCurrent, assertReadable: async () => { assertWriterCurrent(); assertPhysicalSource(); const t = h ? void 0 : (await readSessionTranscriptAnchorsAsync(_, { entryIds: [], contextAuthority: true }, e.abortSignal)).contextAuthority; assertWriterCurrent(); assertPhysicalSource(); const n = h?.binding?.actor.target.sessionKey === _.sessionKey ? h.binding.actor.snapshot(h.authority) : h?.owner?.readSession(_.sessionKey, h.authority); const r = h ? n?.entry : t?.entry; const i = r?.cliHistoryBoundary; const a = h ? n?.transcript.watermark : t?.watermark; if (!r || r.sessionId !== _.sessionId || r.lifecycleRevision !== v.lifecycleRevision || r.activeWriterRunId !== S || !isKnownCliHistoryBoundary(i) || i.sessionId !== _.sessionId || i.writerRunId !== S || i.authFingerprint !== b.authFingerprint || !a || i.generation !== a.generation || i.maxSeq !== a.maxSeq) throw new Error("CLI history authority changed before execution"); checkNativeLoginBoundary(k.replaysHistory); }, ...p !== void 0 ? { confirmsOwner: nativeLoginMatches } : {}, checkNativeLoginBoundary, bindExecutionEnv: (e, t) => { E = e; checkNativeLoginBoundary(t, "CLI history authority changed before execution: the spawn environment selects a different Claude login than the one attested at preparation"); }, settleNativeLogin: async () => { await O; if (p && E !== void 0 && !D && refreshDue()) await resolveNativeCliLoginOwner(d, E).catch(() => void 0); } }; const A = getAdmittedRunDelegatedAuthority(e.admittedRunContext); if (!A) throw new Error("CLI history writer is no longer active"); bindAgentRunTerminalWriteContext(A, { run: (e) => runWithCliHistoryWriter({ ...k, assertCurrent: assertPhysicalSource }, e) }); return k; } async function planCliHistoryBoundary(e, t, n, r, i) { await waitForSessionTranscriptProjection(n, e.abortSignal); i(); const a = await readSessionTranscriptAnchorsAsync(n, { entryIds: [], contextAuthority: true, ...r ? { contextValidation: { admission: r } } : {} }, e.abortSignal); i(); const o = a.contextAuthority; const s = o?.entry; if (!o || !s || s.sessionId !== n.sessionId) return; const { watermark: c } = o; const l = r ? r.rawSeq - 1 : c.maxSeq; const u = !r || c.maxSeq === r.rawSeq; const d = s.cliHistoryBoundary; const { credential: f, nativeLoginOwner: p } = t; const m = f?.type === "oauth" ? f.accountId?.trim() || f.email?.trim() ? [ "oauth", f.provider, f.accountId, f.email, f.clientId, f.enterpriseUrl, f.projectId ] : void 0 : f?.type === "api_key" && f.key?.trim() ? [ "api_key", f.provider, f.key ] : f?.type === "token" && f.token?.trim() ? [ "token", f.provider, f.token ] : p ? ["native-login", p] : void 0; const h = m ? sha256Hex(JSON.stringify([ "cli-history-v1", normalizeProviderId(e.provider), m ])) : void 0; const g = e.expectedWriterRunId ?? e.runId; let _ = Boolean(h && u && e.cliSessionBinding?.forceReuse !== true && isKnownCliHistoryBoundary(d) && d.sessionId === n.sessionId && d.authFingerprint === h && d.generation === c.generation && (d.maxSeq === l || r && d.writerRunId === g && d.maxSeq === c.maxSeq)); if (!_ && h && u && !e.cliSessionId && !e.cliSessionBinding) { let t = false; const r = (await SessionManager.openBoundedAsync(n, { signal: e.abortSignal, maxBytes: 1048576, maxEvents: 100, onTruncated: () => { t = true; } })).getBranch(); i(); const a = r.findLastIndex((e) => e.type === "reset" || e.type === "compaction"); const o = r[a]; const s = a > 0 && o?.type === "reset" && o.firstKeptEntryId === void 0; _ = (!t || s) && buildSessionContext(r).messages.length === 0; } _ &&= c.maxSeq === null || typeof c.generation === "string"; if (!_ && !d) return; return { target: n, snapshot: s, watermark: c, boundary: _ && h ? { version: 1, sessionId: n.sessionId, state: "known", authFingerprint: h, generation: c.generation, maxSeq: c.maxSeq, writerRunId: g } : { version: 1, sessionId: n.sessionId, state: "unknown" }, allowed: _, writerRunId: g }; } //#endregion export { prepareCliHistoryCompactionBoundary as n, replayableTarget as r, prepareCliHistoryBoundary as t };