openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
290 lines (289 loc) • 11.8 kB
JavaScript
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as buildUpdateRehearsalPathEnv } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { n as isWithinRehearsal, r as refuseRehearsal, t as createRehearsalPathInspector } from "./doctor-update-rehearsal-paths-D02-iFrJ.mjs";
import { lstatSync, readFileSync, readdirSync, realpathSync } from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
//#region src/commands/doctor-update-rehearsal-inventory.ts
function valueAt(e, t) {
let n = e;
for (const e of t.split(".")) {
if (!isRecord(n)) return;
n = n[e];
}
return n;
}
function assertConfigLayout(e, t) {
const n = path.join(t, "workspace");
const r = {
"agents.defaults.workspace": n,
"agents.defaults.cwd": n,
"logging.file": path.join(t, "canary.log"),
"gateway.mode": "local",
"gateway.bind": "loopback",
"gateway.auth.mode": "token",
"gateway.tls.enabled": false,
"gateway.tailscale.mode": "off",
"gateway.controlUi.enabled": false,
"cron.enabled": false,
"cron.triggers.enabled": false,
"hooks.enabled": false,
"hooks.internal.enabled": false,
"transcripts.enabled": false,
"discovery.mdns.mode": "off"
};
if (Object.entries(r).some(([t, n]) => valueAt(e, t) !== n)) refuseRehearsal("configuration does not preserve the shipped isolated layout");
for (const t of [
"env",
"diagnostics",
"session.store",
"agents.list"
]) if (valueAt(e, t) !== void 0) refuseRehearsal(`configuration retains ${t}`);
const i = valueAt(e, "gateway.port");
const a = valueAt(e, "gateway.auth.token");
const o = valueAt(e, "transcripts.autoStart");
const s = valueAt(e, "agents.entries");
if (typeof i !== "number" || !Number.isInteger(i) || i < 1 || i > 65535 || typeof a !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(a) || !Array.isArray(o) || o.length !== 0 || !isRecord(s)) refuseRehearsal("configuration is missing its isolated Gateway or agent projection");
for (const [e, r] of Object.entries(s)) {
const i = path.join(n, e);
const a = valueAt(r, "agentDir");
if (!isWithinRehearsal(n, i) || valueAt(r, "workspace") !== i || valueAt(r, "cwd") !== i || typeof a !== "string" || !path.isAbsolute(a) || !isWithinRehearsal(t, a)) refuseRehearsal("an agent points outside its copied layout");
}
const c = [e];
while (c.length > 0) {
const e = c.pop();
if (Array.isArray(e)) c.push(...e);
else if (isRecord(e)) {
if (Object.hasOwn(e, "$include")) refuseRehearsal("configuration retains an include graph");
c.push(...Object.values(e));
}
}
}
/** Inspect an already prepared physical disposable copy, never live recovery coverage.
* The caller owns the original updater/parent and rechecks this admission directly
* before launching Doctor. Inventory does not run plugin detection or migration.
*/
async function inspectPreparedDoctorRehearsal(e) {
const t = e.stateDir;
const n = e.env;
const r = e.assertCurrent;
r();
if (n.OPENCLAW_STATE_DIR !== t || !/^openclaw-update-canary-[a-z0-9]{6}$/iu.test(path.basename(t))) refuseRehearsal("the selected root is not a prepared disposable copy");
const [i, a, o, s] = await Promise.all([
import("./supervisor-markers-DMfWlopE.mjs"),
import("./update-post-core-context-CF1ihiLo.mjs"),
import("./update-control-plane-sentinel-DxpKMxBz.mjs"),
import("./update-doctor-result-BiaHv1QW.mjs")
]);
r();
const c = {
OPENCLAW_UPDATE_IN_PROGRESS: "0",
OPENCLAW_UPDATE_DEFER_CONFIGURED_PLUGIN_INSTALL_REPAIR: "1",
OPENCLAW_UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE: "1",
OPENCLAW_UPDATE_PARENT_SUPPORTS_GATEWAY_RESTART: "1",
OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR: "0",
OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION: "0",
OPENCLAW_SERVICE_REPAIR_POLICY: "external",
...buildUpdateRehearsalPathEnv(t),
OPENCLAW_OAUTH_DIR: n.OPENCLAW_OAUTH_DIR
};
const l = [
...i.SUPERVISOR_HINT_ENV_VARS,
o.CONTROL_PLANE_UPDATE_SENTINEL_META_ENV,
o.UPDATE_RUN_ID_ENV,
s.UPDATE_POST_INSTALL_DOCTOR_RESULT_PATH_ENV,
"OPENCLAW_UPDATE_RUN_HANDOFF",
a.POST_CORE_UPDATE_ENV,
a.POST_CORE_UPDATE_CHANNEL_ENV,
a.POST_CORE_UPDATE_RESULT_PATH_ENV,
a.POST_CORE_UPDATE_INSTALL_RECORDS_PATH_ENV,
a.POST_CORE_UPDATE_STARTED_AT_ENV,
a.POST_CORE_UPDATE_REQUESTED_CHANNEL_ENV,
a.POST_CORE_UPDATE_SOURCE_CONFIG_PATH_ENV,
"OPENCLAW_BUNDLED_PLUGINS_DIR",
"OPENCLAW_DISABLE_BUNDLED_PLUGINS",
"OPENCLAW_GATEWAY_SERVICE_PID",
"OPENCLAW_GATEWAY_PORT",
"OPENCLAW_COMPATIBILITY_HOST_VERSION",
"OPENCLAW_GATEWAY_TOKEN",
"OPENCLAW_GATEWAY_PASSWORD",
"OPENCLAW_PROFILE",
"OPENCLAW_DIAGNOSTICS_TIMELINE_PATH",
"OPENCLAW_TEST_MINIMAL_GATEWAY"
];
for (const e of l) c[e] = void 0;
for (const e of ["OPENCLAW_AGENT_DIR", "PI_CODING_AGENT_DIR"]) {
if (n[e] && (!path.isAbsolute(n[e]) || !isWithinRehearsal(t, n[e]))) refuseRehearsal("an agent environment selector escapes the copy");
c[e] = n[e];
}
const assertEnv = () => {
if (Object.entries(c).some(([e, t]) => n[e] !== t)) refuseRehearsal("the isolated environment changed or retained live selectors");
};
assertEnv();
const { identities: u, inspectPath: d } = createRehearsalPathInspector(t, e.pluginCodeLinks ?? []);
const f = d(t);
if (!f?.isDirectory() || path.resolve(t) !== t || realpathSync(t) !== t) refuseRehearsal("the rehearsal root is not a private directory at its resolved path");
for (const t of e.pluginCodeLinks ?? []) if (!d(t.path, false, true)) refuseRehearsal(`copied plugin code link disappeared: ${t.path}`);
const p = path.join(t, "openclaw.json");
if (!d(p, true)?.isFile()) refuseRehearsal("the copied configuration is missing");
const m = await fs$1.readFile(p, "utf8");
d(p, true);
const h = JSON.parse(m);
assertConfigLayout(h, t);
const g = valueAt(h, "canvasHost");
const _ = valueAt(h, "plugins.entries.canvas.config.host");
const v = {
...isRecord(g) ? g : {},
...isRecord(_) ? _ : {}
}.root;
const y = ["voice-call", "@openclaw/voice-call"].map((e) => valueAt(h, `plugins.entries.${e}.config.store`)).find((e) => typeof e === "string" && e.trim());
const b = valueAt(h, "plugins.entries.memory-lancedb.config.dbPath");
const x = valueAt(h, "plugins.entries.memory-wiki.config.vault.path");
const S = valueAt(h, "channels.reef.stateDir");
for (const e of [
v,
y,
b,
x,
S
]) {
if (typeof e === "string" && e.includes("${")) refuseRehearsal("migration locator retains an unresolved environment template");
if (typeof e === "string" && e.trim().split(/[\\/]/u).includes("..")) refuseRehearsal("migration locator retains parent traversal");
}
if (typeof b === "string" && b.trim() && (b.includes("://") || !path.isAbsolute(b.trim()) && !/^~(?:$|[\\/])/u.test(b.trim()))) refuseRehearsal("LanceDB migration requires an absolute copied path");
const C = [
["canvas", v],
["voice-call", y],
["memory-lancedb", b],
["reef", S]
].flatMap(([e, t]) => typeof t === "string" && t.trim() ? [{
pluginId: e,
path: path.resolve(resolveUserPath(t, n))
}] : []);
if (typeof x === "string") {
const e = x === "~" ? t : x.startsWith("~/") ? path.join(t, x.slice(2)) : x;
C.push({
pluginId: "memory-wiki",
path: path.resolve(e)
});
}
const [{ createConfigIO: w }, T, E, D, O, k, A, j, M] = await Promise.all([
import("./io.factory-D2IOIn7d.mjs"),
import("./openclaw-agent-db-registry-listing-eoyo5V8Q.mjs"),
import("./targets-cXkr4Sqy.mjs"),
import("./openclaw-state-db-readonly-_6T_jl_p.mjs"),
import("./kysely-sync-BnoHwGNh.mjs"),
import("./openclaw-state-db-schema-helpers-DW9Ae6yZ.mjs"),
import("./openclaw-state-db.paths-DiM3pkKt.mjs"),
import("./sqlite-files-DhYaTb_s.mjs"),
import("./paths-C9ebzH5f.mjs")
]);
const { preparePluginDoctorMigrationBackupResources: N } = await import("./doctor-contract-registry-C9_iSocR.mjs");
const { isSqliteSnapshotFile: P } = await import("./sqlite-file-header-BuU9nuxO.mjs");
const F = A.resolveOpenClawStateSqlitePath(n);
if (!d(F)?.isFile()) refuseRehearsal("the copied shared database is missing");
for (const e of j.resolveSqliteDatabaseFilePaths(F)) d(e);
await D.withExistingOpenClawStateDatabaseArtifactPreservingReadOnlyAsync(({ db: e }) => {
const t = O.getNodeSqliteKysely(e);
for (const n of ["state_leases", "agent_database_leases"]) if (k.tableExists(e, n) && O.executeSqliteQueryTakeFirstSync(e, t.selectFrom(n).selectAll().limit(1))) refuseRehearsal("the copied shared database retains process leases");
}, { env: n });
const I = await w({
env: { ...n },
observe: false,
pluginValidation: "skip"
}).readConfigFileSnapshot();
if (I.path !== p || I.raw !== m) refuseRehearsal("the copied configuration changed during inspection");
const L = I.sourceConfigBeforeMigrations ?? I.sourceConfig;
const R = await T.inspectOpenClawRegisteredAgentDatabases({
env: n,
includeIncompatibleSchemaVersions: true
});
const z = [...R, ...E.resolveConfiguredAgentDatabaseTargets(L, {
env: n,
registeredDatabases: R
})];
for (const e of C) if (isWithinRehearsal(t, e.path)) d(e.path);
const B = [];
const V = await N({
config: L,
env: n,
stateDir: t,
warnings: B,
requireLocalResources: true
});
const H = V.resources;
const U = C.filter(({ pluginId: e }) => !V.deferredPluginIds.has(e)).map((e) => e.path);
for (const e of U) d(e);
const W = [
...U,
p,
M.resolveOAuthDir(n, t),
...j.resolveSqliteDatabaseFilePaths(F),
path.join(t, "workspace"),
path.join(t, "canary.log"),
...Object.values(L.agents?.entries ?? {}).flatMap((e) => [
e.workspace,
e.cwd,
e.agentDir
].filter((e) => typeof e === "string")),
...[n.OPENCLAW_AGENT_DIR, n.PI_CODING_AGENT_DIR].filter((e) => typeof e === "string"),
...z.flatMap((e) => j.resolveSqliteDatabaseFilePaths(e.path)),
...H.flatMap((e) => e.kind === "sqlite" ? j.resolveSqliteDatabaseFilePaths(e.path) : [e.path])
];
const G = [{
filename: t,
code: true
}, ...W.map((e) => ({
filename: e,
code: false
}))];
const K = /* @__PURE__ */ new Map();
while (G.length > 0) {
const { filename: e, code: t } = G.pop();
if (K.has(e) && (!K.get(e) || t)) continue;
K.set(e, t);
if (K.size > 1e5) refuseRehearsal("the migration data inventory exceeds bounded inspection");
const n = d(e, false, t);
if (n?.isDirectory()) G.push(...(await fs$1.readdir(e)).map((n) => ({
filename: path.join(e, n),
code: t
})));
else if (n?.isFile() && await P(e)) G.push(...j.resolveSqliteDatabaseFilePaths(e).map((e) => ({
filename: e,
code: false
})));
}
const assertCurrent = () => {
assertEnv();
r();
const e = lstatSync(t);
if (e.dev !== f.dev || e.ino !== f.ino || !e.isDirectory() || e.isSymbolicLink() || process.platform !== "win32" && (e.mode & 63) !== 0 || e.uid !== f.uid || realpathSync(t) !== t) refuseRehearsal("the admitted rehearsal root changed");
};
const assertPrepared = () => {
assertCurrent();
for (const e of u.keys()) if (!d(e, e === p, true)) refuseRehearsal(`copied data disappeared before admission: ${e}`);
for (const [e, t] of K) d(e, e === p, t);
const e = [t];
let n = 0;
while (e.length) {
const t = e.pop();
if (++n > 1e5) refuseRehearsal("the migration data inventory exceeds bounded inspection");
if (d(t, false, true)?.isDirectory()) e.push(...readdirSync(t).map((e) => path.join(t, e)));
}
if (readFileSync(p, "utf8") !== m) refuseRehearsal("the copied configuration changed before admission");
};
assertPrepared();
return {
fact: {
kind: "doctor-schema-rehearsal",
stateDir: t,
warnings: B,
...V.notices.length > 0 ? { notices: V.notices } : {}
},
assertPrepared,
assertCurrent
};
}
//#endregion
export { inspectPreparedDoctorRehearsal };