UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines • 11.8 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{f as shortenHomePath}from"./utils-Dlk0IYAa.mjs";import{n as ignoreMissingPath}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{s as pathMayExistSync}from"./path-existence-BR9MXlgL.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{a as getActiveOpenClawStateDatabaseReadSnapshotAsync,g as withExistingOpenClawStateDatabaseReadOnly,v as withOpenClawStateDatabaseReadSnapshot}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{n as isArtifactPreservingStateRead}from"./artifact-preserving-state-reads-CWuQPqxe.mjs";import{a as createWorkspaceStateIdentity,l as resolveWorkspaceStateAliases,o as normalizeWorkspaceIdentityPath,s as resolveCanonicalWorkspacePath}from"./workspace-state-identity-D-_UPy3C.mjs";import{o as runSqliteReadSnapshotSync}from"./sqlite-transaction-CON-dGDv.mjs";import{l as runOpenClawStateWriteTransaction,n as openOpenClawStateDatabase}from"./openclaw-state-db-BlgxYkYw.mjs";import{s as readConfigFileSnapshot}from"./io.runtime-BvSeVFIY.mjs";import"./io-Di_yuX3t.mjs";import{f as registerWorkspaceStateAliasIdentitiesInTransaction,u as readWorkspaceStateSnapshotFromDatabase}from"./workspace-state-store.kernel-Bz8jhdgj.mjs";import"./workspace-state-store-o0DidR-W.mjs";import{t as note}from"./note-e4DtVgg2.mjs";import{n as listWorkspaceStateDirs}from"./workspace-state-dirs-BRx-XPcW.mjs";import{r as prepareWorkspaceMigrationReceiptMove,t as applyWorkspaceMigrationReceiptMove}from"./state-migrations.workspace-setup-receipts-BGMuOZvD.mjs";import fs from"node:fs";import path from"node:path";import os from"node:os";import{isDeepStrictEqual}from"node:util"; //!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}}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()]}}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()});return`rebound`},n)} //!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.`};async function collectRepointedWorkspaceAliasFindings(e){const t=await configuredWorkspaceDirs(e);const collect=()=>{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};if(!isArtifactPreservingStateRead())return collect();return withOpenClawStateDatabaseReadSnapshot(async()=>{await getActiveOpenClawStateDatabaseReadSnapshotAsync();return collect()})}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`)}}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(` `))}}export{createWorkspaceAliasMigrationRepair as n,collectRepointedWorkspaceAliasFindings as t};