UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

450 lines (449 loc) • 18.8 kB
import { r as installDatabaseProcessRole } from "../admission-scope-DmxaPNhm.mjs"; import { r as defaultRuntime } from "../runtime-B-SLYP-m.mjs"; import { o as getAsyncWorkSignal } from "../async-work-scope-BXagjUap.mjs"; import { i as resolveEnvironmentValue } from "../process-env-DVJdcOcM.mjs"; import { n as OPENCLAW_STATE_SCHEMA_VERSION, t as OPENCLAW_AGENT_SCHEMA_VERSION } from "../openclaw-schema-versions-E_10NoI6.mjs"; import { i as routeLogsToStderr } from "../console-BkI11Tqj.mjs"; import { u as throwSqliteLifecycleErrors } from "../sqlite-lifecycle-errors-D8BU4VLa.mjs"; import "../openclaw-state-db-contract-DfPjvL0M.mjs"; import { r as resolveOpenClawPackageRootSync } from "../openclaw-root-C-ayo09z.mjs"; import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Pn as number, Un as record, sr as unknown, xn as literal } from "../schemas-Cy6abvsu.mjs"; import { i as hasCommandProcessCleanupError } from "../exec-result-DJMhztYN.mjs"; import { n as closeDefaultRetainedNativeWorkerSource } from "../worker-native-lifecycle-BYup9wSI.mjs"; import { a as preparePostgresPoolForUpdate, t as closePostgresPool } from "../pool-ClFRe4Wg.mjs"; import { s as closeOpenClawStateDatabaseAsync } from "../openclaw-state-db-cache-CkwtTqzF.mjs"; import { r as cloneEnvWithPlatformSemantics } from "../config-env-vars-ByeGN-9N.mjs"; import { a as isStatePostgres } from "../openclaw-state-db-engine-sM0tpxNy.mjs"; import "../openclaw-agent-db-contract-aCH9b8Uc.mjs"; import { r as captureOpenClawStateWorkerContext } from "../openclaw-state-worker-context-DAKL_dnZ.mjs"; import "../openclaw-state-db-ARhwdPJg.mjs"; import { S as writeUpdatePostInstallDoctorResult, f as createUpdateDoctorDatabaseWriteCapture, i as UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV, y as recordUpdateDoctorConfigWriteRefusal } from "../update-doctor-result-DwaI51On.mjs"; import { o as withCliProcessScope, r as retainCliProcessJobUntilExit } from "../runtime-cleanup-scope-DuOL68nJ.mjs"; import { t as finalizeActiveDebugProxyCaptures } from "../runtime-cleanup-Duiz3buE.mjs"; import { t as resolveUpdateInstallRoot } from "../update-install-root-U1Z-3dbz.mjs"; import { a as POST_CORE_UPDATE_RESULT_PATH_ENV, n as POST_CORE_UPDATE_ENV } from "../update-post-core-context-Dy8UPbYC.mjs"; import { i as UPDATE_RUN_ID_ENV } from "../update-control-plane-sentinel-ThuSZh3z.mjs"; import { s as updateRunStepsFromResultStep } from "../update-run-step-BjlMycA-.mjs"; import { i as getUpdateRun } from "../update-run-reader-7kFqqMpW.mjs"; import { f as recordUpdateRunStep, n as adoptUpdateRun } from "../update-run-ledger-kQmrTutl.mjs"; import { n as createDelegatedUpdateRequesterAuthority, t as UpdateRequesterRevokedError } from "../update-requester-authority-ZobjNbhT.mjs"; import { n as withUpdateDatabaseEngine } from "../update-command-database-engine-G8lYYN4o.mjs"; import { n as withDelegatedUpdateCommandExecutor, o as captureUpdateCommandExecutorAuthority, t as withUpdateCommandExecutor } from "../update-command-executor-DJ6PbooS.mjs"; import { l as POST_CORE_EXECUTOR_CAPABILITY, u as POST_CORE_MUTATION_PROTOCOL } from "../package-update-activation-CgmPZVp3.mjs"; import { d as isOmittedUpdateTimeout, l as writePostCoreUpdateFailureFile, s as stopSupervisedPredecessorGateway, t as finishUpdate } from "../update-command-post-update-DUejrrmy.mjs"; import { o as recordUpdateRunStepAsync } from "../update-run-write.async-e9wBpfaM.mjs"; import { a as createWindowsTaskAutoStartRecovery, t as createWindowsTaskAutoStartGuard } from "../update-command-service-maintenance-KCRD9MXO.mjs"; import { t as createDoctorServiceInspectionBudget } from "../update-doctor-deadline-IRbqiQ4w.mjs"; import { c as formatUpdateFinalizationError, n as UpdateCommandFailure } from "../update-command-result-BghxBqBH.mjs"; import { l as withUpdateCommandTerminalResult } from "../update-command-terminal-B60oE91c.mjs"; import { t as resolveUpdateFinalizationTimeoutMs } from "../update-finalization-budget-DfB6e_je.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/cli/update-cli/update-command-migrated-input.ts const base = { executor: unknown(), runId: string(), root: string(), busyTimeoutMs: number().optional(), requester: object({ channel: string().optional(), accountId: string().optional(), senderId: string().optional(), authorizationSource: string().optional() }).optional(), originalRecoveryCapture: object({ directory: string(), manifestPath: string(), manifestSha256: string() }).optional() }; const postCoreInput = object({ ...base, opts: object({ json: boolean().optional(), restart: boolean().optional(), yes: boolean().optional(), acceptCapabilities: boolean().optional(), fullIntegrityCheck: boolean().optional(), timeout: string().optional() }) }); const doctorInput = object({ ...base, configInputHash: string(), repair: boolean(), fullIntegrityCheck: boolean().optional(), yes: boolean().optional(), workspaceSuggestions: boolean().optional(), postCoreSchemaRepair: literal(true).optional(), serviceInspectionDeadlineAtMs: number().int().optional(), databaseGenerations: record(string(), string().nullable()).optional(), databasePluginOwners: record(string(), object({ id: string(), rootDir: string(), source: string(), origin: _enum([ "bundled", "global", "workspace", "config" ]) })).optional() }); /** Decode command data once; transported identity never grants execution authority. */ function readUpdatePostCoreInput(e) { return postCoreInput.parse(e); } function readUpdateDoctorInput(e) { return doctorInput.parse(e); } //#endregion //#region src/infra/update-migrated-finalize.worker.ts async function finalizeMigratedUpdate() { installDatabaseProcessRole("cli-oneshot"); if (process.argv[2] === "--check") { const { finishUpdateRun: e } = await import("../cli/daemon-cli.js"); routeLogsToStderr(); if (typeof e !== "function") throw new Error("Update recovery writer is unavailable."); process.stdout.write(JSON.stringify({ executorDelegation: "pid-start-v1", postCoreExecutor: POST_CORE_EXECUTOR_CAPABILITY, mutationProtocol: POST_CORE_MUTATION_PROTOCOL, retainedOwnerBinding: true, doctorConfigWrites: "pid-start-v1", gatewayRestartCompletion: true, state: 36, agent: 38 })); return; } await withCliProcessScope(retainCliProcessJobUntilExit); if (process.argv[2] === "--doctor" || process.argv[2] === "--post-core") await preparePostgresPoolForUpdate(process.argv[2] === "--doctor" ? "openclaw doctor --fix" : "openclaw update repair"); const e = []; for await (const t of process.stdin) e.push(Buffer.isBuffer(t) ? t : Buffer.from(t)); const t = Buffer.concat(e).toString("utf8"); if (process.argv[2] === "--post-core") return await runDelegatedPostCore(readUpdatePostCoreInput(JSON.parse(t))); if (process.argv[2] === "--doctor") return await runDelegatedDoctor(readUpdateDoctorInput(JSON.parse(t))); const n = JSON.parse(t); if (n.params.opts.json) routeLogsToStderr(); if (n.recoveryHandoff) throw new Error("Full-state checkpoint recovery is deferred; retained state was left unchanged."); await withUpdateDatabaseEngine(process.env, async () => { const e = isOmittedUpdateTimeout(n.params.opts.timeout, n); if (e) n.params.opts.timeout = void 0; const t = n.params.opts.run?.activationTimeoutMs ?? (e ? void 0 : await resolveUpdateFinalizationTimeoutMs(n.params.updateStepTimeoutMs, { env: n.params.ownedManagedUpdateEnv ?? n.params.opts.run?.env, databases: n.params.schemaVersions, pluginCount: Object.keys(n.params.preUpdatePluginInstallRecords).length })); let r; const i = await withUpdateCommandTerminalResult(async (e) => { if (n.executor) return await withDelegatedUpdateCommandExecutor(n.executor, n.params.opts.run?.runId ?? "", n.params.result.root ?? n.params.root, async (t) => finalizeInput(n, t, e), t === void 0 ? void 0 : { activationTimeoutMs: t }); const r = n.params.ownedManagedUpdateEnv ?? n.params.opts.run?.env; if (!r) throw new Error("Grantless finalization requires its captured update environment."); const i = n.params.controlPlaneUpdateSentinelMeta; const a = n.params.opts.run?.runId ?? ""; const o = path.dirname(n.resultPath); const s = n.params.result.before?.version === "2026.9.3" && r.OPENCLAW_UPDATE_RUN_HANDOFF === "1" && r.OPENCLAW_UPDATE_RUN_ID === a && i?.runId === a && i.handoffId && i.root && i.root === resolveUpdateInstallRoot(n.params.result.root ?? n.params.root) && path.basename(o).startsWith("openclaw-update-migrated-") && path.basename(n.resultPath) === "result.json" && [ "TMPDIR", "TMP", "TEMP" ].every((e) => resolveEnvironmentValue(process.env, e) === o) ? { runId: a, handoffId: i.handoffId, root: i.root } : void 0; for (const e of [ "TMPDIR", "TMP", "TEMP" ]) { const t = resolveEnvironmentValue(r, e); if (t === void 0) delete process.env[e]; else process.env[e] = t; } return await withUpdateCommandExecutor(a, async (r) => { const i = await r.enter(n.params.result.root ?? n.params.root, { activationTimeoutMs: t }); return await finalizeInput(n, i, e); }, s ? { legacyManagedParent: s } : void 0); }, { ...n.params.opts, onTerminalRecord: (e) => { r = e; } }); const a = r ?? getUpdateRun(i.run.runId, { env: i.run.env }); const o = i.run.completionOwner === "gateway-restart" && i.run.gatewayRestartRequired === true && i.result.status === "ok" && a?.status === "running" && a.phase === "restarting"; if (!a || a.runId !== i.run.runId || a.status === "running" && !o) throw new Error("Update finalization left the update run nonterminal."); const s = { result: i.result, exitCode: i.exitCode, candidateStartAttempted: i.candidateStartAttempted || o, ...o ? { restartRunId: a.runId } : { terminalRunId: a.runId }, executorDelegation: "pid-start-v1" }; await fs.writeFile(n.resultPath, JSON.stringify(s), { mode: 384 }); }); } async function runDelegatedPostCore(e) { const t = process.env[POST_CORE_UPDATE_RESULT_PATH_ENV]?.trim(); const n = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url }); if (!t || !e.executor || process.env["OPENCLAW_UPDATE_POST_CORE"] !== "1" || process.env["OPENCLAW_UPDATE_RUN_ID"] !== e.runId || !n || resolveUpdateInstallRoot(n) !== resolveUpdateInstallRoot(e.root)) throw new Error("Post-core update does not match its delegated run and installed runtime."); if (e.opts.json) routeLogsToStderr(); process.env[POST_CORE_UPDATE_RESULT_PATH_ENV] = `${t}.pending`; try { await withDelegatedUpdateCommandExecutor(e.executor, e.runId, e.root, async (t) => { const n = e.requester ? await createDelegatedUpdateRequesterAuthority(e.requester, e.runId, t) : void 0; const { updateCommand: r } = await import("../update-command-B2TVTPGY.mjs"); t.assertCurrent(); if (n?.isCurrent() === false) throw new UpdateRequesterRevokedError(); await r({ ...e.opts, run: { runId: e.runId, originalRecoveryCapture: e.originalRecoveryCapture, busyTimeoutMs: e.busyTimeoutMs, env: { ...process.env }, executorFence: t, ...n ? { requesterAuthority: n } : {} } }); }); await fs.rename(`${t}.pending`, t); } catch (e) { if (!hasCommandProcessCleanupError(e)) await writePostCoreUpdateFailureFile(t, e); throw e; } } async function runDelegatedDoctor(e) { const t = createDoctorServiceInspectionBudget(e.serviceInspectionDeadlineAtMs); const n = process.env[UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV]?.trim(); if (!n || !e.executor) throw new Error("Update Doctor requires its delegated executor and result path."); await withDelegatedUpdateCommandExecutor(e.executor, e.runId, e.root, async (r, i) => { const a = e.requester ? await createDelegatedUpdateRequesterAuthority(e.requester, e.runId, r) : void 0; const assertCurrent = () => { try { r.assertCurrent(); if (a?.isCurrent() === false) throw new UpdateRequesterRevokedError(); } catch (e) { recordUpdateDoctorConfigWriteRefusal({ reason: e instanceof UpdateRequesterRevokedError ? e.code : "authority-check-failed", message: formatUpdateFinalizationError(e), keys: [] }); throw e; } }; try { assertCurrent(); } catch (e) { if (!(e instanceof UpdateRequesterRevokedError)) throw e; r.assertCurrent(); await writeUpdatePostInstallDoctorResult({ resultPath: n, result: { status: "error", configWriteRefusal: { reason: e.code, message: e.message, keys: [] } } }); process.exitCode = 1; return; } const { runDoctorHealthFlow: o } = await import("../doctor-health-Bt8pq4BW.mjs"); assertCurrent(); t(); const s = isStatePostgres() ? void 0 : createUpdateDoctorDatabaseWriteCapture(e.databaseGenerations, { env: process.env, root: e.root, signal: getAsyncWorkSignal() ?? new AbortController().signal, pluginOwners: e.databasePluginOwners, assertCurrent, warn: (e) => process.stderr.write(e + "\n") }); await s?.admit(); await stopSupervisedPredecessorGateway(e, { databaseWriteCapture: s, root: e.root, assertCurrent, serviceInspectionBudget: t, warn: (e) => process.stderr.write(`${e}\n`) }); assertCurrent(); const c = t(); await o({ ...defaultRuntime, exit: (e) => { process.exitCode = e; } }, { repair: e.repair, fullIntegrityCheck: e.fullIntegrityCheck, nonInteractive: true, ...e.yes !== void 0 ? { yes: e.yes } : {}, ...e.workspaceSuggestions !== void 0 ? { workspaceSuggestions: e.workspaceSuggestions } : {} }, { inputHash: e.configInputHash, assertCurrent, commandAuthority: i, databaseWriteCapture: s, originalRecoveryCapture: { runId: e.runId, installRoot: captureUpdateCommandExecutorAuthority(r, e.runId).installKey, ref: e.originalRecoveryCapture }, ...e.databaseGenerations ? { databaseGenerations: e.databaseGenerations } : {}, ...e.databasePluginOwners ? { databasePluginOwners: e.databasePluginOwners } : {}, serviceInspectionDeadlineAtMs: c === void 0 ? void 0 : Date.now() + c, ...e.postCoreSchemaRepair === true ? { postCoreSchemaRepair: { runId: e.runId, assertCurrent } } : {} }); }); } /** * Time the handoff from receipts the previous driver already wrote, so an * installed driver that predates this step still yields its start: its last * completed row starts the handoff, and this fresh driver ends it before * resuming verification. Timing never changes the update outcome. */ function recordDriverHandoff(e, t, n, r) { try { const i = [...n.steps, ...r]; let a; for (const e of i) if (e.endedAtMs !== void 0 && !e.step.startsWith("driver:") && e.endedAtMs > (a?.endedAtMs ?? 0)) a = e; if (a?.endedAtMs === void 0) return; const o = Date.now(); const s = Math.min(a.endedAtMs, o); const c = i.find((e) => e.step === "driver:adopted")?.endedAtMs; const l = { name: "update-driver-handoff", command: "openclaw update", cwd: t.root ?? "", durationMs: o - s, exitCode: 0, diagnostics: [`Handoff began after "${a.step}"` + (c === void 0 ? "." : `; the fresh driver adopted the run after ${Math.max(0, c - s)}ms.`)] }; t.steps.push(l); for (const t of updateRunStepsFromResultStep(l)) recordUpdateRunStep(e.runId, { ...t, startedAtMs: s, endedAtMs: o }, e); } catch {} } async function finalizeInput(e, t, n) { const r = e.params.opts.run; if (!r || "executorFence" in r || e.params.rollbackBlockedReason !== "state-migrated-no-rollback" && e.params.rollbackBlockedReason !== "rollback-state-unverified") throw new Error("Update finalization requires its migrated update run."); const { requesterAuthority: i, ...a } = r; a.busyTimeoutMs ??= e.params.updateStepTimeoutMs; t.assertCurrent(); const o = adoptUpdateRun(a.runId, a); const s = { ...a, executorFence: t, ...i ? { requesterAuthority: await createDelegatedUpdateRequesterAuthority(i.requester, a.runId, t, a.env) } : {} }; t.assertCurrent(); n(s); if (e.bufferedSteps.length > 0) { const n = cloneEnvWithPlatformSemantics(s.env ?? process.env); const r = captureOpenClawStateWorkerContext({ env: n }); const i = s.requesterAuthority; const assertCurrent = () => { t.assertCurrent(); if (i?.isCurrent() === false) throw new UpdateRequesterRevokedError(); }; for (const t of e.bufferedSteps) await recordUpdateRunStepAsync(s.runId, t, { ...s, env: n, context: r, assertCurrent }); } recordDriverHandoff(s, e.params.result, o, e.bufferedSteps); const c = e.params.preManagedServiceStop; if (e.windowsTaskAutoStartSuspended && !c?.serviceEnv) throw new Error("Transferred Windows task suspension is missing its stopped service owner."); const l = e.windowsTaskAutoStartSuspended && c?.serviceEnv ? createWindowsTaskAutoStartRecovery({ serviceEnv: c.serviceEnv, updateRun: s, alreadySuspended: true, assertCurrentService: createWindowsTaskAutoStartGuard({ root: e.params.result.root ?? e.params.root, before: c, timeoutMs: e.params.updateStepTimeoutMs }), assertCurrent: () => { s.executorFence?.assertCurrent(); if (getUpdateRun(s.runId, { env: s.env })?.status !== "running") throw new Error("Update run no longer owns Windows task activation."); } }) : void 0; let u; let d = 0; let f = false; try { u = await finishUpdate({ ...e.params, result: { ...e.params.result, runId: s.runId }, opts: { ...e.params.opts, run: s }, ...c ? { preManagedServiceStop: { ...c, windowsTaskAutoStartRecovery: l } } : {} }, { candidateRuntime: true, adoptedFinalization: true, onGatewayStartAttempted: () => { f = true; } }); } catch (e) { if (!(e instanceof UpdateCommandFailure)) throw e; u = e.result; d = e.exitCode; } finally { await l?.complete(u?.status === "ok" || u?.recovery?.serviceRestartSafe === true && u.recovery.service === "healthy"); } t.assertCurrent(); return { run: s, result: u, exitCode: d, candidateStartAttempted: f }; } (async () => { const e = []; let t = true; for (const n of [ finalizeMigratedUpdate, finalizeActiveDebugProxyCaptures, closeOpenClawStateDatabaseAsync, closeDefaultRetainedNativeWorkerSource ]) try { await n(); } catch (r) { e.push(r); if (n === closeOpenClawStateDatabaseAsync || n === closeDefaultRetainedNativeWorkerSource) t = false; } if (t) try { await closePostgresPool(); } catch (t) { e.push(t); } throwSqliteLifecycleErrors(e, "Update finalization and resource cleanup failed."); })().catch((e) => { process.stderr.write(`${formatUpdateFinalizationError(e)}\n`); process.exitCode = 1; }); //#endregion export {};