UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

482 lines (481 loc) • 23 kB
import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { g as isReservedSystemAgentId, i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { a as isSameOpenClawAgentDatabasePath } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { A as tryResolveLegacyCompatibilityAgentId, O as tryResolveAmbientOwnerAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import { a as isSqliteCorruptionError, o as isSqliteLockError, p as sqliteErrorCode, r as formatSqliteReadOnlyInspectionFailure } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { S as resolveAgentCreationClaimAgentId, m as AgentDatabaseStartupPublicationError } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs"; import { a as resolveSqliteDatabaseFilePaths } from "./sqlite-files-rWisKj_V.mjs"; import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs"; import { m as openClawStateDatabaseCache } from "./openclaw-state-db-cache-CkwtTqzF.mjs"; import { o as isTerminalSqliteIntegrityError } from "./sqlite-integrity-CCmEgO_m.mjs"; import { n as runWithSqliteDatabaseAdmissionTurn } from "./sqlite-database-admission-turn-BZSVGNZi.mjs"; import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs"; import { n as quotePowerShellArg, t as quoteCliArg } from "./quote-cli-arg-J7A9UE6m.mjs"; import fs from "node:fs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/infra/sqlite-recovery-files.ts /** Offline SQLite recovery preserves journals before moving the main pathname. */ function moveSqliteFilesAside(e, t) { const n = inspectSqliteRecoveryFiles(e); const r = planSqliteRecoveryMoves(n.existing); const i = []; try { for (const n of r.toSorted((t, n) => { if (t.sourcePath === e) return 1; if (n.sourcePath === e) return -1; return t.sourcePath.localeCompare(n.sourcePath); })) { t(); fs.renameSync(n.sourcePath, n.destinationPath); i.push(n); } } catch (n) { const r = []; const a = []; for (const e of i.toReversed()) try { t(); if (fs.lstatSync(e.sourcePath, { throwIfNoEntry: false })) throw new Error(`rollback source was recreated: ${e.sourcePath}`, { cause: n }); fs.renameSync(e.destinationPath, e.sourcePath); } catch (t) { r.push(t); a.push(e.destinationPath); } if (r.length > 0) { const t = r.map((e) => String(e)).join("; "); throw new Error(`Could not move corrupt SQLite file set aside or restore it: ${e}; rollback failures: ${t}. Preserved recovery files: ${a.join(", ")}`, { cause: n }); } throw n; } return { movedFiles: r.map((e) => e.destinationPath), skippedFiles: n.missing }; } function inspectSqliteRecoveryFiles(e) { const t = []; const n = []; for (const r of resolveSqliteDatabaseFilePaths(e)) { const e = fs.lstatSync(r, { throwIfNoEntry: false }); if (!e) n.push(r); else if (!e.isFile()) throw new Error(`SQLite recovery path is not a regular file: ${r}`); else t.push(r); } return { existing: t, missing: n }; } function planSqliteRecoveryMoves(e) { const t = `.corrupt-${Date.now()}`; for (let n = 0; n < 100; n += 1) { const r = n === 0 ? t : `${t}.${n}`; const i = e.map((e) => ({ destinationPath: `${e}${r}`, sourcePath: e })); if (i.every((e) => !fs.lstatSync(e.destinationPath, { throwIfNoEntry: false }))) return i; } throw new Error(`Could not choose recovery paths for ${e[0] ?? "SQLite files"}`); } //#endregion //#region src/infra/state-migrations.agent-owner-guidance.ts function formatAgentDatabaseCorruptionRepairHint(e, t) { if (formatSqliteReadOnlyInspectionFailure(t).includes("creating its private snapshot:")) return; if (!collectNestedErrorCandidates(t).some((e) => isSqliteCorruptionError(e) || ["SQLITE_CORRUPT", "SQLITE_NOTADB"].includes(sqliteErrorCode(e) ?? "") || e instanceof Error && isTerminalSqliteIntegrityError(e))) return; return `Stop the Gateway, back up this database and its SQLite sidecars, then run "${formatCliCommand(`openclaw doctor --session-sqlite recover --session-sqlite-agent ${quoteCliArg(e)}`)}" against the same state/config. Recovery repairs supported index corruption or preserves damaged files with a .corrupt-<timestamp> suffix. Restore a verified backup if you need the previous sessions, then restart the Gateway.`; } function formatAgentDatabaseOwnershipRepairHint(e) { const t = planSqliteRecoveryMoves(resolveSqliteDatabaseFilePaths(e).filter((e) => fs.lstatSync(e, { throwIfNoEntry: false }))); t.sort((t, n) => Number(t.sourcePath === e) - Number(n.sourcePath === e)); const n = t.map(({ sourcePath: e, destinationPath: t }) => process.platform === "win32" ? `Move-Item -LiteralPath ${quotePowerShellArg(e)} -Destination ${quotePowerShellArg(t)} -ErrorAction Stop` : `mv -n -- ${quoteCliArg(e)} ${quoteCliArg(t)}`).join(process.platform === "win32" ? "; " : " && "); return `Preserve and inspect this database before accepting a fresh agent. With all OpenClaw processes stopped, the explicit quarantine move is${process.platform === "win32" ? " (PowerShell)" : ""}:\n${n}\nThen run openclaw doctor --fix and restart the Gateway.`; } //#endregion //#region src/state/agent-database-admission.ts function createAgentDatabaseAdmissionErrorShape(e) { const t = e.code === "agent-database-inspection-pending"; return { code: "UNAVAILABLE", message: `${e.reason}\n${e.repairHint}`, details: e, retryable: t, ...t ? { retryAfterMs: 250 } : {} }; } const refusalCauses = /* @__PURE__ */ new WeakMap(); const readAdmissions = /* @__PURE__ */ new Map(); const refusalsByState = /* @__PURE__ */ new Map(); const startupFtsRepairs = /* @__PURE__ */ new Map(); function recordAgentDatabaseStartupFtsRepair(e, t, n) { if (n === void 0 && startupFtsRepairs.has(e)) throw new Error("Startup FTS repair was already attempted. Run openclaw doctor --fix."); startupFtsRepairs.set(e, { statePath: t, message: n }); if (n) createSubsystemLogger("state/agent-db").warn(n); } function listAgentDatabaseStartupFtsRepairs() { const e = stateKey({}); return [...startupFtsRepairs.values()].flatMap((t) => t.statePath === e && t.message ? [t.message] : []); } const preparation = new AsyncLocalStorage(); /** * Background work that a preparation started (such as model discovery) writes later as an * ordinary caller: refused while admission is pending, admitted once the database is. */ function runOutsideAgentDatabasePreparation(e) { return preparation.exit(e); } /** Startup owns isolated native workers until preparation settles, including failed admission. */ function retainAgentDatabaseStartupWorker(e, t, n) { const r = preparation.getStore(); if (r?.access !== "write" || r.refusal.agentId !== e || r.key !== stateKey(t)) return false; r.assertCurrent(); r.workers.defer(() => racePromiseWithAbortSignal(n(), r.signal)); return true; } function createAgentDatabaseInspectionRefusal(e) { const t = resolveUpdateRehearsalRoot(process.env) && e.reason.includes("creating its private snapshot:") && /(?:code=(?:ENOSPC|EDQUOT)\b|errcode=13\b)/u.test(e.reason); const n = collectNestedErrorCandidates(e.cause).some((e) => e instanceof Error && e.name === "DataCloneError"); const r = !e.pending && isSqliteLockError(e.cause); const i = e.cause instanceof AgentDatabaseStartupPublicationError; const a = { agentId: e.agentId, paths: e.paths, code: e.pending ? "agent-database-inspection-pending" : "agent-database-inspection-failed", reason: r ? "database locked by another process" : e.reason, repairHint: r ? "Close other processes accessing this database, then restart the Gateway to retry admission. Lock contention does not require database repair." : t ? "Free space in the reported snapshot cache, then retry the update. This candidate snapshot failure does not require repairing the serving database." : n ? "A worker request could not be serialized. Update OpenClaw and restart the Gateway; repeating database migration will not repair this request." : i ? "Sessions remain unavailable because newer config or plugin changes kept replacing this agent's runtime preparation. Restart the Gateway to retry admission. This failure does not require database repair." : e.pending ? "Sessions remain unavailable until background inspection and preparation finish. If they cannot complete, stop the Gateway, run \"openclaw doctor --fix\", and restart." : `Sessions remain unavailable. ${formatAgentDatabaseCorruptionRepairHint(e.agentId, e.cause) ?? "Stop the Gateway, run \"openclaw doctor --fix\" to inspect and repair this agent database, and restart."}` }; refusalCauses.set(a, e.cause); return a; } function stateKey(e) { return resolveOpenClawStateSqlitePath(e.env ?? process.env); } function sameKnownState(e, t) { if (e === t) return true; const n = openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(e); const r = openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(t); return Boolean(n && r && n.key === r.key); } function createAgentDatabaseHeldRefusal(e, t) { return { agentId: e, paths: t, code: "agent-database-held", reason: `Agent ${e} database is held for explicit restoration.`, repairHint: "Run openclaw doctor --fix for restoration guidance, then restore the preserved store with agents add. Held databases are not live agents." }; } /** Explicit restoration releases only the physical paths its hold writer committed. */ function releaseAgentDatabaseHeldAdmission(e, t = {}) { const n = refusalsByState.get(stateKey(t)); if (!n) return; for (const [t, r] of n.refusals) { let i = false; const a = admissionRefusalParts(r).flatMap((t) => { if (t.code !== "agent-database-held") return [t]; const n = t.paths.filter((t) => !e.some((e) => isSameOpenClawAgentDatabasePath(t, e))); if (n.length === t.paths.length) return [t]; i = true; return n.length ? [{ ...t, paths: n }] : []; }); if (!i) continue; const o = mergeAdmissionRefusals(a); if (o) n.refusals.set(t, o); else n.refusals.delete(t); sessionChanges.emit({ all: true, scope: { agentId: t, topology: true } }); } } /** Capture existing pending decisions; a later commit must never revoke their successors. */ function captureAgentDatabasePreparationDeletionForIdentity(e, { identityKey: t, databasePath: n }) { const r = normalizeAgentId(e); const i = [...refusalsByState].flatMap(([e, i]) => { const a = openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(e); const o = i.refusals.get(r); return (e === n || a?.key === t) && o?.code === "agent-database-inspection-pending" ? [{ key: e, owner: i, refusal: o }] : []; }); return () => { if (openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(n)?.key !== t) return; for (const { key: e, owner: t, refusal: a } of i) { if (refusalsByState.get(e) !== t || t.refusals.get(r) !== a || !sameKnownState(e, n)) continue; const i = new Map(t.refusals); i.set(r, createAgentDatabaseInspectionRefusal({ ...a, reason: `Agent ${r} was deleted during startup inspection` })); t.refusals = i; } }; } /** Capture only the live preparation whose native command must report fresh journal facts. */ function captureAgentDatabasePreparationJournal(e, t = {}) { const n = preparation.getStore(); if (!n || n.refusal.agentId !== normalizeAgentId(e) || !sameKnownState(n.key, stateKey(t))) return; const assertCurrent = () => { if (!n.active) throw new Error(`Agent database preparation has ended: ${e}`); n.assertCurrent(); }; assertCurrent(); return (e) => { assertCurrent(); if (e !== false) throw new Error(`Agent ${n.refusal.agentId} was deleted during startup inspection`); }; } /** Ownership is derived from the inspected file; missing or corrupt metadata keeps normal refusal. */ function inspectAgentDatabaseAdmission(e) { const t = normalizeAgentId(e.agentId); const n = e.metadata; if (n?.role !== "agent" || !n.agentId || n.agentId === t) return; return { agentId: t, paths: [e.path], embeddedOwnerId: n.agentId, code: "agent-database-ownership-mismatch", reason: `Refused agent ${t}: database ${e.path} belongs to agent ${n.agentId}; requested agent ${t}.`, repairHint: formatAgentDatabaseOwnershipRepairHint(e.path) }; } function canIsolateAgentDatabase(e, t) { return listAgentIds(e).includes(t) && !isReservedSystemAgentId(t) && t !== tryResolveAmbientOwnerAgentId(e) && t !== tryResolveLegacyCompatibilityAgentId(e); } function admissionRefusalParts(e) { const t = refusalCauses.get(e); return t instanceof AggregateError && t.errors.length > 0 && t.errors.every((t) => t instanceof AgentDatabaseAdmissionError && t.refusal.agentId === e.agentId) ? t.errors.flatMap((e) => admissionRefusalParts(e.refusal)) : [e]; } function mergeAdmissionRefusals(e) { if (e.length < 2) return e[0]; const t = { ...e.find((e) => e.code === "agent-database-ownership-mismatch") ?? e.find((e) => e.code !== "agent-database-held" && e.code !== "agent-database-inspection-pending") ?? e.find((e) => e.code === "agent-database-held") ?? e[0], paths: [...new Set(e.flatMap((e) => e.paths))], reason: e.map((e) => e.reason).join("\n"), repairHint: e.map((e) => e.repairHint).join("\n") }; refusalCauses.set(t, new AggregateError(e.map((e) => new AgentDatabaseAdmissionError(e)))); return t; } /** Admission and explicit restoration own these decisions; file edits never clear a live refusal. */ function recordAgentDatabaseAdmissions(e, t = {}) { const n = stateKey(t); const r = t.source ?? "diagnostic"; if (r === "diagnostic" && refusalsByState.get(n)?.source === "startup") return; const i = /* @__PURE__ */ new Map(); for (const t of e) { const e = i.get(t.agentId); if (e === t) continue; const n = e ? mergeAdmissionRefusals([...admissionRefusalParts(e), ...admissionRefusalParts(t)]) : t; i.set(t.agentId, n); } refusalsByState.set(n, { source: r, refusals: i }); } function hasAgentDatabaseAdmissions(e = {}) { return refusalsByState.has(stateKey(e)); } function readAgentDatabaseAdmissionRefusal(e, t = {}) { return readSelectedAgentDatabaseAdmissionRefusal(stateKey(t), normalizeAgentId(e), e); } /** Read readiness never releases writable admission or certifies unchecked database pages. */ function readAgentDatabaseReadAdmissionRefusal(e, t = {}) { return readSelectedAgentDatabaseReadAdmissionRefusal(stateKey(t), normalizeAgentId(e), e); } function readSelectedAgentDatabaseReadAdmissionRefusal(e, t, n) { const r = readSelectedAgentDatabaseAdmissionRefusal(e, t, n, "read"); const i = r && readAdmissions.get(r); if (r?.code === "agent-database-inspection-pending" && i?.key === e) try { i.assertCurrent(); return; } catch {} return r; } /** The startup owner publishes only inspected schemas, and revokes them when its work settles. */ function publishPendingAgentDatabaseReadAdmission(e, t) { t.assertCurrent(); const n = stateKey(t); if (e.code !== "agent-database-inspection-pending" || refusalsByState.get(n)?.refusals.get(e.agentId) !== e) throw new Error(`Agent database admission changed before read preparation: ${e.agentId}`); const r = { key: n, paths: t.paths, assertCurrent: t.assertCurrent }; readAdmissions.set(e, r); runWithAgentDatabaseReadAdmissionTurn = runWithInspectionReadAdmissionTurn; isAgentDatabaseStartupReadReady = inspectAgentDatabaseStartupReadReady; return () => { if (readAdmissions.get(e) === r) { readAdmissions.delete(e); if (readAdmissions.size === 0) { runWithAgentDatabaseReadAdmissionTurn = runWithSqliteDatabaseAdmissionTurn; isAgentDatabaseStartupReadReady = noStartupReadAdmission; } if (refusalsByState.get(n)?.refusals.has(e.agentId)) sessionChanges.invalidate({ all: true, scope: { agentId: e.agentId, topology: true } }); } }; } /** Only an exact inspected physical path may bypass its pending writable preparation. */ const noStartupReadAdmission = () => false; let isAgentDatabaseStartupReadReady = noStartupReadAdmission; function inspectAgentDatabaseStartupReadReady(e, t = {}) { for (const n of refusalsByState.get(stateKey(t))?.refusals.values() ?? []) if (readAdmissions.get(n)?.paths.includes(e) && !readAgentDatabaseReadAdmissionRefusal(n.agentId, t)) return true; return false; } /** Inspected files can serve snapshots while their writable integrity scan holds its turn. */ let runWithAgentDatabaseReadAdmissionTurn = runWithSqliteDatabaseAdmissionTurn; function runWithInspectionReadAdmissionTurn(e, t, n = [], r, i = {}) { const a = refusalsByState.get(stateKey(i))?.refusals.size ? e.filter((e) => !isAgentDatabaseStartupReadReady(e, i)) : e; return runWithSqliteDatabaseAdmissionTurn(a, t, n, r, i); } function assertAgentDatabaseReadAdmitted(e, t = {}) { const n = readAgentDatabaseReadAdmissionRefusal(e, t); if (n) throw new AgentDatabaseAdmissionError(n); } function readSelectedAgentDatabaseAdmissionRefusal(e, t, n, r = "write") { const i = refusalsByState.get(e)?.refusals.get(t); if (i?.code === "agent-database-held" && admissionRefusalParts(i).every((e) => e.code === "agent-database-held") && resolveAgentCreationClaimAgentId(t, e) === t) return; const a = preparation.getStore(); if (a && a.key === e && a.refusal.agentId === t) { if (a.access === "read" && (r === "write" || !a.active)) return i; if (!a.active) throw new Error(`Agent database preparation has ended: ${n}`); a.assertCurrent(); if (a.refusal === i) return; } return i; } /** Preparation borrows only its own pending admission; public callers remain refused. */ async function preparePendingAgentDatabase(e, t, n) { await withPendingAgentDatabasePreparation(e, t, "write", n); sessionChanges.emit({ all: true, scope: { agentId: e.agentId, topology: true } }); } /** Early publication and its descendants can inspect secrets/models, never write the database. */ async function preparePendingAgentDatabaseRead(e, t, n) { await withPendingAgentDatabasePreparation(e, t, "read", n); } async function withPendingAgentDatabasePreparation(e, t, n, r) { const i = stateKey(t); const assertCurrent = () => { t.assertCurrent(); if (e.code !== "agent-database-inspection-pending" || refusalsByState.get(i)?.refusals.get(e.agentId) !== e) throw new Error(`Agent database admission changed during preparation: ${e.agentId}`); }; assertCurrent(); const a = { key: i, refusal: e, assertCurrent, access: n, active: true, signal: t.signal, workers: new AsyncDisposableStack() }; try { await preparation.run(a, async () => { try { var e = _usingCtx(); e.a(a.workers); await r(); } catch (t) { e.e = t; } finally { await e.d(); } }); a.assertCurrent(); if (n === "write") { const t = refusalsByState.get(i); const n = new Map(t.refusals); n.delete(e.agentId); t.refusals = n; } } finally { a.active = false; } } function failPendingAgentDatabase(e, t, n) { const r = stateKey(n); const i = refusalsByState.get(r); if (i?.refusals.get(e.agentId) !== e) return; const a = new Map(i.refusals); a.set(e.agentId, createAgentDatabaseInspectionRefusal({ ...e, reason: formatErrorMessage(t), cause: t })); i.refusals = a; } function listAgentDatabaseAdmissionRefusals(e = {}) { return [...refusalsByState.get(stateKey(e))?.refusals.values() ?? []]; } var AgentDatabaseAdmissionError = class extends Error { constructor(e) { super(`Agent ${e.agentId} (${e.paths.join(", ")}): ${e.reason}\n${e.repairHint}`, { cause: refusalCauses.get(e) }); this.refusal = e; this.name = "AgentDatabaseAdmissionError"; } }; /** A proven owner mismatch needs operator action; unavailable inspections prove no mismatch. */ function isAgentDatabaseOwnershipMismatchError(e) { return collectNestedErrorCandidates(e).some((e) => e instanceof AgentDatabaseAdmissionError && e.refusal.code === "agent-database-ownership-mismatch"); } function assertAgentDatabaseAdmitted(e, t = {}) { const n = readAgentDatabaseAdmissionRefusal(e, t); if (n) throw new AgentDatabaseAdmissionError(n); } /** Capture only the selector; refusal decisions and the caller's preparation remain live. */ function captureAgentDatabaseAdmission(e, t = {}) { const n = stateKey(t); const r = normalizeAgentId(e); const i = t.access === "read"; return () => { const t = i ? readSelectedAgentDatabaseReadAdmissionRefusal(n, r, e) : readSelectedAgentDatabaseAdmissionRefusal(n, r, e); if (t) throw new AgentDatabaseAdmissionError(t); }; } /** Standalone diagnostics derive the same facts without borrowing another process's decision. */ async function evaluateAgentDatabaseAdmissions(e, t = {}) { const { preflightOpenClawDatabaseSchemas: n } = await import("./openclaw-database-preflight-BB0y4HYJ.mjs"); const { resolveConfiguredAgentDatabaseCandidatePaths: r } = await import("./targets-cXkr4Sqy.mjs"); const i = t.env ?? process.env; return (await n({ env: i, configuredAgentDatabaseTargets: [], configuredAgentDatabaseCandidatePaths: r(e, { env: i }), agentAdmissionConfig: e }, "runtime")).agentRefusals ?? []; } //#endregion export { formatAgentDatabaseCorruptionRepairHint as A, readAgentDatabaseReadAdmissionRefusal as C, retainAgentDatabaseStartupWorker as D, releaseAgentDatabaseHeldAdmission as E, inspectSqliteRecoveryFiles as M, moveSqliteFilesAside as N, runOutsideAgentDatabasePreparation as O, readAgentDatabaseAdmissionRefusal as S, recordAgentDatabaseStartupFtsRepair as T, listAgentDatabaseAdmissionRefusals as _, captureAgentDatabaseAdmission as a, preparePendingAgentDatabaseRead as b, createAgentDatabaseAdmissionErrorShape as c, evaluateAgentDatabaseAdmissions as d, failPendingAgentDatabase as f, isAgentDatabaseStartupReadReady as g, isAgentDatabaseOwnershipMismatchError as h, canIsolateAgentDatabase as i, formatAgentDatabaseOwnershipRepairHint as j, runWithAgentDatabaseReadAdmissionTurn as k, createAgentDatabaseHeldRefusal as l, inspectAgentDatabaseAdmission as m, assertAgentDatabaseAdmitted as n, captureAgentDatabasePreparationDeletionForIdentity as o, hasAgentDatabaseAdmissions as p, assertAgentDatabaseReadAdmitted as r, captureAgentDatabasePreparationJournal as s, AgentDatabaseAdmissionError as t, createAgentDatabaseInspectionRefusal as u, listAgentDatabaseStartupFtsRepairs as v, recordAgentDatabaseAdmissions as w, publishPendingAgentDatabaseReadAdmission as x, preparePendingAgentDatabase as y };