openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 9.42 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{x as root}from"./fs-safe-Bxzu1j4h.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 sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{c as hasWorktreeUnknownOutcome}from"./errors-DSG3YKoH.mjs";import{u as prepareSessionSourceEffect}from"./session-source-authority-Cun3s-rH.mjs";import{d as runGit,o as requireGit}from"./git-2P0YMMKQ.mjs";import{d as WORKTREE_SETUP_HEADROOM_BYTES}from"./allocation-70UOBpud.mjs";import{o as timeWorktreePreparationPhase}from"./preparation-timing-CC2_vlen.mjs";import{t as withWorktreeGitConfig}from"./checkout-git-config-DsLh_M7l.mjs";import{i as prepareWorktreeTemplate,t as detectWorktreeFilesystemBackend}from"./filesystem-backend-DzmVomB3.mjs";import{n as prepareWorktreeFilesystemMutation}from"./filesystem-native-BvDS5nVZ.mjs";import{c as readTemplateManifest,o as prepareTemplateManifest}from"./template-registry-async-rWZR1Hkj.mjs";import{n as captureTemplateWorkspaceManifest}from"./workspace-manifest-worker-C4V2H1Gh.mjs";import{a as WORKSPACE_PATH_EXCLUSIONS_JS,s as buildCacheInputPaths}from"./workspace-path-exclusions-Cmi1311P.mjs";import{n as resolveSandboxDependencyTemplateIdentity,t as prepareSandboxDependencyTemplate}from"./dependency-template-CstecgPX.mjs";import{i as prepareLocalWorkspaceCheckout}from"./local-workspace-checkout-BneJgVKr.mjs";import path from"node:path";import{randomUUID}from"node:crypto";import fs from"node:fs/promises";import{parse as parse$1}from"yaml";
//!src/gateway/worker-environments/local-workspace-template.ts
const log=createSubsystemLogger(`agents/worktrees`);const TEMPLATE_PHASE=`attempt.setup.sandbox.workspace_selection.prepare.reconcile.template`;async function removeTemplatePath(e,t){try{var n=_usingCtx();const r=await prepareSessionSourceEffect(t.commitGuard);n.a({[Symbol.asyncDispose]:async()=>await r.release?.()});await prepareWorktreeFilesystemMutation(t,r);t.signal?.throwIfAborted();r.assertCurrent();await fs.rm(e,{recursive:true,force:true})}catch(e){n.e=e}finally{await n.d()}}async function hasContainedVirtualStore(e,t){try{const{buffer:n}=await(await root(e)).read(`node_modules/.modules.yaml`,{symlinks:`reject`,maxBytes:1048576});const r=parse$1(n.toString(`utf8`));if(!isRecord(r)||typeof r.virtualStoreDir!==`string`)return false;const i=path.posix.resolve(t,`node_modules`);const a=path.posix.relative(i,path.posix.resolve(i,r.virtualStoreDir));return a!==`..`&&!a.startsWith(`../`)&&!path.posix.isAbsolute(a)}catch{return false}}async function validateTemplate(e,t,n,r){return await withWorktreeGitConfig(e,true,{signal:n.signal,beforeRun:n.commitGuard,stateOwnerPath:n.workerAuthority?.stateOwnerPath},async i=>{const a=await i.run(e,[`--no-optional-locks`,`status`,`--porcelain=v2`,`--branch`,`-z`,`--untracked-files=normal`,`--ignored=matching`],{signal:n.signal,beforeRun:n.commitGuard,stateOwnerPath:n.workerAuthority?.stateOwnerPath,killProcessTree:true});const o=a.stdout.split(`\0`);if(a.code!==0||a.termination!==`exit`||a.stdoutTruncatedBytes||o.pop()!==``)return false;const s=o.filter(e=>e.startsWith(`# branch.oid `));if(s.length!==1||s[0]!==`# branch.oid ${t}`)return false;for(const t of o){if(t.startsWith(`# `))continue;if(!t.startsWith(`! `)&&!t.startsWith(`? `))return false;const i=t.slice(2);const a=i.replace(/\/$/u,``).split(`/`);if(a.some(e=>!e||e===`.`||e===`..`)||path.isAbsolute(i))return false;const o=path.join(e,...a);const s=a.indexOf(`node_modules`);if(s!==-1&&r!==`source-only`){if(!(await fs.lstat(path.join(e,...a.slice(0,s+1)))).isDirectory())return false;continue}await removeTemplatePath(o,n)}return true})}function sandboxTemplateCacheKey(e,t,n){return sha256Hex(`sandbox-v1\n${e}\n${t}\n${n}`)}async function prepareLocalWorkspaceTemplate(e){const{guard:t}=e;const n=e.buildCacheInputs&&[...buildCacheInputPaths(e.buildCacheInputs)].toSorted();const r=sha256Hex(JSON.stringify([`template-manifest-v1`,WORKSPACE_PATH_EXCLUSIONS_JS,n]));let i;let a;let o;const prepareManifest=async(e,t)=>{if(!n)return;i=await prepareTemplateManifest(e,r,async()=>{const i=a&&o&&!o.some(e=>path.posix.basename(e)===`.gitattributes`)&&await readTemplateManifest(a,r);return await timeWorktreePreparationPhase(`snapshot`,()=>captureTemplateWorkspaceManifest({root:e.path,baseCommit:e.sourceCommit,buildCacheInputs:n,previous:i&&o?{...i,changedPaths:o}:void 0},t.signal))},t.signal);t.commitGuard()};const s=await detectWorktreeFilesystemBackend(e.temporaryRoot,t);if(!s)return;const c={signal:t.signal,beforeRun:t.commitGuard,stateOwnerPath:t.workerAuthority?.stateOwnerPath,killProcessTree:true};const l=await runGit(e.source,[`show`,`${e.baseCommit}:pnpm-lock.yaml`],c);if(l.code!==0||l.stdoutTruncatedBytes){log.debug(`sandbox dependency template skipped: no complete pnpm lockfile at the selected commit`);return}const u=e.identity??await resolveSandboxDependencyTemplateIdentity(e.sandbox,{signal:t.signal,assertCurrent:t.commitGuard});if(!u){log.debug(`sandbox dependency template skipped: local image identity unavailable`);return}const d=path.resolve(e.source,await requireGit(e.source,[`rev-parse`,`--git-common-dir`],c));const prepareSource=async(n,r,i)=>{await t.requireDiskSpace([{path:e.templateRoot,bytes:WORKTREE_SETUP_HEADROOM_BYTES}],`sandbox dependency template`);if(!i)await s.createTemplate(n,r);await timeWorktreePreparationPhase(`checkout`,()=>prepareLocalWorkspaceCheckout({source:e.source,destination:n,temporaryRoot:e.temporaryRoot,baseCommit:e.baseCommit,retainedCommit:i,branch:`openclaw-template`,signal:r.signal,assertCurrent:r.commitGuard,workerAuthority:r.workerAuthority}))};const prepare=async(n,r,i)=>{try{var a=_usingCtx();const o=a.u(observeDiagnosticsTimelinePhases(`${TEMPLATE_PHASE}.build`));const s={...t,...r,signal:r.signal??t.signal};await prepareSource(n,s,i);const c=await prepareSandboxDependencyTemplate({directory:n,cfg:e.sandbox,scopeKey:randomUUID(),identity:u,signal:s.signal,assertCurrent:s.commitGuard,rollbackGuard:r.rollbackGuard});o.mark(`${TEMPLATE_PHASE}.validate`);const l=c.installed&&await hasContainedVirtualStore(n,u.docker.workdir);s.commitGuard();const d=await timeWorktreePreparationPhase(`templateValidateOutput`,()=>validateTemplate(n,e.baseCommit,s,l?`dependencies`:`source-only`));if(l&&d){log.info(`sandbox dependency template prepared for the selected commit`);return}const f=c.installed?l?`installation changed tracked source`:`pnpm virtual store is outside node_modules or unavailable`:c.reason;log.warn(`sandbox dependency template using source-only fallback: ${f}`);if(d)return;o.mark(`${TEMPLATE_PHASE}.rebuild`);await removeTemplatePath(n,s);await prepareSource(n,s)}catch(e){a.e=e}finally{a.d()}};const f=await prepareWorktreeTemplate({env:e.env,now:Date.now,backgroundUsedAt:e.backgroundUsedAt,options:t,cacheKey:sandboxTemplateCacheKey(d,e.templateRoot,u.key),contentKey:sha256Hex(`${e.baseCommit}\n${sha256Hex(l.stdout)}\n${u.key}`),repoRoot:e.repoRoot,commonDir:d,worktreeRoot:e.templateRoot,sourceCommit:e.baseCommit,backend:`sandbox-${s.id}`,requireSpace:()=>t.requireDiskSpace([{path:e.templateRoot,bytes:WORKTREE_SETUP_HEADROOM_BYTES}],`sandbox dependency template`),refresh:async(t,n,r)=>{a=t;const i=await withWorktreeGitConfig(e.source,true,{...c,signal:r.signal,beforeRun:r.commitGuard},n=>n.run(e.source,[`diff-tree`,`--no-commit-id`,`-r`,`--no-renames`,`--name-only`,`-z`,t.sourceCommit,e.baseCommit,`--`],{signal:r.signal,killProcessTree:true}));o=i.code===0&&i.termination===`exit`&&!i.stdoutTruncatedBytes?i.stdout.split(`\0`).filter(Boolean):void 0;if(!o||o.some(e=>e===`pnpm-lock.yaml`||path.posix.basename(e)===`.gitattributes`))return false;await timeWorktreePreparationPhase(`templateClone`,()=>s.cloneTemplate(t.path,n.path,r));await prepare(n.path,r,t.sourceCommit);await prepareManifest(n,r);return true},prepare:async(e,t)=>{await prepare(e.path,t);await prepareManifest(e,t)}});if(!f)return;try{if(!i)await prepareManifest(f,t);return{record:f,backend:s,manifest:i}}catch(e){await f.release(e);throw e}}async function cloneLocalWorkspaceTemplate(e){try{var t=_usingCtx();const n=t.u(observeDiagnosticsTimelinePhases(`${TEMPLATE_PHASE}.select`));const r=await timeWorktreePreparationPhase(`templatePrepare`,()=>prepareLocalWorkspaceTemplate({...e,buildCacheInputs:e.buildCacheInputs??[]}));if(!r)return false;const{record:i,backend:a}=r;const{guard:o}=e;let s;try{n.mark(`${TEMPLATE_PHASE}.clone`);o.commitGuard();await o.requireDiskSpace([{path:e.destination,bytes:a.id===`btrfs`?a.estimateCloneBytes(0,0):WORKTREE_SETUP_HEADROOM_BYTES}],`sandbox workspace clone`);try{await timeWorktreePreparationPhase(`templateApply`,()=>a.cloneTemplate(i.path,e.destination,o))}catch(t){if(hasWorktreeUnknownOutcome(t))throw t;await removeTemplatePath(e.destination,o);log.warn(`sandbox dependency snapshot unavailable; using source-only checkout`);return false}await requireGit(e.destination,[`branch`,`-m`,e.branch],{signal:o.signal,beforeRun:o.commitGuard,stateOwnerPath:o.workerAuthority?.stateOwnerPath,killProcessTree:true});return r.manifest}catch(e){s=e;throw e}finally{n.mark(`${TEMPLATE_PHASE}.release`);await i.release(s)}}catch(e){t.e=e}finally{t.d()}}export{cloneLocalWorkspaceTemplate,prepareLocalWorkspaceTemplate,sandboxTemplateCacheKey};