UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 12 kB
import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{r as hasSqliteWorkerOutcomeUnknown}from"./sqlite-worker-error-DHUQ0e2U.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{n as OpenClawStateLeaseError,r as createOpenClawStateLeaseAbortError}from"./openclaw-state-lease-error-DCUL0v5x.mjs";import"./sqlite-worker-contract-CcRGAuae.mjs";import{i as observeSqliteWorkerCommittedFacts}from"./sqlite-worker-operation-admission-BZvXBQev.mjs";import{i as runOpenClawStateWorkerOperation}from"./openclaw-state-worker-store-7se2aIrr.mjs";import{i as withOpenClawStateLeasesWorkerAdmission}from"./openclaw-state-lease-worker-owner-B0DbaTgn.mjs";import{n as withOpenClawStateLeaseAsync}from"./openclaw-state-lease-B5EAG_56.mjs";import{t as runGitWorkerOperation}from"./git-worker-CBvkg-PR.mjs";import{a as startWorktreePreparationPhase}from"./preparation-timing-CC2_vlen.mjs";import{d as withWorktreeRunEnd,i as captureWorktreeRunEndContext,l as retainWorktreeRunEndFailure}from"./run-end-lifecycle-mk2iX8J8.mjs";import{t as createKeyedFifoLeaseRegistry}from"./keyed-fifo-lease-VAvONh60.mjs";import{i as prepareLocalWorkspaceSourcePathSet,n as localWorkspaceDigestBytes}from"./local-workspace-cas-BX5-hDAy.mjs";import{r as readLocalWorkspaceCommit,t as localWorkspaceFingerprintPatch}from"./local-workspace-publication-ZhCVw1P8.mjs";import{createHash,randomUUID}from"node:crypto";import{serialize}from"node:v8";import{AsyncLocalStorage}from"node:async_hooks";import{promisify}from"node:util";import{constants,deflateRawSync,zstdCompress}from"node:zlib"; //!src/gateway/worker-environments/local-workspace-lease.ts const waitMs=6e4;const queue=createKeyedFifoLeaseRegistry(Symbol.for(`openclaw.localWorkspaceLeaseQueue`));const current=new AsyncLocalStorage;async function withLocalWorkspaceLease(e,t,n){const r=JSON.stringify([t.admission.coordinationKey,e.worktreeId]);const i=current.getStore()??[];if(i.some(e=>e.active&&e.key===r))throw new OpenClawStateLeaseError(`Local sandbox operation already holds workspace.local-reconciliation/${e.worktreeId}; release execution custody before checkpointing this workspace`,{code:`OPENCLAW_STATE_LEASE_INVALID_INPUT`});const a=new AbortController;const o=e.signal?AbortSignal.any([e.signal,a.signal]):a.signal;const s=setTimeout(()=>{a.abort(new OpenClawStateLeaseError(`Timed out after ${waitMs} ms waiting for local sandbox workspace workspace.local-reconciliation/${e.worktreeId}; retry the tool call after the current checkpoint or reconciliation finishes`,{code:`OPENCLAW_STATE_LEASE_HELD`}))},waitMs);s.unref?.();const c=queue.reserve([r]);const l={key:r,active:true};try{await racePromiseWithAbortSignal(c.wait(),o,e=>createOpenClawStateLeaseAbortError(e,`acquisition`,`local sandbox workspace`));o.throwIfAborted();return await withOpenClawStateLeaseAsync({scope:`workspace.local-reconciliation`,key:e.worktreeId,leaseMs:6e4,waitMs,signal:o,leaseLabel:`local sandbox workspace`,operationLabel:`workspace.local-reconciliation`},t,e=>{clearTimeout(s);return current.run([...i,l],()=>n(e))})}catch(e){if(a.signal.aborted&&!hasSqliteWorkerOutcomeUnknown(e))throw a.signal.reason;throw e}finally{clearTimeout(s);l.active=false;c.release()}} //!src/gateway/worker-environments/local-workspace-store.ts const compressMutation=promisify(zstdCompress);const log=createSubsystemLogger(`agents/worktrees`);const reconciliationContext=new AsyncLocalStorage;const shortDigest=e=>createHash(`sha256`).update(e).digest(`hex`).slice(0,16);async function withLocalWorkspaceReconciliation(e,t){const n={workspace:shortDigest(e.worktreeId),plan:shortDigest(e.pendingRef),attempt:randomUUID(),baseCommit:e.baseCommit?.slice(0,12)??`-`,targetCommit:e.targetCommit?.slice(0,12)??`-`,target:e.target,reason:e.reason};return reconciliationContext.run(n,async()=>{const e=JSON.stringify(n);const r=performance.now();let i=false;let a=`aborted`;log.info(`Local workspace reconcile start: correlation=${e}`);try{const e=await t(()=>i=true);a=e.conflictPaths.length?`conflict`:i?`applied`:`replayed`;return e}finally{log.info(`Local workspace reconcile finish: correlation=${e} outcome=${a} durationMs=${(performance.now()-r).toFixed(1)}`)}})}async function hasLocalWorkspaceProjection(e,t){return(await executeExistingOpenClawStateRead({env:t},{type:`localWorkspace.exists`,input:{id:e}},{current:true,live:true}))?.exists??false}function withLocalWorkspaceStore(e,t){const n=e.env??process.env;const r=captureWorktreeRunEndContext(n);const i=e.workerAuthority?.leaseSet;const a=i?.mutationWorktreeIds?.slice();const o=i?.context??r;if(o.admission.coordinationKey!==r.admission.coordinationKey)throw new Error(`Local workspace lease belongs to another database`);return withWorktreeRunEnd(n,()=>{const n=startWorktreePreparationPhase(`workspaceWait`);return withLocalWorkspaceLease({worktreeId:e.worktreeId,signal:e.signal},o,s=>{n();const c=[...i?.leases??[],s];return withOpenClawStateLeasesWorkerAdmission(c,o,async n=>{let i=true;let l;const u=e.workerAuthority?e.workerAuthority.assertCurrent:e.assertCurrent;const assertCustody=()=>{r.admission.assertCurrent();n.assertCurrent();if(!i)throw new Error(`Local workspace custody has ended`)};const assertHost=()=>{assertCustody();u?.()};const assertCurrent=()=>{assertHost();if(e.assertCurrent!==u)e.assertCurrent?.()};try{return await runOpenClawStateWorkerOperation(o,async()=>{const n=await executeExistingOpenClawStateRead({path:o.admission.databasePath,env:o.environment},{type:e.requireAbsent?`localWorkspace.exists`:`localWorkspace.get`,input:{id:e.worktreeId}},{context:o,current:true,live:true});assertCurrent();if(n?.type===`localWorkspace.exists`&&n.exists)throw new Error(`Snapshot retains local workspace projection custody; preserve its recovery data`);l=n?.type===`localWorkspace.get`&&n.row?Object.freeze(n.row):void 0;const pruneLegacy=async()=>{if(!l?.tree_root_digest)return;let t;do{assertCurrent();t=await runOpenClawStateWorkerOperation(o,t=>t.execute({type:`localWorkspace.pruneLegacy`,input:{id:e.worktreeId}}),{assertCurrent})}while(t)};await pruneLegacy();let r;const prepare=async e=>{for(const t of e){assertCurrent();const e=await runOpenClawStateWorkerOperation(o,e=>e.execute({type:`localWorkspace.prepare`,input:{preparation:t}}),{assertCurrent});r=Math.min(r??e,e)}assertCurrent()};const mutate=async(t,n=e.workerAuthority??{},a,s)=>{assertCurrent();if(t.kind===`update`&&t.manifest){const{previousRoot:e,resultingRoot:n,treeRoot:r,fingerprints:i,fingerprintsFromCheckpoint:a}=t.manifest;t.manifest={previousRoot:e,resultingRoot:n,treeRoot:r,fingerprints:i,fingerprintsFromCheckpoint:a,records:[],removed:[]}}let d=a??t;const f=t.kind===`create`?t.row:t.kind===`update`?t.patch:void 0;if(!a&&typeof f?.source_paths_json===`string`){const e=prepareLocalWorkspaceSourcePathSet(f.source_paths_json);await prepare([deflateRawSync(serialize({paths:e}))]);f.source_paths_digest=localWorkspaceDigestBytes(e.digest);if(t.kind===`create`)d={...t,row:{...t.row,source_paths_json:`[]`}};else if(t.kind===`update`)d={...t,patch:{...t.patch,source_paths_json:`[]`}}}if(!(d instanceof Uint8Array)&&d.kind===`update`&&d.manifest?.fingerprintsFromCheckpoint)d={...d,manifest:{...d.manifest,fingerprints:void 0}};if(s&&!(d instanceof Uint8Array)&&d.kind===`update`)d={...d,patch:{...d.patch,journal_pack:void 0}};let p={mutation:t.kind===`update`&&t.manifest?.fingerprints?{...t,patch:{...t.patch,...localWorkspaceFingerprintPatch(t.manifest.fingerprints)}}:t,previous:l};const m=structuredClone(n.predicates);let h=a?.byteLength??0;if(!a){const e=serialize(d);h=e.byteLength;const t=e.byteLength>1048576?await compressMutation(e,{params:{[constants.ZSTD_c_compressionLevel]:1}}):void 0;if(t&&t.byteLength<e.byteLength)d=t}const g={serializedBytes:h+(s?.byteLength??0),wireBytes:(d instanceof Uint8Array?d.byteLength:h)+(s?.byteLength??0),correlation:reconciliationContext.getStore()??{workspace:shortDigest(e.worktreeId),plan:l?.pending_ref?shortDigest(l.pending_ref):`-`,baseCommit:l?.base_commit.slice(0,12)??`-`}};let _;let v;const assertWrite=()=>{if(n.assertCurrent!==assertHost)assertHost();if(n.assertCurrent!==u)n.assertCurrent?.()};try{const t=await withOpenClawStateLeasesWorkerAdmission(c,o,t=>runOpenClawStateWorkerOperation(o,i=>i.execute({type:`localWorkspace.mutate`,input:{id:e.worktreeId,mutation:d,diagnostic:g,preparationEpoch:r,predicates:m,workspaceEvidence:n.workspaceEvidence,stateOwnerPath:n.stateOwnerPath,leases:t.identities}},s?{transferredInput:{journalPack:s}}:void 0),{assertCurrent:assertWrite,createAdmission(n){v=n.settled;const r=t.createAdmission(n);_=r.admission;observeSqliteWorkerCommittedFacts(_,({facts:t})=>{(o.assertPublicationCurrent??o.admission.assertCurrent)();if(t!==void 0)readLocalWorkspaceCommit(t,e.worktreeId,p.mutation,p.previous)});return r}}),{assertCurrent:assertWrite});l=readLocalWorkspaceCommit(t,e.worktreeId,p.mutation,p.previous);if(!p.previous?.tree_root_digest)await pruneLegacy()}catch(t){if((await v)?.kind===`completed`&&_?.committed)try{l=readLocalWorkspaceCommit(_.committed.facts,e.worktreeId,p.mutation,p.previous)}catch(e){i=false;retainWorktreeRunEndFailure(e);throw e}else{i=false;retainWorktreeRunEndFailure(t);throw t}}finally{p=void 0;d=void 0}};const readManifest=async(t,n)=>{assertCurrent();if(t.worktree_id!==e.worktreeId)throw new Error(`Local workspace binding changed`);const r=await runGitWorkerOperation({type:`workspace.manifest.local`,input:{owner:JSON.stringify([o.admission.coordinationKey,e.worktreeId])}},{signal:s.signal,assertCurrent,readWorkspaceManifest:async(r,{signal:i})=>{const a=await executeExistingOpenClawStateRead({path:o.admission.databasePath,env:o.environment},{type:`localWorkspace.manifest`,input:{id:e.worktreeId,revision:t.revision,action:n,knownTreeRoot:r}},{context:o,current:true,live:true,signal:i});assertCurrent();if(!a)throw new Error(`Local workspace manifest is unavailable`);return a.snapshot}});assertCurrent();if(r.kind===`scan`){await prepare(r.preparations??[]);const{preparations:e,...t}=r;return t}if(r.kind===`replace`){await prepare(r.update.preparations??[]);r.update.preparations=void 0}return r};const accept=async(e,t)=>{await prepare(e.preparations??[]);await mutate({kind:`update`,revision:e.revision,patch:e.patch,rejectedResult:e.rejectedResult},t,e.mutation);return l};return await t({signal:s.signal,assertCurrent,workerAuthority:{...e.workerAuthority,leaseSet:{context:o,leases:c,mutationWorktreeIds:a},assertCurrent:assertHost},get:()=>{assertCustody();return l},manifest:readManifest,accept,reject:async(t,n,r)=>{if(t.worktree_id!==e.worktreeId||!t.pending_ref||t.journal_json)throw new Error(`Local workspace rejection requires an unapplied pending result`);await mutate({kind:`update`,revision:t.revision,patch:{},rejectedResult:{ref:t.pending_ref,...n}},r);return l},create:async(e,t)=>{await mutate({kind:`create`,row:e},t);return l},update:async(t,n,r,i,a)=>{if(t.worktree_id!==e.worktreeId)throw new Error(`Local workspace binding changed`);if(i&&`rawManifest`in i){const e=await readManifest(t,{kind:`replace`,...i,patch:n});if(e.kind!==`replace`)throw new Error(`Local workspace baseline preparation is missing`);await accept(e.update,r)}else if(i&&!i.treeRoot){const e=await readManifest(t,{kind:`prepare`,manifest:i,patch:n});if(e.kind!==`replace`)throw new Error(`Local workspace checkpoint preparation is missing`);await accept(e.update,r)}else await mutate({kind:`update`,revision:t.revision,patch:n,manifest:i},r,void 0,a);return l},delete:async(t,n)=>{if(t.worktree_id!==e.worktreeId)throw new Error(`Local workspace binding changed`);await mutate({kind:`delete`,revision:t.revision},n)}})},{assertCurrent:assertHost})}finally{i=false;l=void 0}})}).finally(n)})}export{withLocalWorkspaceReconciliation as n,withLocalWorkspaceStore as r,hasLocalWorkspaceProjection as t};