openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 10.1 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.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 dockerPersistentExecContainerName}from"./persistent-exec.types-Dc8ypvlf.mjs";import{i as execContainer,t as DOCKER_SANDBOX_ENGINE}from"./container-engine-BMQJ1AeL.mjs";import{a as dockerPersistentTargetToEngineTarget,i as dockerPersistentTargetFromEngineTarget,n as bindDockerPersistentTarget}from"./docker-persistent-target-DiNlKD3t.mjs";import"./docker-BopkXkYW.mjs";import{n as bindPodmanSandboxEngine,s as validateSandboxContainerEngineTarget}from"./podman-runtime-BY_VxWG0.mjs";import{_ as assertSandboxRegistryRetirementCurrent,a as readBrowserRegistry,n as assertSandboxRegistryEntryCurrent,s as readRegistry,t as assertSandboxBrowserRegistryEntryCurrent}from"./registry-DlBtCoQb.mjs";import{t as BROWSER_BRIDGES}from"./browser-bridges-Dxep1bbK.mjs";import{t as createSandboxPersistentExecStore}from"./persistent-exec-store-DfHBjyNX.mjs";import{createHash}from"node:crypto";
//!src/agents/sandbox/local-workspace-quiescence.ts
const log=createSubsystemLogger(`sandbox/quiescence`);const pauseCounts={checkpoint:0,preparation:0,reconcile:0,publication:0,retirement:0,restore:0};async function readLocalWorkspaceRuntimes(e,t={}){const n=createSandboxPersistentExecStore(t);const r={path:n.databasePath,env:n.environment,assertCurrent:n.assertCurrent};const[i,a,o]=await Promise.all([readRegistry({...r,workspaceDir:e}),readBrowserRegistry({...r,workspaceDir:e}),n.list()]);return[...i.entries.map(e=>({kind:`container`,entry:e,database:r,assertCurrent:()=>assertSandboxRegistryRetirementCurrent(`container`,e,r)})),...a.entries.map(e=>({kind:`browser`,entry:e,database:r,assertCurrent:()=>assertSandboxRegistryRetirementCurrent(`browser`,e,r)})),...o.flatMap(t=>{const r=t.receipt;if(t.workspaceBinding.workspaceDir!==e||!r)return[];return[{kind:`persistent`,record:t,receipt:r,assertCurrent:()=>n.assertCustodyCurrent(t),assertRetired:async()=>{if((await n.list({ownerKey:t.ownerKey})).length)throw new Error(`Settle persistent streams before retiring their workspace.`)}}]})]}async function prepareLocalWorkspaceFileRead(e){const t=(await readLocalWorkspaceRuntimes(e.runtimeWorkspaceDir??e.workspaceDir)).filter(e=>e.kind!==`persistent`);const assertCurrent=()=>{e.assertCurrent();for(const e of t)if(e.kind===`container`)assertSandboxRegistryEntryCurrent(e.entry);else assertSandboxBrowserRegistryEntryCurrent(e.entry)};assertCurrent();if(!t.length)throw new Error(`Sandbox file backing is unavailable`);const{sandboxContainerShowsWorkspacePaths:n}=await import(`./mount-plan-BcUNnKoh.mjs`);for(const r of t){const{engine:t,backendTarget:i,containerName:a}=localWorkspaceRuntimeEngine(r);await validateSandboxContainerEngineTarget(t,i);assertCurrent();if(!await n({...e,engine:t,containerName:a,assertCurrent}))throw new Error(`Sandbox file backing is unavailable`)}assertCurrent();return assertCurrent}function localWorkspaceRuntimeEngine(e){const t=e.kind===`persistent`?dockerPersistentExecContainerName(e.record.attemptId):e.entry.containerName;const n=e.kind===`persistent`?e.receipt.containerId:void 0;const r=e.kind===`container`?e.entry.backendId:`docker`;const i=e.kind===`persistent`?dockerPersistentTargetToEngineTarget(e.record.backendTarget):e.kind===`container`?e.entry.backendTarget:void 0;if(r!==`docker`&&r!==`podman`)throw new Error(`Local workspace backend cannot fence host projection writes`);if(r===`podman`&&!i)throw new Error(`Local workspace Podman engine owner is missing`);return{engine:r===`podman`?bindPodmanSandboxEngine(i):i?bindDockerPersistentTarget(dockerPersistentTargetFromEngineTarget(i)):DOCKER_SANDBOX_ENGINE,backendTarget:i,containerName:t,expectedId:n}}function parseLocalWorkspacePausedRuntimes(e){if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t)||t.length>128)throw new Error(`Invalid local workspace runtime custody`);return t.map(e=>{if(!isRecord(e)||typeof e.name!==`string`||!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/u.test(e.name)||typeof e.id!==`string`||!/^[a-f0-9]{64}$/u.test(e.id))throw new Error(`Invalid local workspace runtime custody`);return{name:e.name,id:e.id}})}async function quiesceLocalWorkspace(e){try{var t=_usingCtx();const n=t.u(observeDiagnosticsTimelinePhases(`attempt.setup.sandbox.workspace_selection.quiesce.registry`));const r=createHash(`sha256`).update(e.workspaceDir).digest(`hex`).slice(0,16);const i=(await readLocalWorkspaceRuntimes(e.workspaceDir,{env:e.env})).map(e=>({runtime:e,bridges:e.kind===`browser`?[...BROWSER_BRIDGES].filter(([,t])=>t.containerName===e.entry.containerName):[]}));e.assertCurrent();let a=[...e.retained];let o=false;const s=/* @__PURE__ */ new Set;const markPhase=e=>{for(const t of s)t(e)};const c=[];const l=[];const u=[];for(const{runtime:t,bridges:r}of i){if(t.kind===`persistent`&&t.record.phase===`stopped`)continue;const i=localWorkspaceRuntimeEngine(t);const{engine:o,backendTarget:s,containerName:c,expectedId:d}=i;const captureRetirement=n=>{if(t.kind===`persistent`)return;l.push(async()=>{const{removeSandboxRuntimeGeneration:i}=await import(`./manage-BwXHqlXq.mjs`);await i({runtime:t,database:t.database,engine:o,id:n,bridges:r,assertCurrent:e.assertCurrent,assertGenerationCurrent:t.assertCurrent})})};n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.engine_target`);await validateSandboxContainerEngineTarget(o,s);e.assertCurrent();n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.authority`);await t.assertCurrent();n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.inspect`);const f=await execContainer(o,[`inspect`,`-f`,`{{.Id}} {{.State.Running}} {{.State.Paused}}`,d??c],{allowFailure:true,signal:AbortSignal.timeout(3e4)});e.assertCurrent();if(f.code!==0){if(/no such (?:container|object)|does not exist/iu.test(f.stderr)){n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.authority`);await t.assertCurrent();captureRetirement(null);continue}throw new Error(`Local workspace runtime could not be inspected; workspace preserved`)}const[p,m,h]=f.stdout.trim().split(/\s+/u);if(!p||!/^[a-f0-9]{64}$/u.test(p)||d!==void 0&&p!==d||![`true`,`false`].includes(m??``)||![`true`,`false`].includes(h??``))throw new Error(`Invalid local workspace runtime inspection`);n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.authority`);await t.assertCurrent();captureRetirement(p);if(m!==`true`&&h!==`true`)continue;const g=a.some(e=>e.name===c&&e.id===p);if(h===`true`&&!g)throw new Error(`Local workspace runtime was paused by another owner; resume it before retrying`);if(!g){a.push({name:c,id:p});n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.persist`);await e.persist(a)}u.push({runtime:t,target:i,id:p,isPaused:h===`true`,observedAt:performance.now()})}for(const{runtime:t,target:i,id:o,isPaused:l,observedAt:d}of u){const{engine:u,backendTarget:f,containerName:p}=i;const m=e.reason??`reconcile`;let h=d;let g=`pause`;let _=h;const v={};const observePhase=e=>{const t=performance.now();v[g]=(v[g]??0)+t-_;g=e;_=t};if(!l){e.assertCurrent();n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.authority`);await t.assertCurrent();n.mark(`attempt.setup.sandbox.workspace_selection.quiesce.pause`);_=h=performance.now();await execContainer(u,[`pause`,o],{signal:AbortSignal.timeout(3e4)});log.info(`Local workspace pause: reason=${m} scope=${r} count=${++pauseCounts[m]}`,{engine:u.id,runtime:t.kind})}s.add(observePhase);c.push(async()=>{try{var n=_usingCtx();const i=n.u(observeDiagnosticsTimelinePhases(`attempt.setup.sandbox.workspace_selection.resume.engine_target`));if(u.id===`docker`)await validateSandboxContainerEngineTarget(u,f);e.assertCurrent();i.mark(`attempt.setup.sandbox.workspace_selection.resume.inspect`);observePhase(`resumeInspect`);const c=await execContainer(u,[`inspect`,`-f`,`{{.State.Paused}}`,o],{allowFailure:true,signal:AbortSignal.timeout(3e4)});e.assertCurrent();let d=`already-running`;if(c.code!==0){if(!/no such (?:container|object)|does not exist/iu.test(c.stderr))throw new Error(`Local workspace runtime resume inspection failed; exact paused owner retained`);d=`removed`}else if(c.stdout.trim()===`true`){i.mark(`attempt.setup.sandbox.workspace_selection.resume.authority`);observePhase(`resumeAuthority`);await t.assertCurrent();i.mark(`attempt.setup.sandbox.workspace_selection.resume.unpause`);observePhase(`unpause`);const e=await execContainer(u,[`unpause`,o],{allowFailure:true,signal:AbortSignal.timeout(3e4)});if(e.code!==0&&!/no such (?:container|object)|does not exist/iu.test(e.stderr))throw new Error(`Local workspace runtime resume failed; exact paused owner retained`);d=e.code===0?`resumed`:`removed`}else if(c.stdout.trim()!==`false`)throw new Error(`Invalid local workspace runtime resume inspection`);if(s.delete(observePhase)){observePhase(`resume`);let e=`pause`;let n=0;const i={};for(const[t,r]of Object.entries(v)){if(r>n){e=t;n=r}if(r>=1e3)i[t]=Math.round(r)}log.info(`Local workspace unpause: reason=${m} scope=${r} durationMs=${Math.round(performance.now()-h)} dominantPhase=${e} dominantPhaseMs=${Math.round(n)} phaseDurationsMs=${JSON.stringify(i)} durationScope=${l?`observed`:`owner`} outcome=${d}`,{engine:u.id,runtime:t.kind})}e.assertCurrent();a=a.filter(e=>e.name!==p||e.id!==o);i.mark(`attempt.setup.sandbox.workspace_selection.resume.persist`);await e.persist(a)}catch(e){n.e=e}finally{n.d()}})}markPhase(`operation`);return{markPhase,get retired(){return o},retire:async()=>{e.assertCurrent();for(const{runtime:e}of i)if(e.kind===`persistent`)await e.assertRetired();e.assertCurrent();for(const e of l)await e();e.assertCurrent();if(a.length){await e.persist([]);a=[]}o=true},resume:async()=>{if(o||!a.length)return;markPhase(`resume`);e.assertCurrent();for(const e of c.toReversed())await e();e.assertCurrent();if(a.length){await e.persist([]);a=[]}}}}catch(e){t.e=e}finally{t.d()}}export{parseLocalWorkspacePausedRuntimes,prepareLocalWorkspaceFileRead,quiesceLocalWorkspace,readLocalWorkspaceRuntimes};