UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

549 lines (548 loc) • 19.8 kB
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs"; import { d as sleepWithAbort, o as racePromiseWithAbortSignal, s as raceWithTimeout } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { r as withAgentDatabasePreparationContext } from "./agent-database-preparation-context-CkVoUMTY.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { a as isSameOpenClawAgentDatabasePath, n as createOpenClawAgentDatabasePathMatcher } from "./openclaw-agent-db.paths-DJxv80ws.mjs"; import { S as readSqliteDatabaseCleanClose, a as getOrLoadSqliteDatabaseAdmissionForPath, g as prepareSqliteDatabaseAdmission } from "./sqlite-database-admission-DQIqro3d.mjs"; import { t as OPENCLAW_AGENT_SCHEMA_VERSION } from "./openclaw-schema-versions-E_10NoI6.mjs"; import { o as isSqliteLockError } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { b as schemaAdmission } from "./sqlite-schema-facts-B1bVE8IB.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { _ as withSqliteReadOnlyWorkerScope } from "./sqlite-readonly-worker-D3pRJU7r.mjs"; import { a as WorkerTaskError } from "./src-Dkfkl2Oz.mjs"; import { f as AgentDatabaseSchemaAdmissionChangedError, m as AgentDatabaseStartupPublicationError } from "./openclaw-agent-db-resources-Dp8HvLsg.mjs"; import "./worker-task-pool-BshJjv1P.mjs"; import { r as readSqliteIntegrityFileIdentity } from "./sqlite-file-generation-DHPWG9de.mjs"; import { r as cloneEnvWithPlatformSemantics } from "./config-env-vars-ByeGN-9N.mjs"; import { t as createPermitPool } from "./permit-pool-DR3Z0pxU.mjs"; import "./openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { o as sessionChanges } from "./session-row-changes-BA4BqVwF.mjs"; import { S as readAgentDatabaseAdmissionRefusal, _ as listAgentDatabaseAdmissionRefusals, b as preparePendingAgentDatabaseRead, f as failPendingAgentDatabase, n as assertAgentDatabaseAdmitted, t as AgentDatabaseAdmissionError, u as createAgentDatabaseInspectionRefusal, x as publishPendingAgentDatabaseReadAdmission, y as preparePendingAgentDatabase } from "./agent-database-admission-CL6wHJ_N.mjs"; import { s as readAgentDeletionJournalStatusInWorker } from "./agent-deletion-journal.read-DjOO2RZM.mjs"; import { t as GATEWAY_STARTUP_ADMISSION_WAIT_MS } from "./startup-unavailable-DEGJREFb.mjs"; import "./backoff-B-fIQi7C.mjs"; import { t as retryAsync } from "./retry-D-ulnYII.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; //#region src/state/agent-database-startup.helpers.ts function recoveryTiming(e, t = performance.now()) { return { elapsedMs: Math.round(t - e.startedAt), phaseDurationsMs: { ...e.phaseDurationsMs, [e.phase]: Math.round((e.phaseDurationsMs[e.phase] ?? 0) + t - e.phaseStartedAt) } }; } function matchesInspectionPath(e, t, n = isSameOpenClawAgentDatabasePath) { return e.some((e) => { try { return n(e, t); } catch { return false; } }); } //#endregion //#region src/state/agent-database-startup.ts const PREPARATION_PROGRESS_INTERVAL_MS = 6e4; const STARTUP_PUBLICATION_ATTEMPTS = 4; const log = createSubsystemLogger("state/agent-admission"); const startupAdmission = new AsyncLocalStorage(); var AgentDatabaseStartupSupersededError = class extends Error { constructor(e, t) { super(`Agent ${e} ${t} preparation was superseded`); this.name = "AgentDatabaseStartupSupersededError"; } }; /** Startup owns readers until the Gateway adopts them; only the Gateway activates agents. */ var AgentDatabaseStartupAdmission = class { constructor(e = true) { this.deferInspections = e; this.controller = new AbortController(); this.activation = createDeferredCore(); this.work = /* @__PURE__ */ new Set(); this.pending = /* @__PURE__ */ new Map(); this.adopted = false; this.activated = false; this.stopped = false; this.publication = Promise.resolve(); this.opening = createPermitPool(2); this.migrating = createPermitPool(4); this.journalReads = createPermitPool(8); } get signal() { return this.controller.signal; } get isStopped() { return this.stopped; } startProgress() { this.progressTimer ??= setInterval(() => { const e = performance.now(); for (const [t, n] of this.pending) log.warn("agent database startup preparation still running", { agentId: t, phase: n.phase, elapsedMs: Math.round(e - n.startedAt), phaseElapsedMs: Math.round(e - n.phaseStartedAt), ...n.phase === "publication-wait" ? { publishingAgentId: this.publishingAgentId } : {} }); }, PREPARATION_PROGRESS_INTERVAL_MS); this.progressTimer.unref(); } clearProgress() { clearInterval(this.progressTimer); this.progressTimer = void 0; } /** Bootstrap reuses this startup's compatibility headers; writable opens retain admission. */ prepareSchemaHeaders(e) { const t = { statePath: resolveOpenClawStateSqlitePath(e), headers: /* @__PURE__ */ new Map() }; this.preparedSchemaHeaders = t; return (e) => { return ({ version: n, writerAppVersion: r, agentSchemaMeta: i }) => { if (!this.stopped && this.preparedSchemaHeaders === t && n === 38) t.headers.set(e, { version: n, writerAppVersion: r, agentSchemaMeta: i }); }; }; } takePreparedSchemaHeaders(e) { const t = this.preparedSchemaHeaders; this.preparedSchemaHeaders = void 0; return (n, r) => { const i = t?.headers.get(n); return !this.stopped && t?.statePath === resolveOpenClawStateSqlitePath(e) && i?.version === r ? i : void 0; }; } recordStateSchemaPreparation(e) { const t = this.preparedSchemaHeaders; if (this.stopped || t?.statePath !== resolveOpenClawStateSqlitePath(e)) return; const n = getOrLoadSqliteDatabaseAdmissionForPath(t.statePath, schemaAdmission, () => void 0); const r = prepareSqliteDatabaseAdmission(t.statePath); if (n && r) t.state = { identity: r, schemaAdmissionId: n.admissionId }; } takePreparedStateSchema(e) { const t = this.preparedSchemaHeaders; const n = t?.state; if (!t || !n || t.statePath !== resolveOpenClawStateSqlitePath(e)) return; const assertCurrent = () => { const e = getOrLoadSqliteDatabaseAdmissionForPath(t.statePath, schemaAdmission, () => void 0); if (this.stopped || prepareSqliteDatabaseAdmission(t.statePath) !== n.identity || e?.admissionId !== n.schemaAdmissionId) throw new Error("Prepared startup state schema changed before source inspection"); }; try { assertCurrent(); return assertCurrent; } catch { return; } } /** Joins startup work already scheduled before a background consumer begins. */ get pendingPreparation() { return this.work.size > 0 ? Promise.allSettled(this.work) : void 0; } get hasPendingAgents() { return this.pending.size > 0; } /** Join only the current agent preparation, without holding channel startup or healthy agents. */ waitForAgentPreparation(e, t = {}) { const n = this.pending.get(normalizeAgentId(e)); if (!n || readAgentDatabaseAdmissionRefusal(e, t) !== n.refusal) return; const r = t.signal ? AbortSignal.any([this.signal, t.signal]) : this.signal; if (!t.forWrite) { const e = t.forWrite === false ? n.readReady : n.completion; return e && racePromiseWithAbortSignal(e, r); } const i = GATEWAY_STARTUP_ADMISSION_WAIT_MS + Math.ceil(this.pending.size / 2) * 6e4; return raceWithTimeout(n.completion, i, () => { throw new AgentDatabaseAdmissionError({ ...n.refusal, repairHint: "This agent is still preparing. Retry the request after background inspection and preparation finish." }); }, { signal: r, ref: false }).then(() => assertAgentDatabaseAdmitted(e, t)); } track(e) { this.work.add(e); e.then(() => this.work.delete(e), () => this.work.delete(e)); } scheduling(e, t, n) { const r = createOpenClawAgentDatabasePathMatcher(); return { signal: this.signal, canDefer: (e) => this.deferInspections && e.agentId !== void 0 && n.has(e.agentId) && matchesInspectionPath(t, e.path, r), cleanClose: (e) => { try { return readSqliteDatabaseCleanClose(e.path); } catch { return false; } }, track: (e) => this.track(e), defer: (t, n) => this.defer({ env: e, inspections: t, reason: n }) }; } recordInspectionFailure(e, t, n) { this.signal.throwIfAborted(); if (!e.agentId) return false; (t.agentRefusals ??= []).push(createAgentDatabaseInspectionRefusal({ agentId: e.agentId, paths: [e.path], reason: formatErrorMessage(n), cause: n })); return true; } captureRefusals(e) { return new Map(listAgentDatabaseAdmissionRefusals({ env: e }).filter((e) => this.pending.get(e.agentId)?.refusal === e).map((e) => [e.agentId, e])); } reuseRefusal(e, t, n) { const r = e.agentId && n?.get(e.agentId); if (!r || !matchesInspectionPath(r.paths, e.path)) return false; (t.agentRefusals ??= []).push(r); return true; } defer(e) { this.signal.throwIfAborted(); const t = cloneEnvWithPlatformSemantics(e.env); const n = /* @__PURE__ */ new Map(); for (const t of e.inspections) { const e = t.target.agentId; if (!e) throw new Error(`Cannot defer a database without an agent owner: ${t.target.path}`); n.set(e, [...n.get(e) ?? [], t]); } const r = []; for (const [i, a] of n) { const n = [...new Set(a.map(({ target: e }) => e.path))]; const o = createAgentDatabaseInspectionRefusal({ agentId: i, paths: n, pending: true, reason: `Agent ${i} has not completed startup inspection and preparation. ${e.reason}` }); const s = performance.now(); const c = createDeferredCore(); const l = createDeferredCore(); const u = { refusal: o, completion: c.promise, readReady: l.promise, startedAt: s, phase: "inspection", phaseStartedAt: s, phaseDurationsMs: {} }; const phase = (e) => { const t = performance.now(); u.phaseDurationsMs = recoveryTiming(u, t).phaseDurationsMs; u.phase = e; u.phaseStartedAt = t; }; this.pending.set(i, u); this.startProgress(); r.push(o); log.info(o.reason, { agentId: i, paths: n }); const d = n.map((e) => { try { return { pathname: e, identity: readSqliteIntegrityFileIdentity(e) }; } catch (t) { return { pathname: e, error: t }; } }); const f = Promise.allSettled(a.map(({ result: e }) => e)); const p = runInDetachedAsyncContext(async () => { const e = {}; let r; const s = createDeferredCore(); const releasePublication = () => { if (this.publishingAgentId === i) this.publishingAgentId = void 0; s.resolve(); }; try { const c = await f; phase("activation"); const p = await this.activation.promise; if (!p || this.stopped) return; const assertLifetimeCurrent = () => { this.signal.throwIfAborted(); if (!p.isCurrent() || this.pending.get(i) !== u) throw new Error(`Gateway no longer owns preparation for agent ${i}`); }; const assertCurrent = () => { assertLifetimeCurrent(); for (const e of d) { if (!e.identity) throw e.error; readSqliteIntegrityFileIdentity(e.pathname, e.identity); } }; const assertNotDeleted = async () => { const e = await retryAsync(async () => { const e = await this.journalReads.acquire({ signal: this.signal }); try { assertCurrent(); return await readAgentDeletionJournalStatusInWorker(i, { env: t }, this.signal); } finally { e?.(); } }, { attempts: 4, minDelayMs: 500, maxDelayMs: 8e3, jitter: .2, sleep: (e) => sleepWithAbort(e, this.signal), shouldRetry: (e) => e instanceof WorkerTaskError && e.code === "overloaded" }); assertCurrent(); if (e !== "absent") throw new Error(`Agent ${i} was deleted during startup inspection`); }; assertCurrent(); for (const e of c) { if (e.status === "rejected") throw e.reason; const t = e.value; if (t.incompatible.length || t.indeterminate.length || t.agentRefusals?.length || t.pendingMigrations?.length) throw new Error(t.agentRefusals?.map((e) => e.reason).join("; ") || t.indeterminate.map((e) => e.reason).join("; ") || `Agent ${i} database requires Doctor before preparation`); } const m = a.every(({ target: e }, t) => { const n = c[t]; return n?.status === "fulfilled" && matchesInspectionPath(n.value.readReadyAgentPaths ?? [], e.path); }); phase("readiness"); await racePromiseWithAbortSignal(p.preparationReady, this.signal); assertCurrent(); const h = { env: t, assertCurrent, signal: this.signal }; await withSqliteReadOnlyWorkerScope(async () => { await assertNotDeleted(); await preparePendingAgentDatabase(o, h, async () => { try { var a = _usingCtx(); const d = a.a(new AsyncDisposableStack()); const f = { agentId: i, paths: n, env: t, signal: this.signal, assertCurrent, phase }; const publish = async () => { phase("publication-wait"); const a = this.publication; this.publication = s.promise; try { await racePromiseWithAbortSignal(a, this.signal); assertCurrent(); this.publishingAgentId = i; for (let t = 1;; t++) try { e.withdraw = await p.publishAgent(f) || void 0; break; } catch (e) { const n = e instanceof AgentDatabaseStartupSupersededError || e instanceof AgentDatabaseSchemaAdmissionChangedError; if (!n || t >= STARTUP_PUBLICATION_ATTEMPTS) throw n ? new AgentDatabaseStartupPublicationError(e) : e; log.warn("agent database startup preparation was superseded; retrying", { agentId: i, attempt: t }); await sleepWithAbort(500 * 2 ** (t - 1), this.signal); await assertNotDeleted(); } phase("publication"); await assertNotDeleted(); if (p.captureReadAdmission) { r = publishPendingAgentDatabaseReadAdmission(o, { env: t, paths: m ? c.flatMap((e) => e.status === "fulfilled" ? e.value.readReadyAgentPaths ?? [] : []) : n, assertCurrent: p.captureReadAdmission({ ...f, assertCurrent: assertLifetimeCurrent }) }); releasePublication(); u.readReady = void 0; l.resolve(); } } catch (e) { if (!this.stopped) failPendingAgentDatabase(o, e, { env: t }); releasePublication(); throw e; } }; if (m && p.captureReadAdmission) { await preparePendingAgentDatabaseRead(o, { env: t, assertCurrent }, publish); log.info("agent database reads ready while writable inspection continues", { agentId: i, ...recoveryTiming(u) }); runInDetachedAsyncContext(() => sessionChanges.emit({ all: true, scope: { agentId: i, topology: true } })); } const retryLockedPreparation = async (e) => { let t = 0; await retryAsync(async () => { if (t++ > 0) await assertNotDeleted(); assertCurrent(); await e(); }, { attempts: 4, minDelayMs: 500, maxDelayMs: 8e3, jitter: .2, sleep: (e) => sleepWithAbort(e, this.signal), shouldRetry: isSqliteLockError, onRetry: ({ attempt: e }) => log.warn("agent database startup locked; retrying preparation", { agentId: i, phase: u.phase, attempt: e }) }); }; await retryLockedPreparation(async () => { phase("open-wait"); const e = await this.opening.acquire({ signal: this.signal }); try { assertCurrent(); phase("open"); const e = await p.openAgent(f); if (e) d.defer(() => racePromiseWithAbortSignal(Promise.resolve(e[Symbol.asyncDispose]()), this.signal)); } finally { e?.(); } }); await retryLockedPreparation(async () => { phase("migration-wait"); const t = await this.migrating.acquire({ signal: this.signal }); try { assertCurrent(); phase("migration"); const t = await p.migrateAgent(f); e.maintenance = t ? t.maintain : void 0; } finally { t?.(); } }); if (!r) await publish(); else await assertNotDeleted(); } catch (e) { a.e = e; } finally { await a.d(); } }); }, { signal: this.signal, deadlineOwnedByCaller: true }); log.info("agent database recovered after background inspection and preparation", { agentId: i, paths: n, ...recoveryTiming(u) }); } catch (r) { if (!this.stopped) { const a = formatErrorMessage(r); failPendingAgentDatabase(o, r, { env: t }); if (this.pending.get(i) === u) e.withdraw?.(); log.warn("agent database remains degraded", { agentId: i, paths: n, reason: a, repairHint: readAgentDatabaseAdmissionRefusal(i, { env: t })?.repairHint, ...recoveryTiming(u) }); } } finally { r?.(); releasePublication(); if (this.pending.get(i) === u) this.pending.delete(i); if (this.pending.size === 0) this.clearProgress(); l.resolve(); c.resolve(); } if (!readAgentDatabaseAdmissionRefusal(i, { env: t }) && !this.stopped) try { await e.maintenance?.(); } catch (e) { if (!this.stopped) log.warn("agent database background maintenance failed", { agentId: i, reason: formatErrorMessage(e) }); } }); this.track(p); } return r; } adopt() { this.signal.throwIfAborted(); if (this.adopted) throw new Error("Agent database startup admission already belongs to a Gateway"); this.adopted = true; return { stop: () => this.stop() }; } activate(e) { if (!this.adopted || this.stopped || this.activated) return; this.activated = true; this.activation.resolve(e); } async releaseStartup() { if (!this.adopted) await this.stop(); } stop() { return this.stopping ??= (async () => { this.stopped = true; this.clearProgress(); this.preparedSchemaHeaders = void 0; this.controller.abort(/* @__PURE__ */ new Error("Gateway stopped during agent database inspection")); this.activation.resolve(void 0); while (this.work.size > 0) await Promise.allSettled(this.work); })(); } }; function getAgentDatabaseStartupAdmission() { const e = startupAdmission.getStore(); return e?.isStopped ? void 0 : e; } async function withAgentDatabaseStartupAdmission(e, t = {}) { const n = getAgentDatabaseStartupAdmission() ?? new AgentDatabaseStartupAdmission(t.deferInspections); try { return await startupAdmission.run(n, () => withAgentDatabasePreparationContext(() => n, () => e(n))); } finally { await n.releaseStartup(); } } //#endregion export { getAgentDatabaseStartupAdmission as n, withAgentDatabaseStartupAdmission as r, AgentDatabaseStartupSupersededError as t };