UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

282 lines (281 loc) • 13.5 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs"; import { s as pathMayExistSync } from "./path-existence-Co7-GyVr.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs"; import "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as deferSqlitePostCommitPublication } from "./sqlite-post-commit-BrUVQObC.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { o as runSqliteReadSnapshotSync } from "./sqlite-transaction-BHHu6P5-.mjs"; import { a as normalizeWorkspaceIdentityPath, i as createWorkspaceStateIdentity, o as resolveCanonicalWorkspacePath, s as resolveWorkspaceStateAliases } from "./workspace-state-identity-Ce50CSIn.mjs"; import { _ as withSynchronousArtifactPreservingStateSnapshot, m as withExistingOpenClawStateDatabaseReadOnly } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { l as runOpenClawStateWriteTransaction, r as openOpenClawStateDatabase } from "./openclaw-state-db-ARhwdPJg.mjs"; import { s as readConfigFileSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { n as retireWorkspaceFileCache } from "./workspace-file-cache-Dp8gx91S.mjs"; import "./workspace-state-store-DNT7G1J_.mjs"; import { d as registerWorkspaceStateAliasIdentitiesInTransaction, l as readWorkspaceStateSnapshotFromDatabase } from "./workspace-state-store.kernel-BGcNEuj3.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { n as listWorkspaceStateDirs } from "./workspace-state-dirs-Bd0O_fIH.mjs"; import { r as prepareWorkspaceMigrationReceiptMove, t as applyWorkspaceMigrationReceiptMove } from "./state-migrations.workspace-setup-receipts-qMO81tYo.mjs"; import fs from "node:fs"; import path from "node:path"; import os from "node:os"; import { isDeepStrictEqual } from "node:util"; //#region src/agents/workspace-alias-rebind.ts function directoryIdentity(e) { try { const t = fs.statSync(e, { bigint: true }); return t.isDirectory() ? `${t.dev}:${t.ino}:${t.birthtimeNs}` : void 0; } catch (e) { return ignoreMissingPath(e); } } function existingWorkspacePathSpellings(e) { const t = path.parse(e).root; let n = [t]; for (const r of e.slice(t.length).split(path.sep)) n = n.flatMap((e) => { try { return fs.readdirSync(e).filter((e) => normalizeWorkspaceIdentityPath(e) === r).toSorted().map((t) => path.join(e, t)); } catch (e) { return ignoreMissingPath(e) ?? []; } }); return n; } function readWorkspaceMoveState(e, t) { const n = readWorkspaceStateSnapshotFromDatabase({ database: e, identity: t }); const r = getNodeSqliteKysely(e.db); return { setup: executeSqliteQueryTakeFirstSync(e.db, r.selectFrom("workspace_setup_state").selectAll().where("workspace_key", "=", t.workspaceKey)), hashes: [...n.attestation?.generatedHashes ?? []], aliases: executeSqliteQuerySync(e.db, r.selectFrom("workspace_path_aliases").selectAll().where("workspace_key", "=", t.workspaceKey).orderBy("alias_key", "asc")).rows }; } /** Read the old owner without adopting the alias's new target. */ function detectRepointedWorkspaceAlias(e, t = {}) { const n = resolveWorkspaceStateAliases(e); const r = n[0]; const i = n.at(-1); const a = resolveCanonicalWorkspacePath(e); const o = directoryIdentity(a); if (!pathMayExistSync(resolveUserPath(e))) return; return withExistingOpenClawStateDatabaseReadOnly((e) => runSqliteReadSnapshotSync(e.db, () => { const t = getNodeSqliteKysely(e.db); const n = executeSqliteQueryTakeFirstSync(e.db, t.selectFrom("workspace_path_aliases").selectAll().where("alias_key", "=", r.workspaceKey)); if (!n) return; const s = createWorkspaceStateIdentity(n.workspace_path); if (n.alias_path !== r.workspacePath || n.workspace_key !== s.workspaceKey) throw new Error("workspace path alias identity is invalid"); if (s.workspaceKey === i.workspaceKey) return; return { aliasPath: r.workspacePath, storedWorkspacePath: s.workspacePath, currentWorkspacePath: i.workspacePath, currentDirectoryPath: a, currentTargetHasOwnState: executeSqliteQueryTakeFirstSync(e.db, t.selectFrom("workspace_setup_state").select("workspace_key").where("workspace_key", "=", i.workspaceKey)) !== void 0, targetDirectoryIdentity: o, state: readWorkspaceMoveState(e, s) }; }, { operationLabel: "workspace.alias.inspect" }), t); } function inspectWorkspaceAliasMove(e, t, n = [e]) { if (t.currentTargetHasOwnState) return { kind: "blocked", outcome: "current-target-owns-state" }; const r = createWorkspaceStateIdentity(t.storedWorkspacePath); const i = createWorkspaceStateIdentity(t.currentWorkspacePath); if (!t.targetDirectoryIdentity) return { kind: "blocked", outcome: "target-directory-missing" }; if (directoryIdentity(t.currentDirectoryPath) !== t.targetDirectoryIdentity) return { kind: "blocked", outcome: "repoint-changed" }; const matchesDestination = (e) => resolveWorkspaceStateAliases(e).at(-1).workspaceKey === i.workspaceKey && directoryIdentity(resolveCanonicalWorkspacePath(e)) === t.targetDirectoryIdentity; if (existingWorkspacePathSpellings(r.workspacePath).some((e) => !matchesDestination(e))) return { kind: "blocked", outcome: "original-workspace-exists" }; const a = /* @__PURE__ */ new Map(); const o = new Set(t.state.aliases.map((e) => e.alias_key)); const s = new Set(n); for (const n of [ ...t.state.aliases.flatMap((e) => [e.alias_path, ...existingWorkspacePathSpellings(e.alias_path)]), ...s, e ]) { const e = resolveWorkspaceStateAliases(n); const t = e[0]; const i = e.at(-1); if (s.has(n) && i.workspaceKey === r.workspaceKey) return { kind: "blocked", outcome: "configured-workspace-conflict" }; if (matchesDestination(n)) for (const t of e) a.set(t.workspaceKey, t); else if (o.has(t.workspaceKey) && (pathMayExistSync(resolveUserPath(n)) || s.has(n))) return { kind: "blocked", outcome: "configured-workspace-conflict" }; } if (resolveWorkspaceStateAliases(e).at(-1).workspaceKey !== i.workspaceKey) return { kind: "blocked", outcome: "repoint-changed" }; return { kind: "ready", aliases: [...a.values()] }; } /** Transfer only a confirmed move; source history is never rebuilt from templates. */ async function rebindRepointedWorkspaceAlias(e, t, n = {}, r = [e], i) { const a = detectRepointedWorkspaceAlias(e, n); if (!a) return "no-repoint"; if (JSON.stringify(a) !== JSON.stringify(t)) return "repoint-changed"; const o = inspectWorkspaceAliasMove(e, t, r); if (o.kind === "blocked") return o.outcome; const s = createWorkspaceStateIdentity(t.storedWorkspacePath); const c = createWorkspaceStateIdentity(t.currentWorkspacePath); const l = openOpenClawStateDatabase(n); const u = await prepareWorkspaceMigrationReceiptMove({ database: l.db, storedIdentity: s, currentIdentity: c, currentDirectoryPath: t.currentDirectoryPath, storedSetup: t.state.setup }); await i?.(); const d = inspectWorkspaceAliasMove(e, t, r); if (d.kind === "blocked") return d.outcome; return runOpenClawStateWriteTransaction((e) => { const n = readWorkspaceMoveState(e, s); if (JSON.stringify(n) !== JSON.stringify(t.state)) return "repoint-changed"; const r = getNodeSqliteKysely(e.db); if (executeSqliteQueryTakeFirstSync(e.db, r.selectFrom("workspace_setup_state").select("workspace_key").where("workspace_key", "=", c.workspaceKey))) return "current-target-owns-state"; applyWorkspaceMigrationReceiptMove(e.db, u); if (n.setup) { executeSqliteQuerySync(e.db, r.insertInto("workspace_setup_state").values({ ...n.setup, workspace_key: c.workspaceKey, workspace_path: c.workspacePath })); executeSqliteQuerySync(e.db, r.updateTable("workspace_generated_bootstrap_hashes").set({ workspace_key: c.workspaceKey }).where("workspace_key", "=", s.workspaceKey)); executeSqliteQuerySync(e.db, r.deleteFrom("workspace_setup_state").where("workspace_key", "=", s.workspaceKey)); } executeSqliteQuerySync(e.db, r.deleteFrom("workspace_path_aliases").where("workspace_key", "=", s.workspaceKey)); registerWorkspaceStateAliasIdentitiesInTransaction({ database: e, aliases: d.aliases, identity: c, updatedAtMs: Date.now() }); deferSqlitePostCommitPublication(e.db, () => { retireWorkspaceFileCache(s.workspacePath); retireWorkspaceFileCache(c.workspacePath); }); return "rebound"; }, n); } //#endregion //#region src/commands/doctor-workspace-alias.ts async function configuredWorkspaceDirs(e) { return listWorkspaceStateDirs({ cfg: e, env: process.env, homedir: os.homedir, stateDir: resolveStateDir() }); } function describeRepointedWorkspaceAlias(e) { return `Workspace path ${shortenHomePath(e.aliasPath)} now resolves to ${shortenHomePath(e.currentWorkspacePath)}, but its saved setup records belong to ${shortenHomePath(e.storedWorkspacePath)}.`; } const WORKSPACE_ALIAS_CHECK_ID = "core/doctor/workspace-alias"; const REPAIR_HINT = "If the same workspace moved, run `openclaw doctor --fix` and confirm the move, or use `openclaw doctor --fix --force`. Otherwise restore the original link or configure the intended workspace directly."; const REBIND_MESSAGES = { "no-repoint": "The alias no longer needs repair.", "repoint-changed": "The workspace changed after inspection. Nothing was transferred; rerun doctor to inspect it again.", "current-target-owns-state": "The destination already owns workspace records. Nothing was merged or deleted. Restore the original link, or configure that destination directly if you intended to switch workspaces.", "original-workspace-exists": "The original workspace still exists. This repair only moves records after the original folder has moved; restore the link if the move was not intended.", "target-directory-missing": "The destination is not an existing directory. Restore the moved folder before repairing the link.", "configured-workspace-conflict": "Another workspace path still refers to the original location. Update the links for the moved workspace, then rerun doctor; no records were transferred." }; /** Read-only findings include failed inspection so health cannot report a false success. */ async function collectRepointedWorkspaceAliasFindings(e) { const t = await configuredWorkspaceDirs(e); return withSynchronousArtifactPreservingStateSnapshot(() => { const e = []; for (const n of t) { let t; try { const e = detectRepointedWorkspaceAlias(n); if (!e) continue; t = `${describeRepointedWorkspaceAlias(e)} Incoming messages cannot use this workspace until it is repaired.`; } catch (e) { t = `Workspace alias inspection failed for ${shortenHomePath(n)}: ${formatErrorMessage(e)}`; } e.push({ checkId: WORKSPACE_ALIAS_CHECK_ID, severity: "warning", category: "fix-now", docsUrl: "https://docs.openclaw.ai/cli/doctor/state-migrations", message: t, fixHint: REPAIR_HINT }); } return e; }); } async function maybeRepairRepointedWorkspaceAliases(e) { if (!e.prompter.shouldRepair) return; const t = await configuredWorkspaceDirs(e.cfg); const n = await readConfigFileSnapshot(); const verifyConfiguration = async () => { const e = await readConfigFileSnapshot(); if (e.readError || !isDeepStrictEqual(e.sourceConfig, n.sourceConfig)) throw new Error("Workspace configuration changed during repair. No records were transferred; rerun doctor to inspect the current workspace owners."); }; for (const n of t) try { const r = detectRepointedWorkspaceAlias(n); if (!r) continue; const i = describeRepointedWorkspaceAlias(r); const a = inspectWorkspaceAliasMove(n, r, t); if (a.kind === "blocked") { note(`${i} ${REBIND_MESSAGES[a.outcome]}`, "Workspace"); continue; } const o = { message: `${i} Confirm only if this is the same workspace after a folder move. Transfer its saved setup and file-verification history without changing workspace files?`, initialValue: false }; if (!(e.prompter.shouldForce ? await e.prompter.confirmAggressiveAutoFix(o) : await e.prompter.confirmRuntimeRepair({ ...o, requiresInteractiveConfirmation: true }))) { note(`${i} No records were transferred. ${REPAIR_HINT}`, "Workspace"); continue; } const s = await rebindRepointedWorkspaceAlias(n, r, {}, t, verifyConfiguration); note(s === "rebound" ? `Rebound workspace state for ${shortenHomePath(r.aliasPath)} to ${shortenHomePath(r.currentWorkspacePath)}. Workspace files were not changed.` : `${i} ${REBIND_MESSAGES[s]}`, "Workspace"); } catch (e) { note(`Workspace repair was not applied for ${shortenHomePath(n)}: ${formatErrorMessage(e)}`, "Workspace"); } } /** Stop migration discovery if its workspace owner still needs an operator decision. */ function createWorkspaceAliasMigrationRepair(e) { if (!e?.shouldRepair) return; return async (t) => { if ((await collectRepointedWorkspaceAliasFindings(t)).length === 0) return; await maybeRepairRepointedWorkspaceAliases({ cfg: t, prompter: e }); const n = await collectRepointedWorkspaceAliasFindings(t); if (n.length > 0) throw new Error(n.map((e) => `${e.message} ${e.fixHint}`).join("\n")); }; } //#endregion export { createWorkspaceAliasMigrationRepair as n, collectRepointedWorkspaceAliasFindings as t };