UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

11 lines • 34.4 kB
import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import"./abort-signal-BKkRe6pu.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.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{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{s as registerOpenClawAgentDatabaseAsyncResource}from"./openclaw-agent-db-resources-KCMTIo4b.mjs";import{n as OpenClawStateLeaseError}from"./openclaw-state-lease-error-DCUL0v5x.mjs";import{s as composeSessionSourceAssertion}from"./session-source-authority-Cun3s-rH.mjs";import{l as withSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{v as retainPreparedSessionEntryPredicate}from"./session-accessor.sqlite-entry-cache-publication-state-D1mC85IV.mjs";import{t as captureSessionEntryMetadataRead}from"./session-entry-source-authority-DYDyuUDE.mjs";import{i as patchSessionEntryCore}from"./session-accessor.sqlite-entry-CQTjQD5y.mjs";import{d as runGit,o as requireGit}from"./git-2P0YMMKQ.mjs";import{a as startWorktreePreparationPhase,o as timeWorktreePreparationPhase}from"./preparation-timing-CC2_vlen.mjs";import{i as captureWorktreeRunEndContext}from"./run-end-lifecycle-mk2iX8J8.mjs";import{a as prepareWorktreeRegistryGuard,d as readRegistryWorktree,l as readLiveRegistryWorktreeByPath,t as captureWorktreeRegistryReadGuard}from"./registry-read-mqD__iTh.mjs";import{t as nativeWorktreeFilesystem}from"./filesystem-native-BvDS5nVZ.mjs";import{c as isLocalWorkspaceBaseRefreshRef}from"./workspace-result-inventory-Cl0lnMl9.mjs";import{S as workspaceManifestPaths,i as captureWorkspaceManifestDocument,u as loadStagedWorkspaceManifest}from"./workspace-manifest-worker-C4V2H1Gh.mjs";import{s as buildCacheInputPaths}from"./workspace-path-exclusions-Cmi1311P.mjs";import{c as parseWorkerWorkspaceManifest,l as parseWorkerWorkspaceReconciliationPlan,u as serializeWorkerWorkspaceManifest}from"./workspace-manifest-BE9NudAI.mjs";import{l as workspaceSizeRecoveryPaths}from"./workspace-manifest-comparison-DFPdvJq-.mjs";import{i as recoverWorkerWorkspaceReconciliation}from"./workspace-reconcile-recovery-CYJWqiBW.mjs";import"./workspace-reconcile-B9s9mGfp.mjs";import{a as hasWorkerWorkspaceResultRef,d as withStagedWorkerWorkspaceManifest,m as workerWorkspaceResultStaging,p as workerWorkspaceResultRef,r as deleteStagedWorkerWorkspaceResult}from"./workspace-result-staging-BsmW1zVW.mjs";import{n as initializeLocalWorkspaceProjection,r as localWorkspaceProjectionPath,t as assertLocalWorkspaceDirectory}from"./local-workspace-checkout-BneJgVKr.mjs";import{r as withLocalWorkspaceStore}from"./local-workspace-store-qYpfrXeb.mjs";import{a as prepareLocalWorkspaceCheckpoint,c as retireLocalWorkspaceCheckpointCapture,i as pendingLocalWorkspaceDirection,l as selectLocalWorkspaceCheckpoint,n as applyLocalWorkspaceCheckpoint,o as prepareLocalWorkspaceCheckpointCapture,r as createLocalWorkspaceCheckpointRejection,s as removeLocalWorkspaceCheckpointCapture,u as stageLocalWorkspaceCheckpoint}from"./local-workspace-checkpoint-B5FKq_JO.mjs";import{t as LocalWorkspaceConflictError}from"./local-workspace-conflict-error-oVQF3WJD.mjs";import{c as selectLocalWorkspaceCanonicalPaths,i as parseLocalWorkspaceSourcePaths,n as captureLocalWorkspaceArchiveBaseline,o as prepareLocalWorkspaceBuildInputs,s as readLocalWorkspaceGitExclusions,t as admitLocalWorkspaceSourcePaths}from"./local-workspace-inventory-DZGCCq8R.mjs";import path from"node:path";import{randomUUID}from"node:crypto"; //!src/gateway/worker-environments/local-workspace-owner-identity.ts function assertLocalWorkspaceProjectionOwner(e,t,n){if(e.worktree_id!==t.worktree.id||e.agent_id!==t.agentId||e.session_key!==t.sessionKey||e.session_id!==t.sessionId||e.lifecycle_revision!==t.lifecycleRevision||n!==void 0&&e.projection_path!==n)throw new Error(`Local sandbox workspace belongs to a different session incarnation; pending edits were preserved`)}function bindLocalWorkspaceAuthority(e,t,n){return{...t,workspaceEvidence:[...t.workspaceEvidence??[],...e.workerAuthority?.workspaceEvidence??[]],stateOwnerPath:e.workerAuthority?.stateOwnerPath??t.stateOwnerPath,predicates:e.workerAuthority?.predicates??t.predicates,assertCurrent:()=>void n(e.workerAuthority?.assertCurrent??e.assertCurrent)}} //!src/gateway/worker-environments/local-workspace-handoff.ts async function finishLocalWorkspaceHandoff(e,t){e.assertCurrent();if(t.worktreeId!==e.worktree.id||t.toSessionId!==e.sessionId)throw new Error(`Local workspace handoff belongs to a different session incarnation`);const n=await localWorkspaceProjectionPath(e);e.assertCurrent();await withLocalWorkspaceStore({...e,worktreeId:e.worktree.id},async r=>{const i=r.get();if(!i)throw new Error(`Local workspace handoff lost its saved projection; recovery data was preserved`);if(i.session_id===e.sessionId&&i.lifecycle_revision===e.lifecycleRevision){assertLocalWorkspaceProjectionOwner(i,e,n);return}assertLocalWorkspaceProjectionOwner(i,{...e,sessionId:t.fromSessionId,lifecycleRevision:t.lifecycleRevision},n);if(i.revision!==t.projectionRevision||i.pending_ref||i.journal_json||i.paused_runtimes_json)throw new Error(`Local workspace changed after history-cut settlement; saved edits were preserved`);await r.update(i,{session_id:e.sessionId,lifecycle_revision:e.lifecycleRevision},e.workerAuthority)})} //!src/gateway/worker-environments/local-workspace-state.ts const log$1=createSubsystemLogger(`agents/worktrees`);function projectionOperations(e,t,n,r,i,a=`reconcile`){const o=t.signal;let s=n;const selectCurrent=n=>{if(!s)throw new Error(`Local workspace binding is missing`);n?.();assertLocalWorkspaceProjectionOwner(s,e);if(s.projection_path!==r||t.get()?.revision!==s.revision)throw new Error(`Local workspace binding changed`);return s};const current=()=>selectCurrent(e.assertCurrent);const assertCurrent=()=>void current();const c=bindLocalWorkspaceAuthority(e,t.workerAuthority,selectCurrent);const update=async(n,r,i)=>{s=await t.update(current(),n,e.workerAuthority,r,i)};const l=createLocalWorkspaceCheckpointRejection({current,update,removedAt:e.worktree.removedAt,reject:async(n,r)=>{s=await t.reject(n,r,e.workerAuthority)}});const repairBaseline=async()=>{const n=await t.manifest(current(),{kind:`repair`,canonicalRoot:e.worktree.path});if(n.kind!==`replace`)throw new Error(`Local workspace baseline repair is missing`);s=await t.accept(n.update,e.workerAuthority)};const readManifest=async e=>{try{return await t.manifest(current(),e)}catch(n){if(!(n instanceof Error)||!n.message.includes(`Local workspace baseline nodes are missing`))throw n;await repairBaseline();return await t.manifest(current(),e)}};const baselineDocument=async()=>{const e=await readManifest({kind:`materialize`});current();if(e.kind!==`materialize`)throw new Error(`Local workspace baseline materialization is missing`);return e};const replaceBaseline=async(e,t,n={})=>{await update(n,{rawManifest:e,manifestRef:t,buildCacheInputs:await buildCacheInputs()})};const sourcePath=t=>t===`canonical`?current().projection_path:e.worktree.path;const targetPath=t=>t===`canonical`?e.worktree.path:current().projection_path;let u;let d;const buildCacheInputs=()=>u??=prepareLocalWorkspaceBuildInputs({worktree:e.worktree,projection:current(),signal:o,assertCurrent,retainSourcePaths:e=>update({source_paths_json:e})}).then(e=>{d=e.paths;return e.retained});const canonicalPaths=async()=>{const t=await buildCacheInputs();const n=current();const r=n.baseline_ref?await baselineDocument():void 0;return await selectLocalWorkspaceCanonicalPaths({root:e.worktree.path,admittedPaths:d?void 0:parseLocalWorkspaceSourcePaths(n.source_paths_json),preparedPaths:d,signal:o,assertCurrent,baselinePaths:r?await workspaceManifestPaths(r,t,o):void 0})};const capture=async(t,n)=>{const r=sourcePath(t);await assertLocalWorkspaceDirectory(r);const i=await canonicalPaths();const a=await captureWorkspaceManifestDocument({root:r,baseCommit:current().base_commit,includePaths:t===`projection`?i:void 0,gitIgnore:t===`canonical`&&e.worktree.removedAt===void 0?await readLocalWorkspaceGitExclusions(e.worktree.path,r,i):void 0,buildCacheInputs:new Set(await buildCacheInputs()),preserveDirectories:n,signal:o});current();return a};const scan=async(n,r)=>{if(n===`projection`)await i?.resume();i?.markPhase(`scan`);await assertLocalWorkspaceDirectory(r?.root??sourcePath(n));const a=await readManifest({kind:`scan`,target:n,canonicalRoot:e.worktree.path,capture:r});current();if(a.kind!==`scan`)throw new Error(`Local workspace checkpoint scan is missing`);const{observation:o,...c}=a;if(o)s=await t.accept(o,e.workerAuthority);u=Promise.resolve(a.buildCacheInputs);d=void 0;return c};const recover=async()=>{const e=current();if(!e.journal_json)return;await i?.pause();i?.markPhase(`recovery`);if(!e.journal_pack||!pendingLocalWorkspaceDirection(e.pending_target))throw new Error(`Local workspace recovery metadata is incomplete`);if(!isLocalWorkspaceBaseRefreshRef(e.pending_ref)){const t=parseWorkerWorkspaceReconciliationPlan(e.journal_json);await recoverWorkerWorkspaceReconciliation({root:targetPath(pendingLocalWorkspaceDirection(e.pending_target)),journal:{...t,basePack:e.journal_pack},buildCacheInputs:await buildCacheInputs(),assertCurrent,workerAuthority:c})}await update({journal_json:null,journal_pack:null})};const cleanupAccepted=async()=>{const t=current();if(!t.pending_ref||t.pending_target)return;i?.markPhase(`cleanup`);await deleteStagedWorkerWorkspaceResult({root:e.worktree.repoRoot,stagedResultRef:t.pending_ref,assertCurrent,workerAuthority:c});await update({pending_ref:null,checkpoint_json:null,...t.tree_root_digest?{baseline_json:null}:{}})};const settle=(n=false,r,u,d)=>l.settle(async()=>{await recover();const l=current();if(l.baseline_ref&&!l.tree_root_digest){const n=await readManifest({kind:`convert`});if(n.kind===`rescan`){log$1.warn(`Local workspace baseline conversion changed its reference; preserved source data and requesting full-scan baseline repair`);await repairBaseline()}else if(n.kind===`replace`)s=await t.accept(n.update,e.workerAuthority);else throw new Error(`Local workspace conversion preparation is missing`)}if(!n)await cleanupAccepted();const f=current();if(!f.pending_ref)return;const{target:p,refresh:m}=selectLocalWorkspaceCheckpoint(f,f.pending_ref);if(!await hasWorkerWorkspaceResultRef({root:e.worktree.path,stagedResultRef:f.pending_ref})){if(m)throw new Error(`Workspace integration source is unavailable; retry github_publish prepare_pr for an imported PR, or refresh_base for the selected project. Saved work was preserved.`);let t=r;if(!t&&(f.checkpoint_json||e.worktree.removedAt===void 0)){t=await scan(p);await update({checkpoint_json:JSON.stringify(t)})}const n=t?void 0:await baselineDocument();const a=n&&parseWorkerWorkspaceManifest(n.rawManifest,n.manifestRef,await buildCacheInputs());const s=a&&await capture(p,new Set(a.directories));const l=a&&e.worktree.removedAt!==void 0&&e.worktree.snapshotRef?await captureLocalWorkspaceArchiveBaseline({root:e.worktree.repoRoot,snapshotCommit:await requireGit(e.worktree.repoRoot,[`rev-parse`,`${e.worktree.snapshotRef}^{commit}`],{signal:o,beforeRun:assertCurrent}),manifest:a,signal:o,assertCurrent}):n;i?.markPhase(`staging`);await stageLocalWorkspaceCheckpoint({root:e.worktree.path,stagingRoot:d?.root??sourcePath(p),stagedResultRef:f.pending_ref,baseManifestRef:t?.baseManifestRef??l.manifestRef,currentManifestRef:t?.currentManifestRef??s.manifestRef,baseManifestRaw:t?.baseManifestRaw??l.rawManifest,currentManifestRaw:t?.currentManifestRaw??s.rawManifest,buildCacheInputs:t?.buildCacheInputs??await buildCacheInputs(),assertCurrent,workerAuthority:c},{target:p,refresh:m,snapshot:t,current,signal:o})}const h=current().checkpoint_json?JSON.parse(current().checkpoint_json):void 0;if(h&&h.previousRoot!==f.baseline_ref)throw new Error(`Local workspace checkpoint no longer matches its baseline`);await u?.();if(!m)await i?.resume();i?.markPhase(`materialization`);const g=m?await baselineDocument():void 0;await withStagedWorkerWorkspaceManifest({root:e.worktree.path,stagedResultRef:f.pending_ref,buildCacheInputs:h?.buildCacheInputs??await buildCacheInputs()},async e=>{if(m&&(!e.current.baseCommit||e.baseManifestRef!==g.manifestRef))throw new Error(`Local workspace result no longer matches its accepted baseline`);if(h&&(e.baseManifestRef!==h.baseManifestRef||e.currentManifestRef!==h.currentManifestRef))throw new Error(`Local workspace checkpoint payload changed`);await applyLocalWorkspaceCheckpoint({selected:f,reason:a,application:{root:targetPath(p),stagingRoot:e.stagingRoot,baseManifestRef:e.baseManifestRef,currentManifestRef:e.currentManifestRef,reconciliation:e.reconciliation,current:e.current,assertCurrent,workerAuthority:c,freezeTarget:p===`projection`?i?.pause:void 0,onPhase:i?.markPhase},current,update,replaceBaseline,checkpoint:h,target:p,refreshBaseCommit:m?e.current.baseCommit:void 0,rawManifest:e.currentManifestRaw,manifestRef:e.currentManifestRef,beforeCommit:()=>i?.markPhase(`acceptance`)});if(!m||!current().pending_target)await i?.resume();i?.markPhase(`cleanup`)});if(m&&p===`canonical`&&current().pending_target===`projection`)return await settle(n);if(current().pending_target)throw new LocalWorkspaceConflictError;if(!n)await cleanupAccepted()},r?.currentManifestRef);const synchronize=async(e,t)=>{await l.synchronize({target:e,capture:e===`canonical`?i?.capture:void 0,...t,settle,scan});await i?.pause()};const prepare=async(n,i=`prepare`)=>{try{var a=_usingCtx();const l=`attempt.setup.sandbox.workspace_selection.${i}.reconcile`;const u=a.u(observeDiagnosticsTimelinePhases(`${l}.head`));if(!s){const n=await requireGit(e.worktree.path,[`rev-parse`,`--verify`,`HEAD^{commit}`],{signal:o,beforeRun:e.assertCurrent});u.mark(`${l}.sources`);const i=await admitLocalWorkspaceSourcePaths({root:e.worktree.path,signal:o,assertCurrent:e.assertCurrent});e.assertCurrent();u.mark(`${l}.reservation`);s=await t.create({worktree_id:e.worktree.id,agent_id:e.agentId,session_key:e.sessionKey,session_id:e.sessionId,lifecycle_revision:e.lifecycleRevision,projection_path:r,base_commit:n,source_paths_json:i,baseline_json:null,baseline_ref:null,tree_root_digest:null,source_paths_digest:null,canonical_fingerprints:null,projection_fingerprints:null,checkpoint_json:null,pending_ref:null,pending_target:null,journal_json:null,journal_pack:null,paused_runtimes_json:null,created_at_ms:Date.now()},e.workerAuthority)}const d=current();if(!d.baseline_ref){u.mark(`${l}.initialization`);const t=await initializeLocalWorkspaceProjection({owner:e,projectionPath:d.projection_path,baseCommit:d.base_commit,signal:o,assertCurrent,workerAuthority:c,buildCacheInputs,dependencies:n});u.mark(`${l}.baseline`);await update({projection_fingerprints:t.projectionFingerprints??null},t)}u.mark(`${l}.checkpoint`);return await prepareLocalWorkspaceCheckpoint({operation:i,baselineRef:d.baseline_ref,synchronize,current,signal:o})}catch(e){a.e=e}finally{a.d()}};return{current,workerAuthority:c,canonicalPaths,capture,buildCacheInputs,baselineDocument,prepare,reuse:async()=>s?.baseline_ref?await prepare(void 0,`reuse`):void 0,synchronize,settle:async()=>{await settle();await i?.pause()},recover,applyBaseRefresh:async t=>{if(!isLocalWorkspaceBaseRefreshRef(t))throw new Error(`Workspace base refresh requires its own source result`);await settle();const n=await loadStagedWorkspaceManifest(e.worktree.path,t);const r=buildCacheInputPaths(n.current.entries.map(e=>e.path));const i=current();const a=parseLocalWorkspaceSourcePaths(i.source_paths_json);const o=JSON.stringify([.../* @__PURE__ */ new Set([...a,...r])]);await update({pending_ref:t,pending_target:`canonical`,...o===i.source_paths_json?{}:{source_paths_json:o}});u=void 0;d=void 0;await settle()},restoreSnapshot:async()=>{await buildCacheInputs();await recover();const t=current();if(!t.pending_ref)return;if(!t.pending_target){const n=await loadStagedWorkspaceManifest(e.worktree.repoRoot,t.pending_ref,void 0,await buildCacheInputs());current();const r=await baselineDocument();if(n.currentManifestRef!==r.manifestRef)throw new Error(`Archive restore receipt changed`);await replaceBaseline(n.baseManifestRaw,n.baseManifestRef,{pending_target:`canonical`,checkpoint_json:null})}await settle(true)},finishRestore:cleanupAccepted,prepareArchive:async()=>{await settle();if((await runGit(e.worktree.path,[`rev-parse`,`--verify`,`--quiet`,`MERGE_HEAD`],{signal:o,beforeRun:assertCurrent})).code!==1)throw new Error(`Workspace integration is pending; finish the original github_publish prepare_pr or refresh_base action before archiving this worktree. Saved files and merge state were preserved.`);return async t=>{await assertLocalWorkspaceDirectory(sourcePath(`canonical`));const n=await readManifest({kind:`archive`,canonicalRoot:e.worktree.path,archiveRoot:e.worktree.repoRoot,snapshotCommit:t});if(n.kind!==`archive`)throw new Error(`Local workspace archive preparation is missing`);if(!n.overlay)return;const{base:r,accepted:i}=n.overlay;const a=workerWorkspaceResultRef(randomUUID());await update({pending_ref:a,pending_target:`canonical`,checkpoint_json:null});await l.settle(async()=>{await workerWorkspaceResultStaging.stageWorkerWorkspaceResult({root:e.worktree.repoRoot,stagingRoot:current().projection_path,stagedResultRef:a,baseManifestRaw:r.rawManifest,baseManifestRef:r.manifestRef,currentManifestRaw:i.rawManifest,currentManifestRef:i.manifestRef,buildCacheInputs:await buildCacheInputs(),assertCurrent,workerAuthority:c})},current().baseline_ref??void 0);current()}},expire:async n=>{const r=l.assertNotRejected();if(r.journal_json||r.pending_target&&r.pending_target!==`canonical`)throw new Error(`Local sandbox has pending edits; restore its worktree before cleanup`);const i=r.baseline_ref?await baselineDocument():void 0;let a=i?{raw:i.rawManifest,ref:i.manifestRef}:void 0;if(r.pending_ref){if(!n||e.worktree.removedAt===void 0)throw new Error(`Archive receipt still owns its restore data`);if(r.pending_target){const t=await loadStagedWorkspaceManifest(e.worktree.repoRoot,r.pending_ref,void 0,await buildCacheInputs());current();if(t.baseManifestRef!==i?.manifestRef&&t.currentManifestRef!==i?.manifestRef)throw new Error(`Archive retention receipt changed`);a={raw:t.currentManifestRaw,ref:t.currentManifestRef}}}if(a){const e=parseWorkerWorkspaceManifest(a.raw,a.ref,await buildCacheInputs());if((await capture(`canonical`,new Set(e.directories))).rawManifest!==serializeWorkerWorkspaceManifest(e))throw new Error(`Local sandbox has unaccepted edits; restore its worktree before cleanup`)}const{readLocalWorkspaceRuntimes:s}=await import(`./local-workspace-quiescence-B2aGkIL9.mjs`);if((await s(r.projection_path,{env:e.env})).length)throw new Error(`Local sandbox runtime still owns its workspace; cleanup deferred`);const u=path.dirname(r.projection_path);await assertLocalWorkspaceDirectory(u);current();await n?.(assertCurrent);current();if(r.pending_ref&&a){await replaceBaseline(a.raw,a.ref,{pending_target:null,checkpoint_json:null});await cleanupAccepted()}await nativeWorktreeFilesystem.remove(u,{commitGuard:composeSessionSourceAssertion([assertCurrent,c.assertCurrent]),signal:o,workerAuthority:c});await t.delete(current(),e.workerAuthority)},rememberPaused:e=>update({paused_runtimes_json:e})}} //!src/gateway/worker-environments/local-workspace-projection-operation.ts const log=createSubsystemLogger(`agents/worktrees`);async function runLocalWorkspaceProjection(e,t,n,r={}){e.assertCurrent();r.onPhase?.(`operation`);let i=t.get();if(i&&i.session_id===e.sessionId&&i.session_key===e.sessionKey&&i.agent_id===e.agentId&&i.lifecycle_revision!==e.lifecycleRevision)i=await t.update(i,{lifecycle_revision:e.lifecycleRevision},e.workerAuthority);const a=!r.provision&&(r.reason===void 0||r.reason===`reconcile`||r.reason===`preparation`);let o=false;const s=await localWorkspaceProjectionPath(e);e.assertCurrent();t.assertCurrent();const c=projectionOperations(e,t,i,s,a?{pause:()=>pause(),resume:()=>resume(),capture:async e=>{await pause();markPhase(`capture`);const t=g;g=void 0;o||=Boolean(t);await(t?t(e):e())},markPhase:e=>markPhase(e)}:void 0,r.reason);if(i)c.current();const{quiesceLocalWorkspace:l,parseLocalWorkspacePausedRuntimes:u}=await import(`./local-workspace-quiescence-B2aGkIL9.mjs`);const d={env:e.env,signal:t.signal,commitGuard:()=>void c.current(),workerAuthority:e.workerAuthority};let f;const markPhase=e=>{f?.markPhase(e);r.onPhase?.(e)};let p=false;const m={reason:`adaptive-direct`};const resume=async()=>{if(p)r.onPhase?.(`resume`);const e=performance.now();try{await f?.resume();p=false}finally{m.resumeMs=(m.resumeMs??0)+performance.now()-e}};const pause=async()=>{if(p)return;r.onPhase?.(`pause`);f=i&&!r.provision?await timeWorktreePreparationPhase(`runtimeQuiesce`,()=>l({env:e.env,reason:r.reason,workspaceDir:i.projection_path,retained:u(c.current().paused_runtimes_json),persist:e=>c.rememberPaused(e.length?JSON.stringify(e):null),assertCurrent:()=>void c.current()})):void 0;p=Boolean(f);m.pausedAt=performance.now();r.onPhase?.(`operation`)};const h=a||r.reason===`checkpoint`&&r.snapshotCapture;r.onPhase?.(`capturePreparation`);let g=i?.baseline_ref&&h?await prepareLocalWorkspaceCheckpointCapture(i.projection_path,d,()=>timeWorktreePreparationPhase(`runtimeResume`,resume),pause,m):void 0;if(!g||r.reason!==`checkpoint`)await pause();let _=false;try{const e=await n(c,(f||g)&&{get retired(){return f?.retired??false},retire:async()=>{await pause();await f?.retire()},resume,markPhase},g);_=true;return e}catch(t){if(t instanceof Error&&workspaceSizeRecoveryPaths(t).length>0){const{describeLocalWorkspaceRecovery:n}=await import(`./local-workspace-recovery-5wYuuRQR.mjs`);throw await n(t,e,c)}throw t}finally{try{if(!f?.retired)t.workerAuthority.assertCurrent?.();const e=f?.retired?void 0:t.get();if(e&&!e.journal_json&&!(e.pending_target&&isLocalWorkspaceBaseRefreshRef(e.pending_ref))){if(f)await timeWorktreePreparationPhase(`runtimeResume`,resume)}if(i&&(r.reason===`checkpoint`||o)){r.onPhase?.(`cleanup`);if(_)await retireLocalWorkspaceCheckpointCapture(i.projection_path,d);else await removeLocalWorkspaceCheckpointCapture(i.projection_path,d)}}finally{if(i&&r.reason===`checkpoint`)log.info(`Local workspace checkpoint capture: worktree=${e.worktree.id} path=${m.reason===`btrfs`?`snapshot`:`paused`} reason=${m.reason} attemptedSnapshot=${m.copyMs!==void 0} cloneError=${m.cloneError??`-`} preCopyMs=${m.preCopyMs?.toFixed(1)??`-`} copyMs=${m.copyMs?.toFixed(1)??`-`} postCopyBeforeResumeMs=${m.postCopyBeforeResumeMs?.toFixed(1)??`-`} resumeMs=${m.resumeMs?.toFixed(1)??`-`} accepted=${_}`)}}} //!src/gateway/worker-environments/local-workspace-projection.ts const pendingCheckpoints=/* @__PURE__ */ new Map;const pendingPreparations=/* @__PURE__ */ new Map;function withLocalWorkspacePreparation(e,t,n){return joinLocalWorkspaceOperation(pendingPreparations,e,[e.agentId,e.sessionKey,e.sessionId,e.lifecycleRevision],n,t)}async function joinLocalWorkspaceOperation(e,t,n,r,i={}){const a=captureWorktreeRunEndContext(t.env??process.env);const assertCurrent=()=>{a.admission.assertCurrent();i.signal?.throwIfAborted();t.assertCurrent?.();t.workerAuthority?.assertCurrent?.()};assertCurrent();const{worktree:o}=t;const s=JSON.stringify([a.admission.coordinationKey,o.id,o.path,o.repoRoot,o.ownerKind,o.ownerId,o.branch,o.snapshotRef,o.removedAt,n,i.sandbox,i.acceleration,i.knownMutation]);const c=e.get(s);let l;if(c)try{l=await timeWorktreePreparationPhase(`workspaceWait`,()=>racePromiseWithAbortSignal(c.result,i.signal))}catch(a){assertCurrent();if(c.signal?.aborted&&(a===c.signal.reason||a instanceof OpenClawStateLeaseError&&a.code===`OPENCLAW_STATE_LEASE_ABORTED`&&a.cause===c.signal.reason))return joinLocalWorkspaceOperation(e,t,n,r,i);throw a}else{const forget=()=>{if(e.get(s)?.result===t)e.delete(s)};const t=r(forget).finally(forget);e.set(s,{result:t,signal:i.signal});l=await t}assertCurrent();return l}function checkpointLocalWorkspace(e,t={}){return joinLocalWorkspaceOperation(pendingCheckpoints,e,[e.agentId,e.sessionKey,e.sessionId,e.lifecycleRevision],n=>withLocalWorkspaceStore({...e,worktreeId:e.worktree.id},async r=>{n();let i=false;if(!t.knownMutation&&await probeUnchangedLocalWorkspace(e,r,[`canonical`],(e,t)=>{i=e>=2e4||t>=500})){await removeLocalWorkspaceCheckpointCapture(r.get().projection_path,{signal:r.signal,commitGuard:r.assertCurrent});return}await runLocalWorkspaceProjection(e,r,(e,t,n)=>e.synchronize(`canonical`,{captureRejected:true,capture:n,afterCapture:t&&(()=>timeWorktreePreparationPhase(`runtimeResume`,t.resume))}),{reason:`checkpoint`,snapshotCapture:i})}),t)}async function withSettledLocalWorkspace(e,t){return await settleLocalWorkspace(e,t)}async function settleLocalWorkspace(e,t){const n=captureWorktreeRunEndContext(e.env??process.env);const r={...e.env??process.env,...n.environment};const i=[];if(e.retireRuntime){const t=await executeExistingOpenClawStateRead({path:n.admission.databasePath,env:r},{type:`localWorkspace.get`,input:{id:e.worktree.id}},{context:n,current:true,live:true});n.admission.assertCurrent();e.assertCurrent?.();if(t&&(!t.ok||t.type!==`localWorkspace.get`))throw new Error(`Unexpected local workspace retirement lookup`);if(t?.row){if(e.sessionOwner){const i={...e.sessionOwner,lifecycleRevision:t.row.lifecycle_revision,worktree:e.worktree,env:r,assertCurrent:e.assertCurrent??(()=>{}),workerAuthority:e.workerAuthority};const a=await localWorkspaceProjectionPath(i);n.admission.assertCurrent();e.assertCurrent?.();e.workerAuthority?.assertCurrent?.();assertLocalWorkspaceProjectionOwner(t.row,i,a)}const{readRegistry:a}=await import(`./registry-C-LjTrAy.mjs`);const{prepareSandboxPersistentExecRetirement:o}=await import(`./persistent-exec-retirement-RFf0sDMQ.mjs`);for(const s of(await a({path:n.admission.databasePath,env:r})).entries)if(s.workspaceDir===t.row.projection_path)i.push(await o({containerName:s.containerName,env:r,assertCurrent:()=>{n.admission.assertCurrent();e.assertCurrent?.();e.workerAuthority?.assertCurrent?.()}}))}}return await withLocalWorkspaceStore({...e,env:r,worktreeId:e.worktree.id},async a=>{a.assertCurrent();const o=a.get();if(!o)return await t({worktreeId:e.worktree.id,assertCurrent:a.assertCurrent,workerAuthority:a.workerAuthority});const s=e.worktree;const c={...e.workerAuthority,assertCurrent:e.workerAuthority?e.workerAuthority.assertCurrent:e.assertCurrent,predicates:[...e.workerAuthority?.predicates??[],{kind:`projection`,id:s.id,ownerId:o.session_key,path:s.path,repoRoot:s.repoRoot}]};const l=await prepareWorktreeRegistryGuard(n,c);const u={worktree:s,env:r,agentId:e.sessionOwner?.agentId??o.agent_id,sessionKey:e.sessionOwner?.sessionKey??o.session_key,sessionId:e.sessionOwner?.sessionId??o.session_id,lifecycleRevision:e.sessionOwner?e.sessionOwner.lifecycleRevision:o.lifecycle_revision,workerAuthority:c,assertCurrent:()=>{if(e.assertCurrent!==c.assertCurrent)e.assertCurrent?.();l()}};return await runLocalWorkspaceProjection(u,a,async(n,r)=>{if(e.finishRestore)await n.finishRestore();else if(e.restoreSnapshot)await n.restoreSnapshot();else if(n.current().baseline_ref){await n.synchronize(`canonical`);if(e.retireRuntime)await n.synchronize(`projection`)}if(e.retireRuntime){for(const e of i)await e.finish();await r?.retire()}const o=n.current();return await t(o.baseline_ref?{worktreeId:s.id,projectionPath:o.projection_path,projectionRevision:o.revision,prepareArchive:n.prepareArchive,canonicalPaths:n.canonicalPaths,synchronizeProjection:()=>n.synchronize(`projection`),assertCurrent:n.current,workerAuthority:n.workerAuthority}:{worktreeId:s.id,projectionRevision:o.revision,assertCurrent:a.assertCurrent,workerAuthority:a.workerAuthority})},{reason:e.retireRuntime?`retirement`:e.restoreSnapshot||e.finishRestore?`restore`:`publication`})})}async function withSettledLocalWorkspacePath(e,t){const n=captureWorktreeRunEndContext(process.env);const r={...process.env,...n.environment};const i=await readLiveRegistryWorktreeByPath(n,e.cwd);e.assertCurrent?.();return i?await withSettledLocalWorkspace({worktree:i,env:r,assertCurrent:e.assertCurrent},t):await t()}function reuseLocalWorkspaceProjection(e,t,n){return withLocalWorkspaceStore({...e,worktreeId:e.worktree.id,signal:t},async t=>{try{var r=_usingCtx();const i=r.u(observeDiagnosticsTimelinePhases(`attempt.setup.sandbox.workspace_selection.reuse.reconcile`));let a=startWorktreePreparationPhase(`reuse.operation`);const markPhase=e=>{a();a=startWorktreePreparationPhase(`reuse.${e}`)};try{if(t.get()?.baseline_ref)n?.();return await probeUnchangedLocalWorkspace(e,t,[`canonical`,`projection`],void 0,e=>markPhase(e===`canonical`?`probeCanonical`:`probeProjection`))??await runLocalWorkspaceProjection(e,t,e=>e.reuse(),{reason:`preparation`,onPhase:markPhase})}finally{a();i.mark(`attempt.setup.sandbox.workspace_selection.reuse.release`)}}catch(e){r.e=e}finally{r.d()}})}async function probeUnchangedLocalWorkspace(e,t,n,r,i){let a=t.get();if(!a?.baseline_ref||!a.tree_root_digest||a.session_id!==e.sessionId||a.lifecycle_revision!==e.lifecycleRevision||a.pending_ref||a.journal_json||a.paused_runtimes_json)return;projectionOperations(e,t,a,await localWorkspaceProjectionPath(e)).current();for(const o of n){i?.(o);const n=a;const s=performance.now();const c=await timeWorktreePreparationPhase(o===`canonical`?`synchronizeCanonical`:`synchronizeProjection`,async()=>{try{return await t.manifest(n,{kind:`probe`,target:o,canonicalRoot:e.worktree.path})}catch{t.signal.throwIfAborted();t.assertCurrent();return}});r?.(c?.kind===`rescan`?c.entryCount??0:0,performance.now()-s);t.assertCurrent();if(c?.kind!==`scan`||c.resultingRoot!==c.previousRoot)return;if(c.observation)a=await t.accept(c.observation,e.workerAuthority)}return a.projection_path}async function withLocalWorkspaceProjection(e,t,n={}){return await withLocalWorkspaceStore({...e,worktreeId:e.worktree.id,signal:n.signal},r=>runLocalWorkspaceProjection(e,r,t,n))}async function expireLocalWorkspaceProjection(e){const t=captureWorktreeRunEndContext(e.env);const n={...e.env,...t.environment};return await withLocalWorkspaceStore({...e,env:n,worktreeId:e.worktree.id},async r=>{r.assertCurrent();const i=r.get();if(!i){await e.retireSnapshot?.(r.assertCurrent);return}if(e.worktree.removedAt===void 0)throw new Error(`Cannot expire a live sandbox workspace`);const a=captureWorktreeRegistryReadGuard(t,`lifecycle`,e.worktree);const o=await readRegistryWorktree(t,e.worktree.id);const s=a(o);e.assertCurrent();if(o?.removedAt!==e.worktree.removedAt||o?.ownerId!==i.session_key)throw new Error(`Workspace retention owner changed`);const c={worktree:e.worktree,env:n,agentId:i.agent_id,sessionKey:i.session_key,sessionId:i.session_id,lifecycleRevision:i.lifecycle_revision,workerAuthority:e.workerAuthority,assertCurrent:()=>{if(e.workerAuthority?.assertCurrent!==e.assertCurrent)e.workerAuthority?.assertCurrent?.();e.assertCurrent();s()}};await runLocalWorkspaceProjection(c,r,t=>t.expire(e.retireSnapshot))})}async function resolveLocalWorkspaceOwner(e){const t=captureWorktreeRunEndContext(e.env??process.env);const n={...e.env??process.env,...t.environment};const r={agentId:e.agentId,sessionKey:e.sessionKey,storePath:e.storePath??resolveSessionStorePathCore(e.cfg.session?.store,{agentId:e.agentId,env:n}),env:n};const i=new DisposableStack;let a;let unregister=()=>{};i.defer(()=>{a?.release();unregister()});const release=()=>i.dispose();const assertActive=()=>{e.assertCurrent?.();if(i.disposed)throw new Error(`Local sandbox workspace authority changed`)};const o=captureSessionEntryMetadataRead(r,assertActive);try{let i;const s=o?o.readCurrent():await withSessionEntryReadOnlyInWorker(r,assertActive,async e=>{if(!e.ok)throw e.error;const t=e.value;if(i&&t)a=retainPreparedSessionEntryPredicate({databaseIdentity:i,sessionKey:r.sessionKey,entry:t,matches:(e,t)=>t!==void 0&&e?.sessionId===t.sessionId&&e?.lifecycleRevision===t.lifecycleRevision&&t.archivedAt===void 0&&e?.worktree?.id===t.worktree?.id});return t},(e,t)=>{i=t.key;unregister=registerOpenClawAgentDatabaseAsyncResource({agentId:e.agentId,path:e.path,revoke:release,close:async()=>release()})});if(!s?.worktree?.id){release();return}const c={id:s.worktree.id,ownerKind:`session`};const l=captureWorktreeRegistryReadGuard(t,`lifecycle`,c);const u=await readRegistryWorktree(t,s.worktree.id);const d=l(u);if(!u||u.removedAt!==void 0||u.ownerKind!==`session`||u.ownerId!==e.sessionKey||u.repoRoot!==s.worktree.repoRoot||u.branch!==s.worktree.branch||e.workspaceDir&&!isPathInside(u.path,e.workspaceDir))throw new Error(`Local sandbox managed workspace owner changed`);const assertSessionCurrent=()=>{if(!o){assertActive();if(!a?.isCurrent())throw new Error(`Local sandbox workspace authority changed`);return}const e=o.readCurrent();if(e?.sessionId!==s.sessionId||e?.lifecycleRevision!==s.lifecycleRevision||e?.archivedAt!==void 0||e?.worktree?.id!==u.id)throw new Error(`Local sandbox workspace authority changed`)};const assertCurrent=()=>{assertSessionCurrent();d()};assertCurrent();const f={agentId:e.agentId,sessionKey:e.sessionKey,sessionId:s.sessionId,lifecycleRevision:s.lifecycleRevision??null,worktree:u,assertCurrent,workerAuthority:{stateOwnerPath:e.stateOwnerPath,assertCurrent:assertSessionCurrent,predicates:[{kind:`live-binding`,record:u}]},env:n,[Symbol.dispose]:release};if(s.localWorkspaceHandoff){const e=s.localWorkspaceHandoff;await finishLocalWorkspaceHandoff(f,e);await patchSessionEntryCore(r,t=>{assertCurrent();if(t?.sessionId!==f.sessionId||t.lifecycleRevision!==s.lifecycleRevision||JSON.stringify(t.localWorkspaceHandoff)!==JSON.stringify(e))throw new Error(`Local workspace handoff changed before completion`);return{localWorkspaceHandoff:void 0}})}return f}catch(e){release();throw e}}export{withLocalWorkspacePreparation as a,withSettledLocalWorkspacePath as c,reuseLocalWorkspaceProjection as i,expireLocalWorkspaceProjection as n,withLocalWorkspaceProjection as o,resolveLocalWorkspaceOwner as r,withSettledLocalWorkspace as s,checkpointLocalWorkspace as t};