UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 10 kB
import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{u as observeDiagnosticsTimelinePhases}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{s as composeSessionSourceAssertion,u as prepareSessionSourceEffect}from"./session-source-authority-Cun3s-rH.mjs";import{o as timeWorktreePreparationPhase}from"./preparation-timing-CC2_vlen.mjs";import{d as withWorktreeRunEnd,i as captureWorktreeRunEndContext}from"./run-end-lifecycle-mk2iX8J8.mjs";import{n as prepareWorktreeFilesystemMutation,t as nativeWorktreeFilesystem}from"./filesystem-native-BvDS5nVZ.mjs";import{c as isLocalWorkspaceBaseRefreshRef}from"./workspace-result-inventory-Cl0lnMl9.mjs";import{d as serializeWorkerWorkspaceReconciliationPlan}from"./workspace-manifest-BE9NudAI.mjs";import{n as AcceptedWorkspacePublicationIndeterminateError,t as applyStagedWorkerWorkspace}from"./workspace-reconcile-B9s9mGfp.mjs";import{m as workerWorkspaceResultStaging,p as workerWorkspaceResultRef}from"./workspace-result-staging-BsmW1zVW.mjs";import{t as assertLocalWorkspaceDirectory}from"./local-workspace-checkout-BneJgVKr.mjs";import{n as withLocalWorkspaceReconciliation}from"./local-workspace-store-qYpfrXeb.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import fs from"node:fs/promises"; //!src/gateway/worker-environments/local-workspace-checkpoint.ts const pendingCaptureRemovals=resolveGlobalSingleton(Symbol.for(`openclaw.localWorkspaceCaptureRemovals`),()=>/* @__PURE__ */ new Map);const log=createSubsystemLogger(`agents/worktrees`);function captureRemovalOwner(e,t){const n=captureWorktreeRunEndContext(t??process.env);return{context:n,key:JSON.stringify([n.admission.coordinationKey,e])}}async function retireLocalWorkspaceCheckpointCapture(e,t){try{var n=_usingCtx();const r=path.dirname(e);const i=path.join(r,`checkpoint-retired-${randomUUID()}`);const a=await prepareSessionSourceEffect(composeSessionSourceAssertion([t.commitGuard,t.workerAuthority?.assertCurrent]));n.a({[Symbol.asyncDispose]:async()=>await a.release?.()});await prepareWorktreeFilesystemMutation(t,a);t.signal?.throwIfAborted();a.assertCurrent();try{await fs.rename(path.join(r,`checkpoint-capture`),i)}catch(e){if(hasErrnoCode(e,`ENOENT`))return;throw e}a.assertCurrent();const{context:o,key:s}=captureRemovalOwner(e,t.env);const c=withWorktreeRunEnd(o.environment,()=>nativeWorktreeFilesystem.remove(i,{commitGuard:o.admission.assertCurrent}),{independent:true});pendingCaptureRemovals.set(s,c);c.then(()=>pendingCaptureRemovals.delete(s),e=>{pendingCaptureRemovals.delete(s);log.warn(`Local workspace checkpoint capture cleanup failed: ${String(e)}`)})}catch(e){n.e=e}finally{await n.d()}}async function finishRetiredCheckpointCaptures(e,t){const{key:n}=captureRemovalOwner(e,t.env);await pendingCaptureRemovals.get(n)?.catch(()=>{});const r=path.dirname(e);for(const e of await fs.readdir(r))if(/^checkpoint-retired-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u.test(e))await nativeWorktreeFilesystem.remove(path.join(r,e),t)}async function removeLocalWorkspaceCheckpointCapture(e,t){const n=path.join(path.dirname(e),`checkpoint-capture`);if(await fs.lstat(n).then(()=>true,e=>{if(hasErrnoCode(e,`ENOENT`))return false;throw e}))await nativeWorktreeFilesystem.remove(n,t)}async function prepareLocalWorkspaceCheckpointCapture(e,t,n,r,i){await finishRetiredCheckpointCaptures(e,t);await removeLocalWorkspaceCheckpointCapture(e,t);const a=await fs.lstat(e,{bigint:true});if(a.ino!==256n){i.reason=`non-subvolume`;return}if(await nativeWorktreeFilesystem.probe(path.dirname(e),t)!==`btrfs`){i.reason=`btrfs-unavailable`;return}i.reason=`btrfs`;const o=path.join(path.dirname(e),`checkpoint-capture`);return async s=>{const c=Date.now();const l=performance.now();i.preCopyMs=i.pausedAt===void 0?void 0:l-i.pausedAt;let u;try{try{await nativeWorktreeFilesystem.copy(e,o,t)}finally{u=performance.now();i.copyMs=u-l}}catch(e){const t=[`CLONE_UNAVAILABLE`,`EXDEV`,`ENOSYS`].find(t=>hasErrnoCode(e,t));if(!t)throw e;i.reason=`clone-unavailable`;i.cloneError=t;await r();await s();return}const d=await fs.lstat(o,{bigint:true});i.postCopyBeforeResumeMs=performance.now()-u;await n();try{await s({root:o,sourceDev:a.dev,snapshotDev:d.dev,capturedAtMs:c})}catch(e){if(!hasErrnoCode(e,`WORKSPACE_SNAPSHOT_INCOMPLETE`))throw e;i.reason=`nested-incomplete`;await r();await s()}}}var UnstagedWorkspacePathError=class extends Error{};var RejectedLocalWorkspaceResultError=class extends Error{constructor(e,t,n,r){super(e);this.repairable=t;this.resultRef=n;this.projectionPath=r}};function createLocalWorkspaceCheckpointRejection(e){const repairTarget=t=>!isLocalWorkspaceBaseRefreshRef(t.pending_ref)&&e.removedAt===void 0?pendingLocalWorkspaceDirection(t.pending_target):void 0;const rejection=t=>{const n=e.current();return new RejectedLocalWorkspaceResultError(t,repairTarget(n)===`canonical`,n.pending_ref,n.projection_path)};const assertNotRejected=()=>{const t=e.current();if(t.rejectedResult)throw rejection(t.rejectedResult.reason);return t};return{assertNotRejected,settle:async(t,n)=>{assertNotRejected();try{await t()}catch(t){if(!(t instanceof Error)||!hasErrnoCode(t,`WORKSPACE_RESULT_LIMIT`))throw t;const r=e.current();if(r.pending_ref&&r.pending_target&&!r.journal_json){const i=t.message+` Pending workspace changes were preserved. Move disposable build outputs to checkout-root .openclaw/tmp/ or remove unneeded outputs`+(r.pending_target===`projection`?` in the canonical workspace, then retry workspace preparation.`:`, then checkpoint the corrected workspace.`);await e.reject(r,{reason:i,manifestRef:n});throw rejection(i)}throw t}},synchronize:async t=>{const n=e.current();const r=n.rejectedResult;const i=Boolean(t.captureRejected&&r&&t.target===repairTarget(n));if(!i)await t.settle();const capture=async n=>{const a=await t.scan(t.target,n);if(i&&r&&(a.currentManifestRef===r.manifestRef||a.resultingRoot===r.manifestRef))throw rejection(r.reason);if(a.resultingRoot!==a.previousRoot){await e.update({pending_ref:workerWorkspaceResultRef(randomUUID()),pending_target:t.target,checkpoint_json:JSON.stringify(a)});await t.settle(false,a,t.afterCapture,n)}else if(i)await e.update({pending_ref:null,pending_target:null,checkpoint_json:null})};await(t.capture?t.capture(capture):capture())}}}function pendingLocalWorkspaceDirection(e){return e===`canonical`||e===`projection`?e:void 0}function selectLocalWorkspaceCheckpoint(e,t){const n=pendingLocalWorkspaceDirection(e.pending_target);if(!e.baseline_ref||!n)throw new Error(`Local workspace result has no accepted baseline`);return{target:n,refresh:isLocalWorkspaceBaseRefreshRef(t)}}async function stageLocalWorkspaceCheckpoint(e,t){try{return await workerWorkspaceResultStaging.stageWorkerWorkspaceResult(e)}catch(n){t.signal.throwIfAborted();const r=t.current();if(n instanceof Error&&hasErrnoCode(n,`WORKSPACE_STAGE_CURRENT_PATH_UNSAFE`)&&t.target===`canonical`&&!t.refresh&&t.snapshot?.previousRoot===r.baseline_ref&&r.pending_ref===e.stagedResultRef&&r.pending_target===`canonical`&&!r.journal_json)throw new UnstagedWorkspacePathError(n.message,{cause:n});throw n}}async function prepareLocalWorkspaceCheckpoint(e){try{var t=_usingCtx();const n=`attempt.setup.sandbox.workspace_selection.${e.operation}.reconcile.checkpoint`;const r=t.u(observeDiagnosticsTimelinePhases(`${n}.directory`));await assertLocalWorkspaceDirectory(e.current().projection_path);const i=e.current();if(i.rejectedResult&&i.pending_target===`projection`){r.mark(`${n}.repair`);await e.synchronize(`projection`,{captureRejected:true})}if(e.baselineRef){r.mark(`${n}.canonical`);try{await timeWorktreePreparationPhase(`synchronizeCanonical`,()=>e.synchronize(`canonical`))}catch(t){if(!(t instanceof UnstagedWorkspacePathError)&&!(t instanceof RejectedLocalWorkspaceResultError&&t.repairable))throw t;e.signal.throwIfAborted();return e.current().projection_path}}r.mark(`${n}.projection`);await timeWorktreePreparationPhase(`synchronizeProjection`,()=>e.synchronize(`projection`));return e.current().projection_path}catch(e){t.e=e}finally{t.d()}}function applyLocalWorkspaceCheckpoint(e){e.current();let t;const n={journal:{load:async()=>void 0,begin:async(t,n)=>{await e.update({journal_json:serializeWorkerWorkspaceReconciliationPlan(t),journal_pack:t.basePack},void 0,n)},abort:async()=>{await e.update({journal_json:null,journal_pack:null})},commit:async()=>{e.beforeCommit();if(!t)throw new Error(`Local workspace acceptance is missing`);try{if(t.length)await e.update({journal_json:null,journal_pack:null});else if(e.refreshBaseCommit&&e.target===`canonical`)await e.update({pending_target:`projection`,journal_json:null,journal_pack:null});else{const t={...e.refreshBaseCommit?{base_commit:e.refreshBaseCommit}:{},pending_target:null,journal_json:null,journal_pack:null};if(e.checkpoint)await e.update(t,{...e.checkpoint,fingerprintsFromCheckpoint:e.checkpoint.fingerprints?true:void 0});else await e.replaceBaseline(e.rawManifest,e.manifestRef,t)}}catch(e){throw new AcceptedWorkspacePublicationIndeterminateError(`commit`,e)}}},acceptance:{kind:`checkpoint`,publish:async n=>{e.current();t=n}}};return withLocalWorkspaceReconciliation({worktreeId:e.selected.worktree_id,pendingRef:e.selected.pending_ref,baseCommit:e.selected.base_commit,targetCommit:e.application.current.baseCommit,target:e.target,reason:e.reason},t=>applyStagedWorkerWorkspace({...e.application,...n,onPhase:n=>{if(n===`apply`)t();e.application.onPhase?.(n)}}))}export{prepareLocalWorkspaceCheckpoint as a,retireLocalWorkspaceCheckpointCapture as c,pendingLocalWorkspaceDirection as i,selectLocalWorkspaceCheckpoint as l,applyLocalWorkspaceCheckpoint as n,prepareLocalWorkspaceCheckpointCapture as o,createLocalWorkspaceCheckpointRejection as r,removeLocalWorkspaceCheckpointCapture as s,RejectedLocalWorkspaceResultError as t,stageLocalWorkspaceCheckpoint as u};