openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
482 lines • 149 kB
JavaScript
#!/usr/bin/env node
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{i as stripAnsi,n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{Et as _enum,Fn as object,Jn as string,Nt as array,Pn as number,nr as tuple,qn as strictObject,xn as literal}from"./schemas-DuCQi-Qb.mjs";import{u as redactSupportString}from"./diagnostic-support-redaction-fdb2R4EP.mjs";import{t as findCrabboxBinary}from"./crabbox-binary-Bo1EgOsf.mjs";import{r as ensureManagedCrabboxBinary}from"./cli-runtime-api-BLjuJItw.mjs";import{n as resolvePathEnvKey,r as resolveWindowsCmdExePath}from"./windows-cmd-helpers-Dn0Jw1lq.mjs";import{a as ManagedCleanupCancelled,n as hasUnjoinedWork,o as claimManagedCleanup,r as loadManagedChildSpawner,s as failManagedCleanup,t as finalizeManagedChild}from"./managed-child-process-K69elLFz.mjs";import{a as preserveCrabboxArtifacts,i as captureClaimNamespace,n as createStaging,o as captureSourceWitness,t as createMirrorStaging}from"./crabbox-staging-DsqIbtof.mjs";import{accessSync,chmodSync,closeSync,constants,copyFileSync,existsSync,fstatSync,lstatSync,mkdirSync,mkdtempSync,openSync,readFileSync,readSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,rmdirSync,statSync,statfsSync,symlinkSync,utimesSync,writeFileSync}from"node:fs";import{fileURLToPath}from"node:url";import{delimiter,dirname,extname,isAbsolute,join,relative,resolve,sep}from"node:path";import{createHash}from"node:crypto";import{homedir,tmpdir}from"node:os";import{execFileSync,spawnSync}from"node:child_process";import{copyFileDescriptorSync}from"@openclaw/fs-safe/advanced";import{sha256FileSync}from"@openclaw/fs-safe/durability";import{FsSafeError}from"@openclaw/fs-safe/errors";import{isUtf8}from"node:buffer";import{setImmediate}from"node:timers/promises";import{StringDecoder}from"node:string_decoder";import{addAbortSignal}from"node:stream";import{buffer}from"node:stream/consumers";import{DatabaseSync}from"node:sqlite";
//!scripts/crabbox-routing-policy.mts
const workloadAliases=/* @__PURE__ */ new Map([[`check`,`ci-fast`],[`ci`,`ci-fast`],[`ci-fast`,`ci-fast`],[`ci-proof`,`ci-proof`],[`desktop`,`desktop`],[`interactive`,`interactive`],[`release`,`release-proof`],[`release-proof`,`release-proof`],[`untrusted`,`untrusted`],[`windows`,`windows`]]);function normalizeCrabboxWorkload(e){const t=typeof e===`string`?e.trim().toLowerCase():``;if(!t)return``;return workloadAliases.get(t)??null}function crabboxProviderChain({workload:e,configuredProvider:t,target:n,advertisedProviders:r}){const i=new Set(r);const a=t.trim();const o=n.trim().toLowerCase();if(o===`macos`)return available([`aws`],i);if(o===`windows`||e===`windows`)return available([`azure`,`aws`],i);const s=[`azure`,`aws`];switch(e){case`ci-fast`:case`ci-proof`:case`release-proof`:return available([`ascii-box`,`daytona`,...s],i);case`interactive`:return available([`daytona`,...s],i);case`desktop`:return available(s,i);case`untrusted`:return available(s,i);default:return available([a],i)}}function available(e,t){return e.filter(e=>e&&t.has(e))}
//!scripts/crabbox-source-mirror.mts
const fileSchema=strictObject({path:string(),source:string(),stamp:string(),mode:_enum([`100644`,`100755`,`120000`]),blob:string().regex(/^[0-9a-f]{40}$/u)});const metadataSchema=strictObject({version:literal(1),gitVersion:string(),witness:string(),tracked:string(),inventory:array(tuple([string(),string()]))});function mirrorStatStamp(e){return[e.isSymbolicLink()?`link`:e.isFile()?`file`:e.isDirectory()?`dir`:`other`,e.dev,e.ino,e.mode,e.size,e.mtimeMs,e.ctimeMs].join(`:`)}function mirrorArtifact(e){return[`.crabbox/runs`,`.crabbox/captures`].some(t=>e===t||e.startsWith(t+`/`))}function recordMirrorEntry(e,t,n){if(mirrorArtifact(t))return;if(t===`.git/index`){if(!n.isFile()||n.nlink!==1)throw new Error(`source mirror index is not a private regular file`);e.set(t,`mutable-index`)}else if(n.isDirectory()){if(t!==`.crabbox`)e.set(t,`dir:${n.dev}:${n.ino}:${n.mode}`)}else if(n.isFile()||n.isSymbolicLink())e.set(t,mirrorStatStamp(n));else throw new Error(`source mirror contains an unsupported file kind`)}function payloadInventory(e){const t=/* @__PURE__ */ new Map;let n=0;function walk(r){for(const i of readdirSync(join(e,r))){const a=r?`${r}/${i}`:i;if(mirrorArtifact(a))continue;const o=lstatSync(join(e,a));recordMirrorEntry(t,a,o);if(o.isDirectory())walk(a);else if(a.startsWith(`.git/objects/`))n+=o.size}}walk(``);return{entries:t,objectBytes:n}}function openSourceMirror(e,t,n,r){const i=join(e,`mirror.sqlite`);if(n){const e=lstatSync(i);if(!e.isFile()||e.nlink!==1)throw new Error(`source mirror metadata is not a private regular database`)}const a=new DatabaseSync(i);const o=getNodeSqliteKysely(a);const s=/* @__PURE__ */ new Map;let c;try{if(n){const e=executeSqliteQuerySync(a,o.selectFrom(`metadata`).selectAll()).rows;if(e.length!==1||e[0]?.id!==1)throw new Error(`source mirror metadata is incomplete`);c=metadataSchema.parse(JSON.parse(e[0].value));if(c.gitVersion!==r.gitVersion||c.witness!==r.witness||!r.witness)throw new Error(`source mirror Git version or witness changed`);const{entries:n,objectBytes:i}=payloadInventory(t);if(i>268435456)throw new Error(`source mirror private Git objects reached the rebuild budget`);const l=new Map(c.inventory);if(l.size!==c.inventory.length||l.size!==n.size||[...l].some(([e,t])=>n.get(e)!==t))throw new Error(`source mirror payload changed outside its owner`);for(const e of executeSqliteQuerySync(a,o.selectFrom(`files`).selectAll()).rows){const t=fileSchema.parse(e);if(l.get(t.path)!==t.stamp||s.has(t.path))throw new Error(`source mirror file metadata does not match its payload`);s.set(t.path,t)}}else a.exec(`
PRAGMA journal_mode = DELETE;
CREATE TABLE files (
path TEXT PRIMARY KEY, source TEXT NOT NULL, stamp TEXT NOT NULL,
mode TEXT NOT NULL, blob TEXT NOT NULL
);
CREATE TABLE metadata (id INTEGER PRIMARY KEY CHECK (id = 1), value TEXT NOT NULL);
`)}catch(e){a.close();throw e}let l=false;const close=()=>{if(!l){a.close();l=true}};return{files:s,tracked:c?.tracked,close,save(e,t,n){for(const[t,r]of e)if(n.get(t)!==r.stamp)throw new Error(`source mirror changed while freezing ${JSON.stringify(t)}; source was not uploaded`);const i={version:1,...r,tracked:t,inventory:[...n]};a.exec(`BEGIN IMMEDIATE`);try{for(const t of s.keys())if(!e.has(t))executeSqliteQuerySync(a,o.deleteFrom(`files`).where(`path`,`=`,t));const t=[...e.values()].filter(e=>JSON.stringify(e)!==JSON.stringify(s.get(e.path)));for(let e=0;e<t.length;e+=256)executeSqliteQuerySync(a,o.insertInto(`files`).values(t.slice(e,e+256)).onConflict(e=>e.column(`path`).doUpdateSet(e=>({source:e.ref(`excluded.source`),stamp:e.ref(`excluded.stamp`),mode:e.ref(`excluded.mode`),blob:e.ref(`excluded.blob`)}))));executeSqliteQuerySync(a,o.insertInto(`metadata`).values({id:1,value:JSON.stringify(i)}).onConflict(e=>e.column(`id`).doUpdateSet({value:JSON.stringify(i)})));a.exec(`COMMIT`)}catch(e){a.exec(`ROLLBACK`);throw e}finally{close()}}}}
//!scripts/crabbox-source-capsule.mts
const bundleFile=`.openclaw-crabbox-changed-gate.bundle`;const capsuleRef=`refs/openclaw/source-capsule`;const syncPlanSchema=object({candidate:object({files:number().int().nonnegative()}),topFiles:array(object({path:string().min(1)}))});function sourceGitEnvironment(){const e={...process.env,GIT_OPTIONAL_LOCKS:`0`};for(const t of[`GIT_DIR`,`GIT_WORK_TREE`,`GIT_INDEX_FILE`,`GIT_OBJECT_DIRECTORY`,`GIT_ALTERNATE_OBJECT_DIRECTORIES`,`GIT_COMMON_DIR`,`GIT_SHALLOW_FILE`])delete e[t];return e}function capsulePath(e){if(e.split(`/`).some(e=>!e||e===`.`||e===`..`||e.toLowerCase()===`.git`))throw new Error(`source capsule contains an invalid repository path`);if(e.includes(`\0`)||e.includes(`\\`)||e===bundleFile)throw new Error(`source capsule path conflicts with its transport metadata`);return e}function capsuleObjectId(e){const t=e.trim();if(!/^[a-f0-9]{40}$/u.test(t))throw new Error(`source capsule requires a complete SHA-1 Git object identity`);return t}function sourceStat(e,t){const n=t.split(`/`);let r=e;for(const e of n.slice(0,-1)){r=join(r,e);const t=lstatSync(r,{throwIfNoEntry:false});if(!t)return{kind:`missing`};if(!t.isDirectory()||t.isSymbolicLink())return{kind:`replaced`}}const i=lstatSync(join(e,t),{throwIfNoEntry:false});return i?{kind:`present`,stat:i}:{kind:`missing`}}function hasUnverifiedGitPreparation(e,t,n){if(t.GIT_CONFIG||t.GIT_EXTERNAL_DIFF)return true;const probe=n=>spawnSync(`git`,[`-C`,e,`config`,...n],{env:t,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3,killSignal:`SIGKILL`,maxBuffer:65536});const r=probe([`--null`,`--name-only`,`--get-regexp`,`^(core\\.(fsmonitor|hookspath)|filter\\..*\\.(clean|smudge|process)|diff\\.(external|.*\\.(command|textconv)))$`]);if(!r.error&&r.status===1)return false;if(r.error||r.status!==0||!isUtf8(r.stdout))return true;const i=r.stdout.toString(`utf8`).toLowerCase().split(`\0`).filter(Boolean);if(!i.length||i.some(e=>e!==`core.fsmonitor`&&e!==`core.hookspath`&&!e.startsWith(`filter.`)))return true;if(i.some(e=>/^filter\.(unset|unspecified)\./u.test(e)))return true;if(i.includes(`core.hookspath`)){const e=probe([`--null`,`--get`,`core.hooksPath`]);if(e.error||e.status!==0||!e.stdout.equals(Buffer.from(`/dev/null\0`)))return true}if(i.includes(`core.fsmonitor`)){const e=probe([`--null`,`--get`,`core.fsmonitor`]);const t=!e.error&&e.status===0&&e.stdout.equals(Buffer.from(`false\0`))?void 0:probe([`--type=bool`,`--get`,`core.fsmonitor`]);if(t&&(t.error||t.status!==0||t.stdout.toString(`utf8`).trim()!==`false`))return true}if(!i.some(e=>e.startsWith(`filter.`)))return false;const a=[...n];const o=spawnSync(`git`,[`-C`,e,`check-attr`,`-z`,`--stdin`,`filter`],{env:t,input:a.length?a.join(`\0`)+`\0`:``,stdio:[`pipe`,`pipe`,`pipe`],timeout:5e3,killSignal:`SIGKILL`,maxBuffer:67108864});if(o.error||o.status!==0||!isUtf8(o.stdout))return true;const s=o.stdout.toString(`utf8`).split(`\0`);if(s.pop()!==``||s.length!==a.length*3)return true;return a.some((e,t)=>s[t*3]!==e||s[t*3+1]!==`filter`||![`unspecified`,`unset`].includes(s[t*3+2]))}function prepareCrabboxSourceCapsule(e){const t=Date.now();const n=realpathSync(e.repoRoot);const r=sourceGitEnvironment();function git(t,i,a=r,o){let s;try{s=execFileSync(`git`,[`-C`,t,...e.reuseMirror&&t===n?[`-c`,`core.fsmonitor=false`]:[],...i],{env:a,input:o,maxBuffer:67108864,stdio:[`pipe`,`pipe`,`pipe`]})}catch{throw new Error(`source capsule: git ${i[0]} failed; source was not uploaded`)}if(!isUtf8(s))throw new Error(`source capsule requires UTF-8 Git paths and metadata`);return s.toString(`utf8`)}const i=capsuleObjectId(git(n,[`rev-parse`,`--verify`,`HEAD^{commit}`]));const a=capsuleObjectId(git(n,[`rev-parse`,`--verify`,`${e.base}^{commit}`]));const o=git(n,[`ls-files`,`-v`,`--stage`,`-z`]);const s=/* @__PURE__ */ new Map;for(const e of o.split(`\0`).filter(Boolean)){const t=/^([A-Za-z]) (100644|100755|120000) ([a-f0-9]{40}) 0\t([\s\S]+)$/u.exec(e);if(!t||!t[1]||!t[2]||!t[3]||!t[4])throw new Error(`source capsule requires resolved regular-file or symlink index entries`);s.set(capsulePath(t[4]),{mode:t[2],hash:t[3],sparse:t[1].toUpperCase()===`S`})}const c=new Set(s.keys());for(const e of/* @__PURE__ */ new Set([a,i]))for(const t of git(n,[`ls-tree`,`-r`,`--name-only`,`-z`,e]).split(`\0`).filter(Boolean))c.add(capsulePath(t));const l=git(n,[`ls-files`,`--cached`,`--others`,`--exclude-standard`,`-z`]).split(`\0`).filter(Boolean);const u=new Set(l.map(capsulePath));const d=/* @__PURE__ */ new Map;mkdirSync(e.syncRoot,{recursive:true});const f=captureSourceWitness(n,i);function allocateMirror(){const t=createMirrorStaging(e.syncRoot,n);if(t&&!t.staging.recorded){t.discard();throw new Error(`source mirror requires recorded staging; source was not uploaded`)}return t}let p=e.reuseMirror&&f?allocateMirror():void 0;let m;try{if(p){const e={gitVersion:git(n,[`--version`]).trim(),witness:f?JSON.stringify({gitDir:f.gitDir,ref:f.ref}):``};try{m=openSourceMirror(p.staging.root,join(p.staging.payload,`source`),p.reused,e)}catch(t){if(!p.reused)throw t;console.error(`[crabbox] source mirror failed verification; rebuilding a cold capsule`);p.discard();p=allocateMirror();if(p)m=openSourceMirror(p.staging.root,join(p.staging.payload,`source`),false,e)}}}catch(e){p?.discard();throw e}const h=p?.staging??createStaging(e.syncRoot,n);const g=h.payload;const _=join(g,`source`);let v=false;const cleanup=()=>{m?.close();if(p){if(v)p.finish();else p.discard()}else h.dispose()};try{const l=p?.reused??false;mkdirSync(_,{recursive:true});const y={...r,GIT_CONFIG_GLOBAL:`/dev/null`,GIT_CONFIG_NOSYSTEM:`1`,GIT_CONFIG_COUNT:`0`,GIT_AUTHOR_NAME:`OpenClaw`,GIT_AUTHOR_EMAIL:`ci@openclaw.local`,GIT_COMMITTER_NAME:`OpenClaw`,GIT_COMMITTER_EMAIL:`ci@openclaw.local`};delete y.GIT_CONFIG_PARAMETERS;delete y.GIT_CONFIG;if(!l)git(_,[`init`,`--quiet`,`--template=`],y);if(p){git(_,[`config`,`core.hooksPath`,`/dev/null`],y);git(_,[`config`,`core.fsmonitor`,`false`],y)}const ee=git(n,[`rev-parse`,`--path-format=absolute`,`--git-path`,`objects`]).trim();writeFileSync(join(_,`.git`,`objects`,`info`,`alternates`),`${ee}\n`);git(_,[`update-ref`,`--no-deref`,`HEAD`,i],y);git(_,[`update-ref`,`refs/heads/main`,a],y);const b=spawnSync(`git`,[`-C`,n,`config`,`--path`,`--null`,`--get`,`core.excludesFile`],{env:r});if(b.status===0&&isUtf8(b.stdout)){const e=b.stdout.toString(`utf8`).slice(0,-1);git(_,[`config`,`core.excludesFile`,e?resolve(n,e):``],y)}else if(b.status!==1)throw new Error(`source capsule could not resolve Git exclusion policy`);else if(l)git(_,[`config`,`core.excludesFile`,``],y);git(_,[`remote`,l?`set-url`:`add`,`origin`,git(n,[`remote`,`get-url`,`origin`]).trim()],y);if(l){rmSync(join(_,`.git`,`index`));copyFileSync(join(_,`.git`,`mirror-selection-index`),join(_,`.git`,`index`))}const x=/* @__PURE__ */ new Map;for(const e of(m?.tracked??``).split(`\0`).filter(Boolean)){const t=e.indexOf(` `);x.set(e.slice(t+1),e.slice(2,t))}const S=[];const C=/* @__PURE__ */ new Set;for(const e of x.keys())if(!s.has(e))S.push(`0 ${`0`.repeat(40)}\t${e}\0`);for(const[e,t]of s)if(x.get(e)!==`${t.mode} ${t.hash} 0`){S.push(`${t.mode} ${t.hash}\t${e}\0`);C.add(e)}git(_,[`update-index`,`-z`,`--index-info`],y,S.join(``));const w=git(n,[`rev-parse`,`--path-format=absolute`,`--git-path`,`info/exclude`]).trim();if(lstatSync(w,{throwIfNoEntry:false})){const e=realpathSync(w);if(!lstatSync(e).isFile())throw new Error(`source capsule requires a regular Git info/exclude policy file`);mkdirSync(join(_,`.git`,`info`),{recursive:true});const t=openSync(e,constants.O_RDONLY|constants.O_NOFOLLOW);try{writeFileSync(join(_,`.git`,`info`,`exclude`),readFileSync(t))}finally{closeSync(t)}}else if(l)rmSync(join(_,`.git`,`info`,`exclude`),{force:true});const T=/* @__PURE__ */ new Map;const E=/* @__PURE__ */ new Set;function removeFrozen(e){rmSync(join(_,e));for(let t=dirname(e);t!==`.`;t=dirname(t))try{rmdirSync(join(_,t))}catch(e){if(e.code!==`ENOTEMPTY`)throw e;break}}for(const[e,t]of m?.files??[]){if(!u.has(e)){removeFrozen(e);continue}const r=sourceStat(n,e);const i=r.kind===`present`?mirrorStatStamp(r.stat):r.kind;d.set(e,i);const a=s.get(e);const o=i===`missing`&&a?.sparse?`sparse:${a.mode}:${a.hash}`:i;if(t.source!==o)removeFrozen(e);else E.add(e)}if(l)rmSync(join(_,bundleFile));let D=0;let O=0;const k=join(g,`links`);mkdirSync(k);function writeFailure(e,t,n){const r=n;const i=[r?.code===void 0?void 0:`code=${JSON.stringify(r.code)}`,r?.errno===void 0?void 0:`errno=${JSON.stringify(r.errno)}`].filter(Boolean).join(`, `);return new Error(`source capsule: ${t} failed for ${JSON.stringify(e)}${i?` (${i})`:``}; source was not uploaded`,{cause:n})}const A=/* @__PURE__ */ new Set;function mkdirFrozenParent(e){const t=dirname(e);if(!A.has(t)){mkdirSync(t,{recursive:true});A.add(t)}}function writeFrozen(e,t,n){const r=join(_,e);let i=r;let a=`mkdir`;try{mkdirFrozenParent(r);if(n===`120000`){a=`symlink`;symlinkSync(t,r);i=join(k,String(T.size));a=`write symlink blob`;writeFileSync(i,t)}else{a=`write file`;writeFileSync(r,t);a=`chmod`;chmodSync(r,n===`100755`?493:420)}}catch(t){throw writeFailure(e,a,t)}T.set(e,{mode:n,blobPath:i,stamp:m?mirrorStatStamp(lstatSync(r)):void 0});D+=1}function copySource(e){const t=m?.files.get(e);if(E.has(e)&&t){T.set(e,{mode:t.mode,blobPath:join(_,e),blob:t.blob,stamp:t.stamp});O+=1;return`present`}const r=sourceStat(n,e);const i=r.kind===`present`?mirrorStatStamp(r.stat):r.kind;d.set(e,i);if(r.kind!==`present`||r.stat.isDirectory())return r.kind;const a=r.stat;const o=join(n,e);if(a.isSymbolicLink()){writeFrozen(e,readlinkSync(o,{encoding:`buffer`}),`120000`);return`present`}if(!a.isFile())throw new Error(`source capsule has an unsupported file kind at ${JSON.stringify(e)}`);const s=join(_,e);const c=(a.mode&64)!==0?`100755`:`100644`;const l=openSync(o,constants.O_RDONLY|constants.O_NOFOLLOW);try{const t=fstatSync(l);if(!t.isFile()||t.dev!==a.dev||t.ino!==a.ino)throw new Error(`source capsule file identity changed: ${JSON.stringify(e)}`);let n=`mkdir`;let r;try{mkdirFrozenParent(s);n=`write file`;r=openSync(s,`wx`)}catch(t){throw writeFailure(e,n,t)}try{let n;try{n=copyFileDescriptorSync(l,r,{maxBytes:t.size})}catch(t){if(t instanceof FsSafeError&&t.code===`too-large`)throw new Error(`source changed while freezing ${JSON.stringify(e)}; retry after edits finish`,{cause:t});if(t?.syscall===`write`||t instanceof FsSafeError&&t.code===`helper-failed`)throw writeFailure(e,`write file`,t);throw t}if(n!==t.size)throw new Error(`source changed while freezing ${JSON.stringify(e)}; retry after edits finish`);try{chmodSync(s,c===`100755`?493:420)}catch(t){throw writeFailure(e,`chmod`,t)}}finally{closeSync(r)}}finally{closeSync(l)}T.set(e,{mode:c,blobPath:s,stamp:m?mirrorStatStamp(lstatSync(s)):void 0});D+=1;return`present`}const j=[];for(const e of[...u].toSorted()){const t=copySource(e);const n=s.get(e);if(t===`missing`&&n?.sparse)j.push({path:e,mode:n.mode,hash:n.hash})}if(j.length){const e=join(g,`sparse-blobs`);const t=openSync(e,`wx`,384);try{execFileSync(`git`,[`-C`,n,`cat-file`,`--batch`],{env:r,input:j.map(e=>e.hash).join(`
`)+`
`,stdio:[`pipe`,t,`pipe`]})}catch{throw new Error(`source capsule could not materialize missing sparse index blobs`)}finally{closeSync(t)}const i=openSync(e,`r`);let a=0;try{for(const e of j){const t=Buffer.alloc(128);const n=readSync(i,t,0,t.length,a);const r=t.indexOf(10,0);const o=t.subarray(0,r).toString(`ascii`);const s=/^([a-f0-9]{40}) blob (\d+)$/u.exec(o);if(r<0||r>=n||!s||s[1]!==e.hash||!s[2])throw new Error(`source capsule received invalid sparse blob framing`);const c=Number(s[2]);if(!Number.isSafeInteger(c))throw new Error(`source capsule sparse blob size is invalid`);a+=r+1;const l=Buffer.alloc(c);for(let e=0;e<c;){const t=readSync(i,l,e,c-e,a+e);if(!t)throw new Error(`source capsule sparse blob was truncated`);e+=t}a+=c;const u=Buffer.alloc(1);if(readSync(i,u,0,1,a)!==1||u[0]!==10)throw new Error(`source capsule sparse blob separator is missing`);a+=1;writeFrozen(e.path,l,e.mode)}if(a!==fstatSync(i).size)throw new Error(`source capsule sparse blob stream has unexpected data`)}finally{closeSync(i)}}const M={...r};const N=Object.fromEntries(Object.entries(r).filter(([e])=>{const t=e.toUpperCase();return!t.startsWith(`GIT_`)||t===`GIT_CEILING_DIRECTORIES`||t===`GIT_DISCOVERY_ACROSS_FILESYSTEM`}));let P=false;const holdPreparation=()=>{if(h.recorded&&!P){h.hold(`writers`);P=true}};const checkPreparation=e=>{if(h.recorded&&!P&&hasUnverifiedGitPreparation(_,e,/* @__PURE__ */ new Set([...c,...T.keys()])))holdPreparation()};const F=[];let I;const L=r.CRABBOX_CONFIG;if(L){const e=resolve(n,L);function repositoryPolicyPath(e){const t=relative(n,e);return t!==`..`&&!t.startsWith(`..${sep}`)&&!isAbsolute(t)?capsulePath(t):void 0}let t=repositoryPolicyPath(e);if(!t)try{t=repositoryPolicyPath(realpathSync(e))}catch{}if(t){F.push(t);I=join(_,t)}else I=e;M.CRABBOX_CONFIG=I}else F.push(`crabbox.yaml`,`.crabbox.yaml`);for(const e of[...F,`.crabboxignore`])if((T.has(e)?`present`:copySource(e))!==`missing`&&![`100644`,`100755`].includes(T.get(e)?.mode??``))throw new Error(`source capsule cannot relocate non-regular repository policy ${JSON.stringify(e)}; use a regular policy file before uploading`);checkPreparation(r);const te=new Set(git(_,[`ls-files`,`--cached`,`--others`,`--exclude-standard`,`-z`]).split(`\0`).filter(Boolean));for(const e of T.keys())if(u.has(e)&&!te.has(e))throw new Error(`source capsule Git exclusion context changed in the frozen checkout`);function selectSource(){checkPreparation(M);checkPreparation(N);let t;try{const n=spawnSync(e.syncPlan.command,e.syncPlan.args,{cwd:_,env:M,windowsVerbatimArguments:e.syncPlan.windowsVerbatimArguments,encoding:`utf8`,maxBuffer:67108864,stdio:[`ignore`,`pipe`,`pipe`]});if(n.error||n.status!==0)throw new Error(`Crabbox sync-plan failed`);t=JSON.parse(n.stdout)}catch{throw new Error(`source capsule requires a successful Crabbox sync-plan; inspect source exclusions before retrying`)}const n=syncPlanSchema.safeParse(t);if(!n.success)throw new Error(`source capsule received an invalid Crabbox sync-plan`);if(typeof t===`object`&&t!==null&&`localGitSeed`in t&&t.localGitSeed!=null)holdPreparation();const r=new Set(n.data.topFiles.map(e=>capsulePath(e.path)));if(r.size!==n.data.candidate.files||r.size!==n.data.topFiles.length)throw new Error(`source capsule requires the complete, unique Crabbox sync-plan selection`);return r}function refreshIndex(e){if(!e.length)return;const t=spawnSync(`git`,[`-C`,_,...l?[`add`,`--refresh`,`--pathspec-from-file=-`,`--pathspec-file-nul`]:[`update-index`,`--refresh`]],{env:{...y,GIT_LITERAL_PATHSPECS:`1`},input:l?e.join(`\0`)+`\0`:void 0,stdio:[`pipe`,`pipe`,`pipe`],maxBuffer:67108864});if(t.error||t.status!==0&&t.status!==1)throw new Error(`source capsule could not refresh its Git index`)}refreshIndex([...s.keys()].filter(e=>T.has(e)&&(!l||!E.has(e)||C.has(e))));if(m)copyFileSync(join(_,`.git`,`index`),join(_,`.git`,`mirror-selection-index`));const R=/* @__PURE__ */ new Set;for(const e of T.keys())for(let t=dirname(e);t!==`.`;t=dirname(t))R.add(t);const z=[/* @__PURE__ */ new Set];for(const e of[...c].toSorted()){if(T.has(e)||R.has(e))continue;const t=[];for(let n=dirname(e);n!==`.`;n=dirname(n))t.push(n);if(t.some(e=>T.has(e)))continue;let n=z.find(e=>t.every(t=>!e.has(t)));if(!n){n=/* @__PURE__ */ new Set;z.push(n)}n.add(e)}const ne=git(_,[`hash-object`,`-w`,`--stdin`],y,``).trim();const unstageDeletions=e=>git(_,[`update-index`,`-z`,`--index-info`],y,[...e].map(e=>`0 ${`0`.repeat(40)}\t${e}\0`).join(``));unstageDeletions(z.flatMap(e=>[...e]));const B=[];let V;for(const e of z){for(const t of e){mkdirSync(dirname(join(_,t)),{recursive:true});writeFileSync(join(_,t),``,{flag:`wx`})}git(_,[`update-index`,`-z`,`--index-info`],y,[...e].map(e=>`100644 ${ne}\t${e}\0`).join(``));const t=selectSource();for(const n of e){if(t.delete(n))B.push(n);removeFrozen(n)}unstageDeletions(e);if(V&&(V.size!==t.size||[...V].some(e=>!t.has(e))))throw new Error(`source capsule policy changed while selecting deletions`);V=t}if(!V)throw new Error(`source capsule selection is missing`);for(const e of s.keys())if(T.has(e)&&!V.has(e))throw new Error(`source capsule privacy selection excludes required tracked source ${JSON.stringify(e)}; resolve the conflict before uploading`);for(const e of V){if(T.has(e))continue;const t=e.split(`/`);if(!(s.has(e)&&t.some((e,n)=>n>0&&T.has(t.slice(0,n).join(`/`)))))throw new Error(`source capsule selection contains an absent source entry`)}const H=[...V].filter(e=>u.has(e)&&T.has(e)).toSorted();const U=new Set(H);for(const e of F)if(T.has(e)&&!U.has(e))throw new Error(`source capsule cannot retain excluded repository runtime configuration ${JSON.stringify(e)} for staged delegation`);for(const e of T.keys())if(!U.has(e))removeFrozen(e);const W=H.filter(e=>!T.get(e).blob);const G=git(_,[`hash-object`,`-w`,`--no-filters`,`--stdin-paths`],y,W.map(e=>JSON.stringify(T.get(e).blobPath)).join(`
`)+(W.length?`
`:``)).trim().split(`
`).filter(Boolean);if(G.length!==W.length||G.some(e=>!/^[a-f0-9]{40}$/u.test(e)))throw new Error(`source capsule could not freeze every raw blob`);for(const[e,t]of W.entries())T.get(t).blob=G[e];const re=H.map(e=>T.get(e).blob);if(l){rmSync(join(_,`.git`,`index`));copyFileSync(join(_,`.git`,`mirror-candidate-index`),join(_,`.git`,`index`))}else git(_,[`read-tree`,`--empty`],y);const K=[];for(const e of m?.files.keys()??[])if(!U.has(e))K.push(`0 ${`0`.repeat(40)}\t${e}\0`);for(const e of H){const t=T.get(e);const n=m?.files.get(e);if(!l||n?.mode!==t.mode||n.blob!==t.blob)K.push(`${t.mode} ${t.blob}\t${e}\0`)}if(l)K.unshift(`0 ${`0`.repeat(40)}\t${bundleFile}\0`);git(_,[`update-index`,`-z`,`--index-info`],y,K.join(``));const q=capsuleObjectId(git(_,[`write-tree`],y));const J=capsuleObjectId(git(_,[`commit-tree`,q,`-p`,a],y,JSON.stringify({deleted:B})+`
`));git(_,[`update-ref`,capsuleRef,J],y);const Y=join(g,`shallow`);writeFileSync(Y,`${a}\n`);const X=join(_,bundleFile);git(_,[`bundle`,`create`,X,`${a}..${capsuleRef}`],{...y,GIT_SHALLOW_FILE:Y});const Z=openSync(X,`r`);let Q;try{Q=sha256FileSync(Z).digest}finally{closeSync(Z)}git(_,[`update-index`,`--add`,`--cacheinfo`,`100644,${capsuleObjectId(git(_,[`hash-object`,`-w`,`--no-filters`,X],y))},${bundleFile}`],y);refreshIndex([...H.filter(e=>!l||!E.has(e)),bundleFile]);if(e.seedFromBase)git(_,[`update-ref`,`--no-deref`,`HEAD`,a],y);if(m)copyFileSync(join(_,`.git`,`index`),join(_,`.git`,`mirror-candidate-index`));rmSync(k,{recursive:true,force:true});rmSync(join(g,`sparse-blobs`),{force:true});rmSync(Y,{force:true});const $=m?/* @__PURE__ */ new Map:void 0;if(h.recorded){checkPreparation(r);checkPreparation(N);h.prepared({files:H.map((e,t)=>({path:e,mode:T.get(e).mode,blob:re[t]})),deleted:B},f,$?(e,t)=>{if(e.startsWith(`source/`))recordMirrorEntry($,e.slice(7),t)}:void 0)}if(m&&$){const e=/* @__PURE__ */ new Map;for(const t of H){const n=T.get(t);const r=s.get(t);const i=d.get(t);e.set(t,{path:t,source:i===`missing`&&r?.sparse?`sparse:${r.mode}:${r.hash}`:i,stamp:n.stamp,mode:n.mode,blob:n.blob})}m.save(e,o,$);console.error(`[crabbox] source mirror ${l?`warm`:`cold`}: copied ${D} files, reused ${O} files; preparation ${Date.now()-t}ms`)}v=true;return{sourceSha:i,baseSha:a,tree:q,carrier:J,digest:Q,bundlePath:X,directory:_,cleanup,staging:h,configPath:I}}catch(e){try{cleanup()}catch(t){throw new AggregateError([e,t],`source capsule cleanup failed; temporary checkout retained at ${g}: ${t instanceof Error?t.message:String(t)}`,{cause:t})}throw e}}
//!scripts/crabbox-source-receiver.mts
const receiver=String.raw`
const fs = require("node:fs");
const path = require("node:path");
const { createHash } = require("node:crypto");
const { isUtf8 } = require("node:buffer");
const { spawn, spawnSync } = require("node:child_process");
const { constants } = require("node:os");
const { getSystemErrorMap } = require("node:util");
const expected = JSON.parse(process.argv[1]);
const syncRoot = process.cwd();
const cwd = expected.payload === undefined && !expected.script ? process.argv[2] ?? syncRoot : syncRoot;
let temporary;
let nativeGit;
let publishedGit;
let child;
let signal;
let childSettlement;
let settled = true;
const preserveGit = typeof expected.payload === "string" || expected.script;
// SSH output can close before cleanup; retain this handler for queued errors.
if (preserveGit) process.stderr.on("error", error => {
if (error.code !== "EPIPE") throw error;
});
function forwardSignal(value) {
signal ??= value;
if (child?.pid) childSettlement ??= settleGroup(child.pid, value);
}
const signalHandlers = ["SIGINT", "SIGTERM", "SIGHUP"].map(value => [value, () => forwardSignal(value)]);
function groupAlive(pid) {
try { process.kill(-pid, 0); return true; } catch (error) {
return error.code === "ESRCH" ? false : null;
}
}
async function settleGroup(pid, firstSignal = "SIGTERM") {
if (groupAlive(pid) === false) return;
process.stderr.write("[crabbox] stopping background source work before Git restoration\n");
for (const value of [firstSignal, "SIGKILL"]) {
try { process.kill(-pid, value); } catch (error) {
if (error.code === "ESRCH") return;
}
const deadline = Date.now() + 1000;
while (Date.now() < deadline) {
if (groupAlive(pid) === false) return;
await new Promise(resolve => setTimeout(resolve, 25));
}
}
settled = false;
process.stderr.write("[crabbox] source child cleanup is unverified; temporary source and receiver retained\n");
// Keep the native workspace witness alive until absence is actually observed.
// The lease lifetime bounds this recovery hold; losing SSH does not prove closure.
await new Promise(resolve => {
const timer = setInterval(() => {
if (groupAlive(pid) === false) { clearInterval(timer); settled = true; resolve(); }
}, 100);
});
}
async function runChild(command, args, env, stdio = "inherit") {
if (signal) throw new Error("source payload interrupted before start");
return await new Promise((resolve, reject) => {
const running = spawn(command, args, { cwd, env, stdio, detached: true });
child = running;
childSettlement = null;
running.once("error", reject);
running.once("close", async (status, stoppedBy) => {
// The group can outlive its leader. Keep both our signal target and the
// native witness until every remaining writer has stopped.
if (running.pid) await (childSettlement ??= settleGroup(running.pid));
child = null;
resolve({ status, signal: stoppedBy });
});
});
}
async function receive() {
if (preserveGit) for (const [value, handler] of signalHandlers)
process.on(value, handler);
function fail(message) { throw new Error(message); }
function stat(file) {
try { return fs.lstatSync(file); } catch (error) {
if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
throw error;
}
}
function safePath(file) {
if (!file || file.includes("\\") || file.split("/").some(part =>
!part || part === "." || part === ".." || part.toLowerCase() === ".git")) fail("unsafe source path");
return file;
}
function hashFile(file, algorithm, blob = false) {
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
try {
const info = fs.fstatSync(fd);
if (!info.isFile()) fail("source entry is not a regular file");
const hash = createHash(algorithm);
if (blob) hash.update("blob " + info.size + "\0");
const buffer = Buffer.alloc(65536);
let size;
while ((size = fs.readSync(fd, buffer)) > 0) hash.update(buffer.subarray(0, size));
return hash.digest("hex");
} finally { fs.closeSync(fd); }
}
const gitFailureCause = Object.freeze({
noSpace: "no-space", permissionDenied: "permission-denied",
commandUnavailable: "command-unavailable", outputLimit: "output-limit",
terminated: "terminated", remoteRefMissing: "remote-ref-missing",
invalidObjectData: "invalid-object-data", dns: "dns", connection: "connection",
auth: "auth", unknown: "unknown",
});
function gitFailure(phase, result) {
const errors = getSystemErrorMap();
const rawCode = result.error?.code;
const code = [...errors.values()].some(([name]) => name === rawCode) ? rawCode : null;
const text = Buffer.isBuffer(result.stderr) ? result.stderr.toString("utf8").trim() : "";
const cause = code === "ENOSPC" ? gitFailureCause.noSpace
: code === "EACCES" || code === "EPERM" ? gitFailureCause.permissionDenied
: code === "ENOENT" ? gitFailureCause.commandUnavailable
: code === "ENOBUFS" ? gitFailureCause.outputLimit
: result.signal !== null ? gitFailureCause.terminated
: /^fatal: couldn't find remote ref [^\r\n]+$/u.test(text) ? gitFailureCause.remoteRefMissing
: /^fatal: (?:pack has bad object(?: at offset \d+)?|bad object [a-f0-9]+|index-pack failed|fetch-pack: invalid index-pack output)$/u.test(text) ? gitFailureCause.invalidObjectData
: /^fatal: unable to access '[^'\r\n]+': Could not resolve (?:host|proxy): [^\r\n]+$/u.test(text) ? gitFailureCause.dns
: /^fatal: unable to access '[^'\r\n]+': (?:Failed to connect to [^\r\n]+|Recv failure: Connection reset by peer)$/u.test(text) ? gitFailureCause.connection
: /^fatal: (?:Authentication failed for '[^'\r\n]+'|could not read Username for '[^'\r\n]+': [^\r\n]+)$/u.test(text) ? gitFailureCause.auth
: gitFailureCause.unknown;
return { phase, baseSha: /^[a-f0-9]{40}$/u.test(expected.baseSha) ? expected.baseSha : null,
status: result.status, signal: result.signal, spawnError: Boolean(result.error),
code, errno: errors.has(result.error?.errno) ? result.error.errno : null, cause };
}
try {
if (!preserveGit && process.argv[2] && (cwd === syncRoot || cwd.startsWith(syncRoot + path.sep) || syncRoot.startsWith(cwd + path.sep)))
fail("Testbox execution and sync workspaces overlap; stop this lease and warm a fresh one");
const capsule = path.join(syncRoot, ".openclaw-crabbox-changed-gate.bundle");
if (!stat(capsule)?.isFile() || hashFile(capsule, "sha256") !== expected.digest)
fail("missing or mismatched source capsule; rerun from the local candidate");
// Native cleanup owns only syncRoot. Source application and the payload share
// the prepared workspace, so ignored runtime never enters the native delete walk.
process.chdir(cwd);
temporary = fs.mkdtempSync(path.join(cwd, ".openclaw-source-"));
const bundle = path.join(temporary, "source.bundle");
fs.copyFileSync(capsule, bundle);
if (hashFile(bundle, "sha256") !== expected.digest) fail("source capsule changed during import");
const gitDir = path.join(temporary, "git");
const env = { ...process.env, GIT_DIR: gitDir, GIT_WORK_TREE: cwd,
GIT_INDEX_FILE: path.join(gitDir, "index"), GIT_OPTIONAL_LOCKS: "0" };
delete env.GIT_COMMON_DIR;
delete env.GIT_OBJECT_DIRECTORY;
delete env.GIT_ALTERNATE_OBJECT_DIRECTORIES;
delete env.GIT_SHALLOW_FILE;
function git(args, options = {}) {
const { encoding, phase = args[0], ...spawnOptions } = options;
const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", ...args],
{ cwd, env, maxBuffer: 64 * 1024 * 1024, ...spawnOptions });
if (result.status !== 0) fail("source Git operation failed: " + JSON.stringify(gitFailure(phase, result)));
if (encoding === "buffer") return result.stdout;
if (result.stdout === null) return "";
if (!isUtf8(result.stdout)) fail("unsupported non-UTF-8 Git metadata");
return result.stdout.toString("utf8");
}
git(["init", "-q"]);
git(["remote", "add", "origin", "https://github.com/openclaw/openclaw.git"]);
const preparedGit = path.join(cwd, ".git");
const preparedEnv = { ...env, GIT_DIR: preparedGit,
GIT_INDEX_FILE: path.join(preparedGit, "index") };
const reuseBase = stat(preparedGit)?.isDirectory() &&
git(["for-each-ref", "--format=%(objectname)", "refs/remotes/origin/main"], {
env: preparedEnv,
}).trim() === expected.baseSha;
// A promisor checkout can own the exact commit and tree while omitting blobs
// needed by later checkout and content-diff operations. Inspect the base and
// each immediate parent's tree without lazy fetching, matching fetch depth 2.
const preparedDepth = reuseBase ? git(["rev-list", "--parents", "--max-count=1",
expected.baseSha], {
env: { ...preparedEnv, GIT_NO_LAZY_FETCH: "1" }, phase: "base-inspect",
}).trim().split(" ") : [];
const preparedBaseComplete = reuseBase && preparedDepth.every(commit =>
!git(["rev-list", "--objects", "--missing=print", "--max-count=1", commit], {
env: { ...preparedEnv, GIT_NO_LAZY_FETCH: "1" }, phase: "base-inspect",
}).split("\n").some(line => line.startsWith("?")));
// Complete prepared objects stay local. An incomplete or absent prepared base
// uses the existing depth-bounded canonical fetch and keeps every exact-SHA guard.
git(["fetch", "-q", "--depth=2", preparedBaseComplete ? preparedGit : "origin",
expected.baseSha + ":refs/remotes/origin/main"], { phase: "base-fetch" });
if (git(["rev-parse", "refs/remotes/origin/main"]).trim() !== expected.baseSha)
fail("source base mismatch");
git(["fetch", "-q", bundle, "refs/openclaw/source-capsule:refs/heads/openclaw-source"],
{ phase: "capsule-fetch" });
for (const [ref, value] of [
["refs/heads/openclaw-source", expected.carrier],
["refs/heads/openclaw-source^{tree}", expected.tree],
["refs/heads/openclaw-source^", expected.baseSha],
]) if (git(["rev-parse", ref]).trim() !== value) fail("source capsule identity mismatch");
function entries(tree, directory = gitDir) {
const output = git(["ls-tree", "-r", "-z", tree], { encoding: "buffer",
env: { ...env, GIT_DIR: directory, GIT_INDEX_FILE: path.join(directory, "index") } });
if (!isUtf8(output)) fail("unsupported non-UTF-8 source paths");
return output.subarray(0, -1).toString("utf8")
.split("\0").filter(Boolean).map(row => {
const match = /^(100644|100755|120000) blob ([a-f0-9]{40})\t([\s\S]+)$/.exec(row);
if (!match) fail("unsupported source tree entry");
return { mode: match[1], oid: match[2], file: safePath(match[3]) };
});
}
// The prepared workspace can contain newer workflow source. Its committed tree
// owns only cleanup candidates; the capsule alone selects the executed source.
const previous = new Map((!preserveGit && process.argv[2] ? entries("HEAD", path.join(cwd, ".git")) : [])
.map(entry => [entry.file, entry]));
const files = entries(expected.tree);
const metadata = JSON.parse(git(["show", "-s", "--format=%B", expected.carrier]));
if (!Array.isArray(metadata.deleted) || metadata.deleted.some(file => typeof file !== "string"))
fail("invalid source deletion inventory");
const deleted = new Set(metadata.deleted.map(safePath));
const selected = new Set(files.map(entry => entry.file));
const directories = new Set();
for (const { file } of files) {
let parent = path.posix.dirname(file);
while (parent !== ".") { directories.add(parent); parent = path.posix.dirname(parent); }
}
// Never follow an old directory symlink while removing or creating source entries.
function reachable(file) {
let parent = path.posix.dirname(file);
while (parent !== ".") {
if (!stat(parent)?.isDirectory()) return false;
parent = path.posix.dirname(parent);
}
return true;
}
function remove(file) {
safePath(file);
if (reachable(file)) fs.rmSync(file, { recursive: true, force: true });
}
// The producer owns privacy-filtered deletions, including ignored entries lost
// from old indexes. A directory with unknown contents is not ours to erase.
for (const file of [...deleted].sort((a, b) => b.split("/").length - a.split("/").length)) {
if (selected.has(file) || directories.has(file)) fail("conflicting source deletion");
if (reachable(file)) {
if (stat(file)?.isDirectory()) fs.rmdirSync(file);
else fs.rmSync(file, { force: true });
}
}
for (const directory of [...directories].sort((a, b) => a.split("/").length - b.split("/").length)) {
if (!stat(directory)?.isDirectory()) {
remove(directory);
fs.mkdirSync(directory);
}
}
// Reuse only physically verified bytes, kinds, and executable bits. No source
// code runs before acceptance; lifecycle hooks still trigger a full recheck.
const changed = files.filter(entry => sourceMismatch(entry) !== null);
// Batch raw blobs once; checkout/archive would apply attributes or export rules.
const blobPath = path.join(temporary, "blobs");
const output = fs.openSync(blobPath, "wx");
try { git(["cat-file", "--batch"], {
input: changed.map(entry => entry.oid + "\n").join(""), stdio: ["pipe", output, "pipe"]
}); } finally { fs.closeSync(output); }
const input = fs.openSync(blobPath, "r");
const buffer = Buffer.alloc(65536);
let cursor = 0;
let end = 0;
function take(count) {
if (cursor === end) { end = fs.readSync(input, buffer); cursor = 0; }
if (end === 0) fail("truncated source blobs");
const chunk = buffer.subarray(cursor, Math.min(end, cursor + count));
cursor += chunk.length;
return chunk;
}
try {
for (const entry of changed) {
let header = "";
for (;;) {
const byte = take(1)[0];
if (byte === 10) break;
header += String.fromCharCode(byte);
if (header.length > 100) fail("invalid source blob header");
}
const match = /^([a-f0-9]{40}) blob (\d+)$/.exec(header);
if (!match || match[1] !== entry.oid) fail("source blob identity mismatch");
let remaining = Number(match[2]);
remove(entry.file);
const fd = entry.mode === "120000" ? null : fs.openSync(entry.file, "wx", 0o600);
const target = [];
try {
while (remaining > 0) {
const bytes = take(remaining);
remaining -= bytes.length;
if (fd === null) target.push(Buffer.from(bytes));
else fs.writeFileSync(fd, bytes);
}
} finally { if (fd !== null) fs.closeSync(fd); }
if (take(1)[0] !== 10) fail("invalid source blob terminator");
if (fd === null) fs.symlinkSync(Buffer.concat(target), entry.file);
else fs.chmodSync(entry.file, entry.mode === "100755" ? 0o755 : 0o644);
}
} finally { fs.closeSync(input); }
git(["read-tree", expected.tree]);
fs.rmSync(capsule);
for (;;) {
const extras = git(["ls-files", "--others", "--exclude-standard", "-z"]).split("\0")
.filter(file => file && !file.startsWith(path.basename(temporary) + "/"));
if (extras.length === 0) break;
// Settle ancestor ignore rules first: removing a negated rule can protect
// descendant rules already listed, while removing an exclusion can reveal more.
const ignore = extras.filter(file => path.posix.basename(file) === ".gitignore")
.sort((a, b) => a.split("/").length - b.split("/").length)[0];
for (const file of ignore ? [ignore] : extras) {
const entry = previous.get(file);
if (!entry) fail("unexpected source entry: " + file);
// Preserve untracked, ignored, and modified runtime state. Only unchanged
// committed extras may be retired after the new source's ignore rules apply.
verify(entry);
fs.unlinkSync(file);
deleted.add(file);
}
// Each pass removes committed files. Retiring their .gitignore rules can
// expose more entries, so verification ends only with an empty inventory.
}
for (const file of deleted) {
if (reachable(file) && stat(file)) fail("source deletion mismatch: " + file);
}
// Verify filesystem bytes, kind, and executable bit independently of either index.
function sourceMismatch({ file, mode, oid }) {
if (!reachable(file)) return "source parent mismatch";
const info = stat(file);
let actual;
if (mode === "120000") {
if (!info?.isSymbolicLink()) return "source kind mismatch";
const target = fs.readlinkSync(file, { encoding: "buffer" });
actual = createHash("sha1").update("blob " + target.length + "\0").update(target).digest("hex");
} else {
if (!info?.isFile() || Boolean(info.mode & 0o100) !== (mode === "100755"))
return "source mode mismatch";
actual = hashFile(file, "sha1", true);
}
return actual === oid ? null : "source bytes mismatch";
}
function verify(entry) {
const mismatch = sourceMismatch(entry);
if (mismatch) fail(mismatch + ": " + entry.file);
}
if (expected.alias) git(["update-ref", expected.alias, expected.baseSha]);
git(["symbolic-ref", "HEAD", "refs/heads/openclaw-source"]);
const sourceIndex = git(["ls-files", "--stage", "-v", "-z"], { encoding: "buffer" });
const sourceGit = stat(env.GIT_DIR);
// The payload consumes Git identity as well as bytes. Lifecycle hooks may refresh
// index caches or hooksPath, but cannot change source membership or comparison refs.
function verifySource(entries = files) {
const currentGit = stat(env.GIT_DIR);
if (!currentGit?.isDirectory() || currentGit.dev !== sourceGit.dev || currentGit.ino !== sourceGit.ino ||
!stat(env.GIT_INDEX_FILE)?.isFile() || stat(path.join(env.GIT_DIR, "commondir")))
fail("source Git owner mismatch");
for (const entry of entries) verify(entry);
for (const file of deleted) {
if (reachable(file) && stat(file)) fail("source deletion mismatch: " + file);
}
if (!git(["ls-files", "--stage", "-v", "-z"], { encoding: "buffer" }).equals(sourceIndex))
fail("source index mismatch");
if (git(["symbolic-ref", "HEAD"]).trim() !== "refs/heads/openclaw-source")
fail("source HEAD mismatch");
for (const [ref, value] of [
["HEAD", expected.carrier], ["refs/remotes/origin/main", expected.baseSha],
...(expected.alias ? [[expected.alias, expected.baseSha]] : []),
]) if (git(["rev-parse", ref]).trim() !== value) fail("source comparison ref mismatch: " + ref);
const extras = git(["ls-files", "--others", "--exclude-standard", "-z"])
.split("\0").filter(file => file && !file.startsWith(path.basename(temporary) + "/"));
if (extras.length) fail("unexpected source entry: " + extras[0]);
}
verifySource(changed);
// Publish Git identity only after verification; rejected source must retain
// the prepared checkout revision for recovery. Renaming preserves its owner.
// Boat reuses this transport checkout. Keep its exact Git owner, including
// native sync metadata, until the selected-source payload has fully closed.
if (preserveGit && stat(path.join(cwd, ".git"))) {
nativeGit = path.join(temporary, "native-git");
fs.renameSync(path.join(cwd, ".git"), nativeGit);
} else {
fs.rmSync(".git", { recursive: true, force: true });
}
fs.renameSync(gitDir, path.join(cwd, ".git"));
publishedGit = stat(path.join(cwd, ".git"));
env.GIT_DIR = path.join(cwd, ".git");
env.GIT_INDEX_FILE = path.join(env.GIT_DIR, "index");
if (selected.has("pnpm-lock.yaml")) {
const installer = ".github/actions/setup-node-env/install-dependencies.sh";
if (!selected.has(installer) || !stat(installer)?.isFile())
fail("selected source lacks a regular dependency install owner");
// Hydration belongs to workflow source. Reconcile through the selected
// source's install owner before any caller payload can run.
const installEnv = { ...env, CI: "true", GITHUB_WORKSPACE: cwd,
NODE_BIN: path.dirname(process.execPath), FROZEN_LOCKFILE: "true",
PNPM_CONFIG_FROZEN_LOCKFILE: "true",
DEPENDENCY_CACHE: "false", DEPENDENCY_CACHE_HIT: "false" };
for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"]) delete installEnv[key];
process.stderr.write("[crabbox] reconciling selected-source dependencies\n");
const install = preserveGit
? await runChild("bash", [installer], installEnv, ["inherit", 2, 2])
: spawnSync("bash", [installer], { cwd, env: installEnv, stdio: ["inherit", 2, 2] });
if (install.status !== 0) fail("selected-source frozen install failed; payload was not run");
verifySource();
}
process.stderr.write("[crabbox] verified source=" + expected.sourceSha + " tree=" + expected.tree + " carrier=" + expected.carrier + "\n");
if (preserveGit) {
let result;
if (expected.script) {
const script = fs.readFileSync(3).subarray(0, expected.scriptBytes);
fs.closeSync(3);
const file = path.join(temporary, "payload");
fs.writeFileSync(file, script, { mode: 0o700 });
const args = process.argv.slice(2);
result = script.subarray(0, 2).toString() === "#!"
? await runChild(file, args, { ...process.env, CI: "true" })
: await runChild("bash", [file, ...args], { ...process.env, CI: "true" });
} else {
result = await runChild("bash", ["-c", expected.payload, "openclaw-source-payload", ...process.argv.slice(2)], process.env);
}
process.exitCode = signal ? 128 + constants.signals[signal] : result.status ?? 128 + constants.signals[result.signal];
}
} catch (error) {
process.stderr.write("[crabbox] source verification failed: " + error.message + "\n");
process.exitCode = signal ? 128 + constants.signals[signal] : 2;
} finally {
try {
if (!settled) fail("source payload settlement is unverified; temporary source retained");
if (preserveGit && publishedGit) {
const current = stat(path.join(cwd, ".git"));
if (!current || current.dev !== publishedGit.dev || current.ino !== publishedGit.ino)
fail("source Git owner changed; temporary source retained");
fs.rmSync(path.join(cwd, ".git"), { recursive: true });
}
if (nativeGit) fs.renameSync(nativeGit, path.join(cwd, ".git"));
if (temporary) fs.rmSync(temporary, { recursive: true, force: true });
} catch (error) {
process.stderr.write("[crabbox] source Git restoration failed: " + error.message + "\n");
process.exitCode ||= 2;
}
if (preserveGit) for (const [value, handler] of signalHandlers)
process.removeListener(value, handler);
}
}
void receive();
`;function remoteSourceBootstrap(e,t,n,r){const quote=e=>`'${e.replaceAll(`'`,`'\\''`)}'`;const{sourceSha:i,baseSha:a,tree:o,carrier:s,digest:c}=e;const l=`node -e ${quote(receiver)} ${quote(JSON.stringify({sourceSha:i,baseSha:a,tree:o,carrier:s,digest:c,alias:t,payload:r&&`command`in r?r.command:void 0,script:Boolean(r&&`script`in r),scriptBytes:r&&`script`in r?Buffer.byteLength(r.script):void 0}))}`;if(!n){if(r&&`script`in r)return`exec ${l} "$@" 3<<'${r.delimiter}'\n${r.script}${r.script.endsWith(`
`)?``:`
`}${r.delimiter}\n`;return r===void 0?l:`exec ${l} "$@"`}return[`openclaw_source_root="$(cd ./.git/crabbox-artifact-root && pwd -P)" || { echo "[crabbox] missing prepared Testbox execution workspace; stop this lease and warm a fresh one" >&2; exit 2; };`,`${l} "$openclaw_source_root" && cd "$openclaw_source_root"`].join(` `)}
//!scripts/crabbox-wrapper-providers.mts
const providerAliases=/* @__PURE__ */ new Map([[`ascii`,`ascii-box`],[`asciibox`,`ascii-box`],[`boat`,`ascii-box`],[`blacksmith`,`blacksmith-testbox`],[`cf`,`cloudflare`],[`container`,`local-container`],[`docker`,`local-container`],[`exe`,`exe-dev`],[`exedev`,`exe-dev`],[`google`,`gcp`],[`google-cloud`,`gcp`],[`local-docker`,`local-container`],[`namespace`,`namespace-devbox`],[`namespace-devboxes`,`namespace-devbox`],[`rail`,`railway`],[`railwayapp`,`railway`],[`run-pod`,`runpod`],[`runpodio`,`runpod`],[`sem`,`semaphore`],[`static`,`ssh`],[`static-ssh`,`ssh`],[`tensorlake-sbx`,`tensorlake`],[`tl`,`tensorlake`]]);function canonicalProviderName(e){return providerAliases.get(e)??e}function addProviderNames(e,t){for(const n of t.replace(/\s+\(defaults?\b.*$/u,``).split(/\s*(?:,|\||\bor\b)\s*/u).map(e=>e.trim()).filter(Boolean))if(/^[a-z0-9][a-z0-9-]*$/u.test(n))e.add(n)}function providerListContinuation(e,t){const n=e.match(/^\s*((?:or\s+)?[a-z0-9][a-z0-9-]*(?:\s*(?:,|\||\bor\b)\s*(?:or\s+)?[a-z0-9][a-z0-9-]*)*\s*(?:,|\|)?)(?:\s+\(defaults?\b.*)?\s*$/u);if(!n)return``;if(/[,|]\s*$/u.test(t)||/[,|]|\bor\b|\(defaults?\b/u.test(e))return n[1]??``;return``}function parseProvidersFromHelp(e){const t=/* @__PURE__ */ new Set;const n=e.split(/\r?\n/u);for(let e=0;e<n.length;e+=1){const r=n[e]??``;const i=r.match(/provider:\s*([a-z0-9][a-z0-9, -]*)(?:\s*\(defaults?\b|$)/u);if(i){let r=i[1]??``;while(!/\(defaults?\b/u.test(n[e]??``)&&e+1<n.length){const t=providerListContinuation(n[e+1]??``,r);if(!t)break;e+=1;r=`${r} ${t}`}addProviderNames(t,r);continue}const a=r.match(/^\s+-{1,2}provider(?:[=\s]+)([a-z0-9][a-z0-9|, -]*)(?:\s{2,}|\s+\(|$)/u)?.[1]??``;if(/[,|]|\bor\b/u.test(a))addProviderNames(t,a)}return[...t]}function isProviderAdvertised(e,t){const n=canonicalProviderName(e);return t.includes(e)||t.includes(n)}
//!scripts/testbox-lease-freshness.mts
const STATE_VERSION=2;const ENVIRONMENT_INPUTS=[`.crabbox.yaml`,`.github/actions/prepare-testbox-shell`,`.github/actions/setup-android-toolchain`,`.node-version`,`scripts/crabbox-wrapper.mjs`,`scripts/crabbox-wrapper.mts`,`scripts/crabbox-source-capsule.mts`,`scripts/crabbox-source-receiver.mts`,`scripts/testbox-lease-freshness.mts`];function booleanOption(e,t){return[`1`,`t`,`T`,`TRUE`,`true`,`True`].includes(e.get(t)??``)}function git(e,t){return execFileSync(`git`,[`-C`,e,...t],{encoding:`utf8`,env:{...process.env,GIT_CONFIG_GLOBAL:`/dev/null`}}).trim()}function listFiles(e){if(!existsSync(e))return[];if(statSync(e).isFile())return[e];return readdirSync(e,{withFileTypes:true}).flatMap(t=>listFiles(resolve(e,t.name))).toSorted((e,t)=>e.localeCompare(t))}function digestInputs(e,t){const n=createHash(`sha256`);for(const r of t)for(const t of listFiles(resolve(e,r))){n.update(t.slice(e.length));n.update(`\0`);n.update(readFileSync(t));n.update(`\0`)}return n.digest(`hex`)}function digest(e){return createHash(`sha256`).update(e).digest(`hex`)}function taskIdentity(e,t){const n=e.get(`label`)??``;const r=t.CODEX_THREAD_ID?`codex`:t.CLAUDE_CODE_SESSION_ID?`claude`:t.GITHUB_RUN_ID?`github-actions`:`operator`;const i=t.CODEX_THREAD_ID||t.CLAUDE_CODE_SESSION_ID||(t.GITHUB_RUN_ID?`${t.GITHUB_REPOSITORY}:${t.GITHUB_RUN_ID}:${t.GITHUB_RUN_ATTEMPT}:${t.GITHUB_JOB}`:``);return{caller:r,taskKey:i||n?digest(JSON.stringify([r,i,n])):``}}function buildTestboxLeaseFingerprint(e,t,n){const r=t.get(`blacksmith-workflow`)??`.github/workflows/ci-check-testbox.yml`;let i;try{i=git(e,[`merge-base`,`HEAD`,`refs/remotes/origin/main`])}catch{i=git(e,[`rev-parse`,`HEAD`])}return{version:STATE_VERSION,...taskIdentity(t,n),checkoutKey:digest(realpathSync(e)),baseSha:i,headSha:git(e,[`rev-parse`,`HEAD`]),dependencyDigest:digest(execFileSync(process.execPath,[resolve(e,`.github/actions/setup-node-env/dependency-fingerprint.mjs`),`--workspace`,e,`--frozen-lockfile`,`true`],{cwd:e,env:{...process.env,...n},encoding:`utf8`}).trim()),environmentDigest:digestInputs(e,[...ENVIRONMENT_INPUTS,...r?[r]:[]]),workflow:r,job:t.get(`blacksmith-job`)??`check`,ref:t.get(`blacksmith-ref`)??`main`}}function testboxLeaseStaleReasons(e,t){if(!isRecord(e)||e.version!==STATE_VERSION||!isRecord(t))return[`state schema`];if(typeof e.headSha!==`string`||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(e.headSha))return[`headSha`];return[`taskKey`,`checkoutKey`,`baseSha`,`dependencyDigest`,`environmentDigest`,`workflow`,`job`,`ref`].filter(n=>e[n]!==t[n])}function assertAllocationReceipt(e,t,n){if(!t)return;const r=resolve(e,`${t}.json`);if(!existsSync(r))throw new Error(`Testbox ${t} has no allocation receipt; stop it and allocate a fresh lease through scripts/crabbox-wrapper.mjs`);const i=testboxLeaseStaleReasons(JSON.parse(readFileSync(r,`utf8`)),n);if(i.length>0)throw new Error(`Testbox ${t} is stale (${i.join(`, `)}); stop it and allocate a fresh lease`)}function prepareTestboxLeaseFreshness({operation:e,options:t,command:n,env:r,provider:i,repoRoot:a}){const o=t.get(`id`)??``;if(i!==`blacksmith-testbox`||![`run`,`warmup`].includes(e))return null;const s=r.OPENCLAW_TESTBOX_LEASE_STATE_DIR?.trim();if(r.VITEST&&!s)return null;const c=resolve(s||resolve(a,`.crabbox`,`testbox-leases`));const l=buildTestboxLeaseFingerprint(a,t,r);if(o&&!/^tbx_[a-zA-Z0-9_-]+$/u.test(o))throw new Error(`Testbox reuse requires an exact tbx_ lease id`);const u=booleanOption(t,`keep`);const d=booleanOption(t,`keep-on-failure`);if(!l.taskKey&&(o||e===`warmup`||u||d))throw new Error(`Reusable Testboxes need a caller session or task label. Start with run --keep --label <unique-task-name>, reuse that label on each run, then stop the lease`);assertAllocationReceipt(c,o,l);return{current:l,stateDir:c,id:o,retained:e===`warmup`||u||Boolean(o),keepOnFailure:d,assertCurrent(){assertAllocationReceipt(c,o,l)},attribution:{...l,commandKey:digest(JSON.stringify(n)),operation:e,requestedIdleTimeout:t.get(`idle-timeout`)||void 0,requestedTtl:t.get(`ttl`)||void 0}}}function recordTestboxLeaseFreshness(e,t=e?.id,n=0){if(!e||!e.retained&&!(e.keepOnFailure&&n!==0))return;if(!t||!/^tbx_[a-zA-Z0-9_-]+$/u.test(t))throw new Error(`Testbox did not return an allocation receipt; inspect the native lease before reusing it`);if(e.id)return;mkdirSync(e.stateDir,{recursive:true});const r=resolve(e.stateDir,`${t}.json`);const i=`${r}.tmp-${process.pid}`;writeFileSync(i,`${JSON.stringify(e.current,null,2)}\n`,{mode:384});renameSync(i,r)}
//!scripts/crabbox-wrapper.mts
const repoRoot=resolve(dirname(fileURLToPath(import.meta.url)),`..`);const args=process.argv.slice(2);if(args[0]===`--`)args.shift();if(args[0]===`staging`){const{runStagingCommand:e}=await import(`./crabbox-staging-BGE9uwdN.mjs`);process.exit(await e(args.slice(1),fullCheckoutSyncRoot(false),{cwd:repoRoot,binary:findCrabboxBinary({openclawRoot:process.env.OPENCLAW_CRABBOX_WRAPPER_IGNORE_REPO_BINARY===`1`?void 0:repoRoot,pathEnv:process.env[resolvePathEnvKey(process.env)]})??`crabbox`}))}const CRABBOX_METADATA_PROBE_TIMEOUT_MS=5e3;const MAX_TIMING_JSON_LINE_CHARS=1048576;const CRABBOX_METADATA_PROBE_RETRY_TIMEOUT_MS=2e4;const ignoreRepoBinary=process.env.OPENCLAW_CRABBOX_WRAPPER_IGNORE_REPO_BINARY===`1`;const candidateBinary=findCrabboxBinary({openclawRoot:ignoreRepoBinary?void 0:repoRoot,pathEnv:process.env[resolvePathEnvKey(process.env)]})??resolveGitCommonCrabboxBinary(process.env,process.platform)??`crabbox`;let cli;try{cli=await ensureManagedCrabboxBinary({binary:candidateBinary})}catch(e){console.error(`[crabbox] ${e instanceof Error?e.message:String(e)}`);process.exit(2)}const{binary,version:version$1}=cli;const workloadCommand=isWorkloadRoutedCommand(args);const workloadOption=workloadCommand?extractWrapperValueOption(args,`--workload`):void 0;const userArgStart=commandUserArgStart(args);function extractWrapperValueOption(e,t){const n=`${t}=`;for(let r=0;r<e.length;r+=1){const i=e[r]??``;if(i===`--`)break;if(i===t){const t=e[r+1];if(!t||t===`--`||t.startsWith(`-`)){e.splice(r,1);return null}e.splice(r,2);return t}if(i.startsWith(n)){e.splice(r,1);return i.slice(n.length)||null}}}function isWorkloadRoutedCommand(e){return[`run`,`warmup`].includes(e[0]??``)||e[0]===`actions`&&e[1]===`hydrate`}function commandUserArgStart(e){return e[0]===`actions`&&e[1]===`hydrate`?2:1}function commandCandidates(e,t){if(t!==`win32`)return[e];if(extname(e))return[e];return[`${e}.exe`,`${e}.cmd`,`${e}.bat`,`${e}.com`,e]}function resolvePathBinary(e,t,n){const r=t[resolvePathEnvKey(t)]??``;for(const t of r.split(delimiter).filter(Boolean))for(const r of commandCandidates(e,n)){const e=resolve(t,r);if(isExecutableFile(e,n))return e}return null}function resolveGitCommonCrabboxBinary(e,t){const n=spawnInvocation(resolvePathBinary(`git`,e,t)??`git`,[`rev-parse`,`--git-common-dir`],e,t);const r=spawnSync(n.command,n.args,{cwd:repoRoot,encoding:`utf8`,stdio:[`ignore`,`pipe`,`ignore`],windowsVerbatimArguments:n.windowsVerbatimArguments});if((r.status??1)!==0)return null;const i=r.stdout.trim();if(!i)return null;const a=isAbsolute(i)?i:resolve(repoRoot,i);return findCrabboxBinary({openclawRoot:resolve(a,`..`),platform:t})}function isExecutableFile(e,t){try{if(!statSync(e).isFile())return false;if(t!==`win32`)accessSync(e,constants.X_OK);return true}catch{return false}}function spawnInvocation(e,t,n,r){const i=extname(e).toLowerCase();if(r===`win32`&&(i===`.cmd`||i===`.bat`)){const i=resolveNodeCmdShim(e,r);if(i)return{command:i.node,args:[...i.args,...t]};return{command:resolveWindowsCmdExePath(n),args:[`/d`,`/s`,`/c`,buildBatchCommandLine(e,t)],windowsVerbatimArguments:true}}return{command:e,args:t}}function resolveNodeCmdShim(e,t){let n;try{n=readFileSync(e,`utf8`)}catch{return null}for(const r of n.split(/\r?\n/u)){const n=r.trim();const i=/^"([^"]+node(?:\.exe)?)"\s+"%~dp0([^"]+)"\s+%\*$/iu.exec(n);if(!i)continue;const a=resolve(dirname(e),i[2]??``);if(!isExecutableFile(a,t))continue;return{node:i[1]??`node`,args:[a]}}const r=resolveNpmNodeCmdShim(e,n,t);if(r)return r;return null}function resolveNpmNodeCmdShim(e,t,n){const r=t.split(/\r?\n/u).map(e=>e.trim());if(!r.some(e=>/^IF EXIST "%dp0%\\node\.exe" \($/iu.test(e))||!r.some(e=>/^SET "_prog=node(?:\.exe)?"$/iu.test(e)))return null;const i=r.find(e=>e.includes(`"%_prog%"`)&&e.endsWith(`%*`));if(!i)return null;const a=/(?:^|&)\s*"%_prog%"\s+(.*?)"(%dp0%\\[^"]+)"\s+%\*$/iu.exec(i);if(!a||(a[1]??``).trim())return null;const o=resolve(dirname(e),(a[2]??``).replace(/^%dp0%\\/iu,``));if(!isExecutableFile(o,n))return null;const s=resolve(dirname(e),`node.exe`);return{node:isExecutableFile(s,n)?s:`node`,args:[o]}}const cmdMetaCharactersRe=/([()\][%!^"`<>&|;, *?])/g;const jsRuntimeEntrypoints=/* @__PURE__ */ new Set([`pnpm`,`npm`,`npx`,`corepack`,`node`,`yarn`,`bun`,`bunx`]);const awsMacosCorepackEntrypoints=/* @__PURE__ */ new Set([`pnpm`,`yarn`,`corepack`]);const awsMacosBunEntrypoints=/* @__PURE__ */ new Set([`bun`,`bunx`]);const awsMacosBunVersion=`1.4.4`;const awsMacosSwiftEntrypoints=/* @__PURE__ */ new Set([`swift`,`xcodebuild`]);const awsMacosSwiftScriptTargets=/* @__PURE__ */ new Set([`mac:package`,`mac:restart`,`scripts/build-and-run-mac.sh`,`scripts/package-mac-app.sh`,`scripts/package-mac-dist.sh`,`scripts/restart-mac.sh`]);const awsMacosPackageManagerScriptTargets=/* @__PURE__ */ new Set([`scripts/package-mac-app.sh`,`scripts/package-mac-dist.sh`,`scripts/restart-mac.sh`]);const shellControlCommandPrefixes=/* @__PURE__ */ new Set([`if`,`while`,`until`,`then`,`do`,`else`,`elif`,`!`]);const shellCommandExecutionPrefixes=/* @__PURE__ */ new Set([`exec`]);const shellInlineCommandInterpreters=/* @__PURE__ */ new Set([`bash`,`dash`,`ksh`,`sh`,`zsh`]);const remoteChangedGateEnv=[`OPENCLAW_CHECK_CHANGED_REMOTE_CHILD=1`,`OPENCLAW_CHANGED_LANES_RAW_SYNC=1`,`CI=1`];const shellInlineCommandOptionsWithNextValue=/* @__PURE__ */ new Set([`+O`,`+o`,`-O`,`-o`,`--init-file`,`--rcfile`]);const nodeOptionsWithNextValueBeforeScript=/* @__PURE__ */ new Set([`--allow-fs-read`,`--allow-fs-write`,`--conditions`,`--cpu-prof-dir`,`--cpu-prof-interval`,`--cpu-prof-name`,`--debug-port`,`--diagnostic-dir`,`--disable-proto`,`--disable-warning`,`--dns-result-order`,`--env-file`,`--env-file-if-exists`,`--experimental-config-file`,`--experimental-loader`,`--experimental-test-isolation`,`--heap-prof-dir`,`--heap-prof-interval`,`--heap-prof-name`,`--heapsnapshot-near-heap-limit`,`--heapsnapshot-signal`,`--icu-data-dir`,`--import`,`--inspect-port`,`--inspect-publish-uid`,`--initial-old-space-size`,`--localstorage-file`,`--loader`,`--max-http-header-size`,`--max-old-space-size`,`--max-old-space-size-percentage`,`--max-semi-space-size`,`--network-family-autoselection-attempt-timeout`,`--openssl-config`,`--redirect-warnings`,`--report-dir`,`--report-directory`,`--report-filename`,`--report-signal`,`--require`,`--secure-heap`,`--secure-heap-min`,`--snapshot-blob`,`--test-concurrency`,`--test-coverage-branches`,`--test-coverage-exclude`,`--test-coverage-functions`,`--test-coverage-include`,`--test-coverage-lines`,`--test-global-setup`,`--test-isolation`,`--test-name-pattern`,`--test-reporter`,`--test-reporter-destination`,`--test-rerun-failures`,`--test-shard`,`--test-skip-pattern`,`--test-timeout`,`--title`,`--tls-cipher-list`,`--tls-keylog`,`--trace-event-categories`,`--trace-event-file-pattern`,`--trace-require-module`,`--unhandled-rejections`,`--use-largepages`,`--v8-pool-size`,`--watch-kill-signal`,`--watch-path`,`-C`,`-r`]);const nodeOptionsWithoutScript=/* @__PURE__ */ new Set([`--build-sea`,`--build-snapshot`,`--build-snapshot-config`,`--check`,`--completion-bash`,`--eval`,`--experimental-sea-config`,`--help`,`--input-type`,`--interactive`,`--print`,`--prof-process`,`--run`,`--v8-options`,`--version`,`-c`,`-e`,`-h`,`-i`,`-p`,`-v`]);function escapeBatchCommand(e){return e.replace(cmdMetaCharactersRe,`^$1`)}function escapeBatchArgument(e){let t=e;t=t.replace(/(?=(\\+?)?)\1"/g,`$1$1\\"`);t=t.replace(/(?=(\\+?)?)\1$/,`$1$1`);t=`"${t}"`;t=t.replace(cmdMetaCharactersRe,`^$1`);return t.replace(cmdMetaCharactersRe,`^$1`)}function buildBatchCommandLine(e,t){return`"${[escapeBatchCommand(e),...t.map(escapeBatchArgument)].join(` `)}"`}function checkedOutput(e,t,n=resolveMetadataProbeTimeoutMs(process.env)){const r=spawnInvocation(e,t,process.env,process.platform);const i=spawnSync(r.command,r.args,{cwd:repoRoot,encoding:`utf8`,stdio:[`ignore`,`pipe`,`pipe`],windowsVerbatimArguments:r.windowsVerbatimArguments,...n===null?{}:{timeout:n},killSignal:`SIGKILL`});return{status:i.error?.name===`Error`&&i.signal===`SIGKILL`?124:i.status??1,text:`${i.stdout??``}${i.stderr??``}`.trim(),stdout:(i.stdout??``).trim(),stderr:(i.stderr??``).trim()}}function recoveryCommand(e){return[binary,...e].map(recoveryCommandArgument).join(` `)}function recoveryCommandArgument(e){const t=e;if(/^[A-Za-z0-9_./:@%+=,-]+$/u.test(t))return t;if(process.platform===`win32`)return`"${t.replaceAll(`"`,`""`)}"`;return`'${t.replaceAll(`'`,`'\\''`)}'`}function probeCrabboxHelp(e,t){const n=checkedOutput(e,t);if(n.status===0&&n.text.length>0)return n;return checkedOutput(e,t,CRABBOX_METADATA_PROBE_RETRY_TIMEOUT_MS)}function gitOutput(e,t={}){const n=resolvePathBinary(`git`,process.env,process.platform)??`git`;const r={...process.env,...t,GIT_CONFIG_GLOBAL:`/dev/null`};const i=spawnInvocation(n,e,r,process.platform);const a=spawnSync(i.command,i.args,{cwd:repoRoot,encoding:`utf8`,env:r,stdio:[`ignore`,`pipe`,`pipe`],windowsVerbatimArguments:i.windowsVerbatimArguments});return{status:a.status??1,text:`${a.stdout??``}${a.stderr??``}`.trim(),stdout:(a.stdout??``).trim()}}let resolvedCrabboxConfigCache;function resolvedCrabboxConfig(){if(resolvedCrabboxConfigCache!==void 0)return resolvedCrabboxConfigCache;const e=checkedOutput(binary,[`config`,`show`,`--json`]);if(e.status!==0){resolvedCrabboxConfigCache=null;return resolvedCrabboxConfigCache}try{const t=JSON.parse(e.stdout||e.text);resolvedCrabboxConfigCache=isRecord(t)?t:null}catch{resolvedCrabboxConfigCache=null}return resolvedCrabboxConfigCache}function envProvider(){const e=process.env.CRABBOX_PROVIDER?.trim();if(e)return e;return``}function configProvider(){const e=resolvedCrabboxConfig()?.provider;if(typeof e===`string`&&e.trim())return e.trim();try{return readFileSync(resolve(repoRoot,`.crabbox.yaml`),`utf8`).match(/^provider:\s*([^\s#]+)/m)?.[1]??`aws`}catch{return`aws`}}function effectiveTargetContext(e){const t=resolvedCrabboxConfig();const n=typeof t?.target===`string`?t.target.trim():``;const r=typeof t?.windowsMode===`string`?t.windowsMode.trim():``;return{target:(optionValue(e,`--target`)||process.env.CRABBOX_TARGET?.trim()||process.env.CRABBOX_TARGET_OS?.trim()||n).toLowerCase(),windowsMode:(optionValue(e,`--windows-mode`)||process.env.CRABBOX_WINDOWS_MODE?.trim()||r).toLowerCase()}}let commandValueOptionsFromHelp;function parseCommandValueOptionsFromHelp(e){const t=/* @__PURE__ */ new Set;for(const n of e.split(/\r?\n/u)){const e=n.match(/^\s+-{1,2}([a-z0-9][a-z0-9-]*)\s+(?:string|duration|int|float|value)\b/u);if(e)t.add(e[1]??``)}return t}function commandOptionName(e){return e.replace(/^-+/u,``).split(`=`,1)[0]??``}function parseCommandInvocation(e,t){commandValueOptionsFromHelp??=parseCommandValueOptionsFromHelp(e);const n=isWorkloadRoutedCommand(t);const r=n?commandUserArgStart(t):0;let i=-1;let a=n?t.length:t.indexOf(`--`);a=a<0?t.length:a;if(n)for(let e=r;e<t.length;e+=1){const n=t[e]??``;if(n===`--`){i=e+1;a=e;break}if(n===`-`||!n.startsWith(`-`)){i=e;a=e;break}if(!n.includes(`=`)&&commandValueOptionsFromHelp.has(commandOptionName(n)))e+=1}const o=[];const s=/* @__PURE__ */ new Map;for(let e=r;e<a;e+=1){const r=t[e]??``;if(!r.startsWith(`-`))continue;const i=commandOptionName(r);const a=r.indexOf(`=`);const c=!n||commandValueOptionsFromHelp.has(i);const l={index:e,value:a>=0?r.slice(a+1):c?t[e+1]??``:``};o.push({name:i,...l});if(!s.has(i))s.set(i,l);if(n&&a<0&&c)e+=1}const c=o.findLast(({name:e})=>e===`script`);const l=o.findLast(({name:e})=>e===`script-stdin`);const u=o.some(({name:e,index:n,value:r})=>e===`script-stdin`&&t[n]?.includes(`=`)&&!/^(?:1|t|T|true|TRUE|True|0|f|F|false|FALSE|False)$/u.test(r));const d=Boolean(l&&(!t[l.index]?.includes(`=`)||/^(?:1|t|T|true|TRUE|True)$/u.test(l.value)));return{args:t,scriptRequested:!u&&Boolean(c?.value||d),script:u||c?.value&&d?void 0:c?.value?c:d?l:void 0,commandArgs:i>=0?t.slice(i):[],optionEntries:o,options:s,optionEnd:a,start:i}}function commandProvider(e){return optionValue(e,`--provider`)}function selectedProvider(e,t=[]){const n=effectiveTargetContext(e);if(workloadOption===null)return{provider:``,source:`policy`,workload:``,chain:[],error:`--workload requires a value`};const r=requestedWorkload(e);if(r===null)return{provider:``,source:`policy`,workload:workloadOption??process.env.OPENCLAW_CRABBOX_WORKLOAD??``,chain:[],error:`unsupported Crabbox workload ${JSON.stringify(workloadOption??process.env.OPENCLAW_CRABBOX_WORKLOAD)}`};if(r===`windows`&&n.target!==`windows`)return{provider:``,source:`policy`,workload:r,chain:[],error:`Crabbox workload=windows requires target=windows`};const i=canonicalProviderName(configProvider());const a=r?crabboxProviderChain({workload:r,configuredProvider:i,target:n.target,advertisedProviders:t.map(canonicalProviderName)}):[];if(r===`untrusted`&&hasOption(e,`--id`))return{provider:``,source:`policy`,workload:r,chain:a,error:`Crabbox workload=untrusted requires a fresh lease; --id reuse is forbidden without persisted workload provenance`};const o=commandProvider(e);if(o){const e=canonicalProviderName(o);if(r&&!a.includes(e))return{provider:``,source:`explicit`,workload:r,chain:a,error:`provider=${e} is not eligible for workload=${r}; allowed=${a.join(`,`)||`none`}`};return{provider:o,source:`explicit`,workload:r,chain:a}}const s=envProvider();if(s){const e=canonicalProviderName(s);if(r&&!a.includes(e))return{provider:``,source:`environment`,workload:r,chain:a,error:`provider=${e} is not eligible for workload=${r}; allowed=${a.join(`,`)||`none`}`};return{provider:s,source:`environment`,workload:r,chain:a}}if(r&&hasOption(e,`--id`))return{provider:``,source:`policy`,workload:r,chain:[],error:`reusing a workload-routed lease with --id requires --provider (or CRABBOX_PROVIDER) from the originating route`};if(!r&&shouldPreferAzureForWindows(e,t))return{provider:`azure`,source:`windows-default`,workload:``,chain:[]};if(!r)return{provider:i,source:`config`,workload:``,chain:[]};const c=/* @__PURE__ */ new Map;let l=``;for(const e of a){const t=crabboxProviderReadiness(e,n);c.set(e,t);if(t.ready){l=e;break}}if(!l)return{provider:``,source:`policy`,workload:r,chain:a,readiness:c,error:`no ready provider for workload=${r}`};return{provider:l,source:`policy`,workload:r,chain:a,readiness:c}}function requestedWorkload(e){if(!isWorkloadRoutedCommand(e))return``;const t=workloadOption??process.env.OPENCLAW_CRABBOX_WORKLOAD?.trim()??``;if(!t)return``;return normalizeCrabboxWorkload(t)}function crabboxProviderReadiness(e,t){const n=canonicalProviderName(e);const r=[`doctor`,`--provider`,n];if(t.target)r.push(`--target`,t.target);if(t.target===`windows`&&t.windowsMode)r.push(`--windows-mode`,t.windowsMode);r.push(`--json`);const i=checkedOutput(binary,r,null);const a=parseDoctorResult(i.stdout,n,i.status);const o=[`aws`,`azure`,`daytona`].includes(n);const s=a?.checks.find(e=>e.check===`broker`);const c=!o||s?.status===`ok`;const l=a?.checks.some(e=>e.status===`failed`&&e.details?.class===`broker_auth`)===true;const u=a?.ok===true&&c;const d=i.stderr||(/^[[{]/u.test(i.stdout)?``:i.stdout);const f=a?doctorFailureDiagnostic(a,c):compactDiagnosticText(d);return{ready:u,reason:u?`doctor-ready`:a?`doctor exited ${i.status}${f?`: ${f}`:``}`:`invalid doctor JSON (exit ${i.status})${f?`: ${f}`:``}`,...u?{}:{recovery:`run \`${recoveryCommand(r)}\``},brokerReady:c,brokerAuthFailure:l}}function isDoctorCheck(e){return isRecord(e)&&typeof e.status===`string`&&Boolean(e.status)&&typeof e.check===`string`&&Boolean(e.check)&&(e.message===void 0||typeof e.message===`string`)&&(e.details===void 0||isRecord(e.details)&&Object.values(e.details).every(e=>typeof e===`string`))}function parseDoctorResult(e,t,n){try{const r=JSON.parse(e);if(!isRecord(r)||typeof r.ok!==`boolean`||r.provider!==t||!Array.isArray(r.checks)||(r.ok?n!==0:n!==1))return null;const i=r.checks;if(!i.every(isDoctorCheck)||r.ok!==i.every(e=>![`failed`,`missing`].includes(e.status.trim().toLowerCase())))return null;return r}catch{return null}}function compactDiagnosticText(e,t=500){const n=stripAnsi(e).split(/\r\n?|\n/u).map(sanitizeForLog).join(`
`);const r=redactSupportString(n,{env:process.env,stateDir:``},{maxLength:Number.MAX_SAFE_INTEGER}).replace(/\s+/gu,` `).trim();return r.length<=t?r:`${r.slice(0,t-3)}...`}function doctorFailureDiagnostic(e,t){const n=e.checks.filter(e=>[`failed`,`missing`].includes(e.status.trim().toLowerCase()));const r=n.slice(0,4).map(e=>{const t=[...[`class`,`hint`].flatMap(t=>{const n=e.details?.[t];return n?[`${t}=${compactDiagnosticText(n,80)}`]:[]}),...e.message?[compactDiagnosticText(e.message,160)]:[]].join(` `);return`${compactDiagnosticText(e.check,60)} (${e.status.trim().toLowerCase()})${t?`: ${t}`:``}`});if(n.length>r.length)r.push(`${n.length-r.length} more failed checks omitted`);if(!t&&!n.some(e=>e.check===`broker`))r.push(`broker: required ok check missing`);return r.join(`; `)}function formatProviderReadiness(e){return[...e.entries()].map(([e,t])=>`${e}:${t.ready?`ready`:t.reason}`).join(`,`)}function providerRecoveryAdvice(e){return[...new Set([...e.values()].map(e=>e.recovery).filter(e=>typeof e===`string`&&e.length>0))]}function shouldRequireBrokeredCloud(e,t,n=false){const r=canonicalProviderName(t);if(![`aws`,`azure`,`daytona`].includes(r))return false;if(requestedWorkload(e))return true;if(n&&directCloudOverrideEnabled(t))return false;return e[0]===`run`||e[0]===`warmup`||e[0]===`actions`&&e[1]===`hydrate`}function directCloudOverrideEnabled(e){return canonicalProviderName(e)!==`aws`&&process.env.OPENCLAW_CRABBOX_ALLOW_DIRECT_CLOUD===`1`}function enforceBrokeredCloud(e,t,n,r){if(!shouldRequireBrokeredCloud(e,t,n))return;const i=canonicalProviderName(t);const a=r??crabboxProviderReadiness(i,effectiveTargetContext(e));if(`brokerAuthFailure`in a&&a.brokerAuthFailure){const e=[`[crabbox] provider=${i} requires managed Crabbox broker authentication for OpenClaw proof.`,`[crabbox] ${a.reason}.`,`[crabbox] run \`${recoveryCommand([`login`,`--url`,`https://crabbox.openclaw.ai`])}\`, then retry.`];if(i!==`aws`)e.push(`[crabbox] direct ${i} debugging requires an original \`--provider ${i}\`, no \`--workload\`, and OPENCLAW_CRABBOX_ALLOW_DIRECT_CLOUD=1.`);console.error(e.join(`
`));process.exit(2)}if(!(`brokerReady`in a)||!a.brokerReady){console.error([`[crabbox] provider=${i} failed readiness for OpenClaw proof: ${a.reason}.`,...a.recovery?[`[crabbox] recovery: ${a.recovery}.`]:[]].join(`
`));process.exit(2)}}function optionValue(e,t){return parseCommandInvocation(help.text,e).options.get(commandOptionName(t))?.value??``}function hasOption(e,t){return parseCommandInvocation(help.text,e).options.has(commandOptionName(t))}function commandOptionEnd(e){return parseCommandInvocation(help.text,e).optionEnd}function shouldPreferAzureForWindows(e,t=[]){return[`run`,`warmup`].includes(e[0]??``)&&isWindowsRemoteTarget(e)&&!commandProvider(e)&&!envProvider()&&!hasOption(e,`--id`)&&t.includes(`azure`)}function ensureAzureWindowsProvider(e,t,n=[]){if(t!==`azure`||!shouldPreferAzureForWindows(e,n))return e;const r=commandOptionEnd(e);const i=[...e];i.splice(r,0,`--provider`,`azure`);return i}function ensurePolicyProvider(e,t){if(t.source!==`policy`||!t.provider||commandProvider(e)||envProvider())return e;const n=[...e];const r=commandOptionEnd(n);n.splice(r,0,`--provider`,t.provider);return n}function ensureAwsMacOnDemandMarket(e,t){if(![`run`,`warmup`].includes(e[0]??``)||t!==`aws`||optionValue(e,`--target`)!==`macos`||hasOption(e,`--market`)||hasOption(e,`--id`))return e;const n=commandOptionEnd(e);const r=[...e];r.splice(n,0,`--market`,`on-demand`);return r}function ensureBoatDefaultClass(e,t){if(![`run`,`warmup`].includes(e[0]??``)||canonicalProviderName(t)!==`ascii-box`||[`--class`,`--type`,`--id`].some(t=>hasOption(e,t))||process.env.CRABBOX_DEFAULT_CLASS||process.env.CRABBOX_SERVER_TYPE||process.env.CRABBOX_CONFIG)return e;const n=resolvedCrabboxConfig();if(n?.class!==`standard`||n.serverTypeExplicit!==false)return e;const r=[...e];r.splice(commandOptionEnd(r),0,`--class`,`fast`);return r}function ensureNativeWindowsHydrateJob(e){if(e[0]!==`actions`||e[1]!==`hydrate`||!isNativeWindowsRemoteTarget(e))return e;const t=parseCommandInvocation(help.text,e);const n=t.options.get(`job`);if(n?.value&&n.value!==`hydrate`)return e;const r=[...e];const i=`hydrate-windows-daemon`;if(n){const e=r[n.index]??``;if(e.includes(`=`))r[n.index]=`${e.slice(0,e.indexOf(`=`)+1)}${i}`;else r[n.index+1]=i}else r.splice(t.optionEnd,0,`--job`,i);return r}const localPathRunOptions=/* @__PURE__ */ new Set([`capture-stderr`,`capture-stdout`,`emit-proof`,`env-from-profile`,`script`]);function repoRelativePath(e){if(!e||e===`-`||isAbsolute(e))return e;return resolve(repoRoot,e)}function repoRelativeDownload(e){const t=e.indexOf(`=`);if(t<0)return e;return`${e.slice(0,t+1)}${repoRelativePath(e.slice(t+1))}`}function absolutizeLocalRunPaths(e){if(e[0]!==`run`)return e;const t=[...e];const n=parseCommandInvocation(help.text,t);for(const{index:e,name:r}of n.optionEntries){const i=t[e]??``;const a=r===`download`?repoRelativeDownload:repoRelativePath;if(localPathRunOptions.has(r)||r===`download`){const r=i.indexOf(`=`);if(r>=0)t[e]=`${i.slice(0,r+1)}${a(i.slice(r+1))}`;else if(e+1<n.optionEnd)t[e+1]=a(t[e+1]??``)}}return t}function pathExists(e){try{statSync(e);return true}catch{return false}}function crabboxConfigDir(){if(process.platform===`darwin`)return resolve(homedir(),`Library`,`Application Support`,`crabbox`);if(process.platform===`win32`)return resolve(process.env.APPDATA||resolve(homedir(),`AppData`,`Roaming`),`crabbox`);return resolve(process.env.XDG_CONFIG_HOME||resolve(homedir(),`.config`),`crabbox`)}function userDisplayPath(e){const t=homedir();const n=relative(t,e);if(n&&!n.startsWith(`..`)&&!isAbsolute(n))return`~/${n}`;return e}function blacksmithTestboxPrivateKeyPath(e){const t=process.env.XDG_STATE_HOME;if(t&&!(process.platform===`win32`?/^(?:[a-z]:[\\/]|[\\/]{2}|[\\/]\?\?[\\/][^\\/]+[\\/])/iu.test(t):isAbsolute(t))){console.error(`[crabbox] XDG_STATE_HOME must be absolute for generated lease SSH material`);process.exit(2)}const n=t?join(t,`crabbox`):crabboxConfigDir();return join(n,`testboxes`,e,`id_ed25519`)}function crabboxLeaseClaimPath(e){return resolve(crabboxLeaseClaimsDir(),`${e}.json`)}function crabboxLeaseClaimsDir(){const e=process.env.XDG_STATE_HOME;const t=e?resolve(e,`crabbox`):resolve(crabboxConfigDir(),`state`);return resolve(t,`claims`)}function blacksmithTestboxClaimRepoRoot(e){const t=crabboxLeaseClaimPath(e);if(!pathExists(t))return``;const n=JSON.parse(readFileSync(t,`utf8`));return typeof n.repoRoot===`string`?n.repoRoot:``}function enforceCrabboxOwnedBlacksmithLease(e){if(e[0]!==`run`)return;const t=optionValue(e,`--id`);if(!t)return;if(!t.startsWith(`tbx_`))return;const n=blacksmithTestboxPrivateKeyPath(t);if(!pathExists(n)){console.error([`[crabbox] provider=blacksmith-testbox --id ${t} has no Crabbox SSH key at ${userDisplayPath(n)}.`,`[crabbox] create reusable Testboxes through Crabbox before reusing them: node scripts/crabbox-wrapper.mjs warmup --provider blacksmith-testbox --idle-timeout 15m`,"[crabbox] direct `blacksmith testbox warmup` leases can be used with `blacksmith testbox run`, but Crabbox cannot sync or run them by id."].join(`
`));process.exit(2)}const r=blacksmithTestboxClaimRepoRoot(t);if(r&&r!==repoRoot&&!hasOption(e,`--reclaim`)){console.error(`[crabbox] lease ${t} is claimed by repo ${r}; use --reclaim to claim it for ${repoRoot}`);process.exit(2)}}function restoreTemporaryLeaseClaimPath(e){const t=readFileSync(e,`utf8`);const n=JSON.parse(t);if(!n||typeof n!==`object`||n.repoRoot!==childCwd)return;if(n.provider===`ascii-box`&&[`ascii_box_deletion_completed`,`ascii_box_deletion_operation`,`ascii_box_deletion_operation_binding`].some(e=>Object.hasOwn(n.labels??{},e)))throw new Error(`Boat deletion receipts bind the temporary checkout; stop the lease there before removing it`);n.repoRoot=repoRoot;const r=`${e}.tmp-${process.pid}-${Date.now()}`;try{writeFileSync(r,`${JSON.stringify(n)}\n`,{encoding:`utf8`,mode:384});renameSync(r,e)}finally{rmSync(r,{force:true})}}function restoreTemporaryLeaseClaim(e,t){if(childCwd===repoRoot)return true;const n=e[0]===`run`?optionValue(e,`--id`)||optionValue(e,`--lease-id`):``;const r=((canonicalProvider===`aws`||canonicalProvider===`ascii-box`)&&!/^cbx_[a-f0-9]{12}$/u.test(n)?``:n)||t;const i=e[0]===`warmup`||e[0]===`run`&&(canonicalProvider===`aws`||canonicalProvider===`ascii-box`||n||hasOption(e,`--keep`)||hasOption(e,`--keep-on-failure`));let a=[];if(r)a=[crabboxLeaseClaimPath(r)];else if(i)try{const e=crabboxLeaseClaimsDir();if(pathExists(e))a=readdirSync(e).filter(e=>e.endsWith(`.json`)&&(![`aws`,`ascii-box`].includes(canonicalProvider)||/^cbx_[a-f0-9]{12}\.json$/u.test(e))).map(t=>resolve(e,t))}catch(e){console.error(`[crabbox] warning: failed to inspect temporary lease claims: ${e instanceof Error?e.message:String(e)}`);return false}else return true;let o=true;for(const e of a){if(!pathExists(e))continue;try{restoreTemporaryLeaseClaimPath(e)}catch(e){o=false;console.error(`[crabbox] warning: failed to restore temporary lease claim: ${e instanceof Error?e.message:String(e)}`)}}return o}function observeLeaseTimingJSONLine(e){const t=e.trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return;try{const e=JSON.parse(t);if(canonicalProviderName(e?.provider)===canonicalProvider&&typeof e.leaseId===`string`&&(canonicalProvider===`aws`||canonicalProvider===`ascii-box`?/^cbx_[a-f0-9]{12}$/u.test(e.leaseId):/^tbx_[a-zA-Z0-9_-]+$/u.test(e.leaseId)))capturedLeaseId=e.leaseId}catch{}}function shellQuote(e){const t=e;if(t===``)return`''`;if(/^[A-Za-z0-9_./:=@%+-]+$/u.test(t))return t;return`'${t.replaceAll(`'`,`'\\''`)}'`}function shellJoin(e){return e.map(shellQuote).join(` `)}function powershellQuote(e){const t=e;if(t===``)return`''`;if(/^[A-Za-z0-9_./:=%+-]+$/u.test(t))return t;return`'${t.replaceAll(`'`,`''`)}'`}function powershellJoin(e){return e.map(powershellQuote).join(` `)}function isLocalContainerProvider(e){return[`local-container`,`docker`,`container`,`local-docker`].includes(e)}function replaceRunPayload(e,t){const n=[...e.args];n.splice(e.start,n.length-e.start,...t);return n}function renderRunShellCommand(e,t=shellJoin){return e.options.has(`shell`)&&e.commandArgs.length===1?e.commandArgs[0]??``:t(e.commandArgs)}function replaceRunCommandWithShell(e,t){let n=e;if(!n.options.has(`shell`)){const e=[...n.args];e.splice(n.optionEnd,0,`--shell`);n=parseCommandInvocation(help.text,e)}return replaceRunPayload(n,[t])}function normalizedCommandWords(e){const t=e.length===1?(e[0]??``).split(/\s+/u):[...e];while(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]??``))t.shift();return t.map(e=>e.replace(/^['"]|['";|&()]+$/g,``))}function commandRuntimeEntrypoint(e){if(e.length===1){for(const t of shellCommandWordCandidates(e[0]??``)){const e=commandWordsRuntimeEntrypoint(t);if(e)return e}return``}const t=commandWordsRuntimeEntrypoint(normalizedCommandWords(e));if(t)return t;return``}function commandWordsRuntimeEntrypoint(e){let t=e;t=normalizeExecutableWords(t);const n=(t[0]??``).split(`/`).pop()??``;if(jsRuntimeEntrypoints.has(n))return n;const r=shellInlineCommand(t);if(!r)return``;for(const e of shellCommandWordCandidates(r)){const t=commandWordsRuntimeEntrypoint(e);if(t)return t}return``}function commandWordsShellEntrypoint(e){const t=shellWordBasename(normalizeExecutableWords(e)[0]);return shellInlineCommandInterpreters.has(t)?t:``}function commandNeedsAwsMacosPackageManager(e,t={}){if(isChangedGateCommand(e))return true;if(commandNeedsEntrypoint(e,awsMacosCorepackEntrypoints,t))return true;if(e.length===1)return shellCommandWordCandidates(e[0]??``).some(e=>commandWordsNeedAwsMacosPackageManager(e,t));return commandWordsNeedAwsMacosPackageManager(normalizedCommandWords(e),t)}function commandNeedsAwsMacosBun(e){return commandNeedsEntrypoint(e,awsMacosBunEntrypoints)}function commandNeedsAwsMacosSwiftToolchain(e){if(e.length===1)return shellCommandWordCandidates(e[0]??``).some(commandWordsNeedAwsMacosSwiftToolchain);return commandWordsNeedAwsMacosSwiftToolchain(normalizedCommandWords(e))}function commandWordsNeedAwsMacosSwiftToolchain(e){let t=e;t=normalizeExecutableWords(t);const n=(t[0]??``).split(`/`).pop()??``;if(isSupportedSystemEnvCommand(n)){const e=[...t];if(stripEnvCommandOptions(e,{canShimIgnoreEnvironment:true}))return commandWordsNeedAwsMacosSwiftToolchain(e)}if(awsMacosSwiftEntrypoints.has(n))return true;if(n===`pnpm`){const e=t[1]===`run`?t[2]:t[1];if(awsMacosSwiftScriptTargets.has(e??``))return true}if(isScriptTarget(t[0],awsMacosSwiftScriptTargets))return true;if(commandWordsRunScriptTarget(t,awsMacosSwiftScriptTargets))return true;const r=shellInlineCommand(t);if(!r)return false;return shellCommandWordCandidates(r).some(commandWordsNeedAwsMacosSwiftToolchain)}function commandWordsNeedAwsMacosPackageManager(e,t={}){let n=e;const r=shellWordBasename(normalizedCommandWords(e)[0]);const i=t.canShimIgnoreEnvironment!==false;n=normalizeExecutableWords(n);if(isSupportedSystemEnvCommand((n[0]??``).split(`/`).pop()??``)){const e=[...n];if(stripEnvCommandOptions(e,{canShimIgnoreEnvironment:i&&isSupportedSystemEnvCommand(r)}))return commandWordsNeedAwsMacosPackageManager(e,t)}if(isScriptTarget(n[0],awsMacosPackageManagerScriptTargets))return true;if(commandWordsRunScriptTarget(n,awsMacosPackageManagerScriptTargets))return true;const a=shellInlineCommand(n);if(!a)return false;return shellCommandWordCandidates(a).some(e=>commandWordsNeedAwsMacosPackageManager(e,t))}function isScriptTarget(e,t){if(!e)return false;const n=e.replace(/^\.\//u,``);return t.has(n)||t.has(n.split(`/`).pop()??``)}function commandWordsRunScriptTarget(e,t){const n=(e[0]??``).split(`/`).pop()??``;if(!shellInlineCommandInterpreters.has(n))return false;for(let n=1;n<e.length;n+=1){const r=e[n]??``;if(!r)return false;if(r===`--`)continue;if(r===`-c`||/^-[^-]*c/u.test(r))return false;if(shellInlineCommandOptionConsumesNextValue(r)){n+=1;continue}if(r.startsWith(`-`)||r.startsWith(`+`))continue;return isScriptTarget(r,t)}return false}function commandNeedsEntrypoint(e,t,n={}){if(e.length===1)return shellCommandWordCandidates(e[0]??``).some(e=>commandWordsNeedEntrypoint(e,t,n));return commandWordsNeedEntrypoint(normalizedCommandWords(e),t,n)}function commandWordsNeedEntrypoint(e,t,n={}){let r=e;r=normalizeExecutableWords(r,n);const i=(r[0]??``).split(`/`).pop()??``;if(t.has(i))return true;const a=shellInlineCommand(r);if(!a)return false;return shellCommandWordCandidates(a).some(e=>commandWordsNeedEntrypoint(e,t,n))}function isChangedGateCommand(e){if(e.length===1)return shellCommandWordCandidates(e[0]??``).some(e=>isChangedGateCommandWords(e));return isChangedGateCommandWords(normalizedCommandWords(e),{canShimIgnoreEnvironment:shellWordBasename(e[0])===`env`})}function changedGateBases(e){const t=e.length===1?shellCommandWordCandidates(e[0]??``):[normalizedCommandWords(e)];const n=[];for(const r of t)n.push(...changedGateBasesFromWords(r,{canShimIgnoreEnvironment:shellWordBasename(e[0])===`env`}));return n}function changedGateBasesFromWords(e,t={}){const n=normalizeExecutableWords(e,t);if(isCheckGateWords(n)){for(let e=0;e<n.length;e+=1){const t=n[e]??``;if(t===`--base`)return[n[e+1]||`origin/main`];if(t.startsWith(`--base=`))return[t.slice(7)||`origin/main`]}return[`origin/main`]}const r=shellInlineCommand(n);if(!r)return[];const i=[];for(const e of shellCommandWordCandidates(r))i.push(...changedGateBasesFromWords(e));return i}function isChangedGateCommandWords(e,t={}){let n=e;n=normalizeExecutableWords(n,t);if(isChangedGateWords(n))return true;const r=shellInlineCommand(n);return r?shellCommandWordCandidates(r).some(e=>isChangedGateCommandWords(e)):false}function isChangedGateWords(e){let t=e;t=normalizeExecutableWords(t);if(t[0]===`corepack`)t.shift();return t[0]===`pnpm`&&t[1]===`check:changed`||t[0]===`pnpm`&&t[1]===`run`&&t[2]===`check:changed`||nodeScriptWord(t)?.endsWith(`scripts/check-changed.mjs`)}function isCheckGateWords(e){if(isChangedGateWords(e))return true;const t=normalizeExecutableWords(e);if(t[0]===`corepack`)t.shift();return t[0]===`pnpm`&&t[1]===`check`||t[0]===`pnpm`&&t[1]===`run`&&t[2]===`check`||nodeScriptWord(t)?.endsWith(`scripts/check.mts`)}function nodeScriptWord(e){if(shellWordBasename(e[0])!==`node`)return``;for(let t=1;t<e.length;t+=1){const n=e[t]??``;if(!n)return``;if(n===`--`)return e[t+1]??``;if(nodeOptionsWithoutScript.has(n)||nodeOptionsWithoutScriptPrefix(n))return``;const r=nodeOptionValueModeBeforeScript(n);if(r===`next`){t+=1;continue}if(r===`inline`)continue;if(n.startsWith(`-`)&&n!==`-`)continue;return n}return``}function nodeOptionsWithoutScriptPrefix(e){return e.startsWith(`--eval=`)||e.startsWith(`--print=`)}function nodeOptionValueModeBeforeScript(e){if(nodeOptionsWithNextValueBeforeScript.has(e))return`next`;const t=e.indexOf(`=`);if(t>0&&nodeOptionsWithNextValueBeforeScript.has(e.slice(0,t)))return`inline`;return``}function shellInlineCommand(e){const t=shellWordBasename(e[0]);if(!shellInlineCommandInterpreters.has(t))return``;for(let t=1;t<e.length;t+=1){const n=e[t]??``;if(n===`--`)return``;if(!n.startsWith(`-`)&&!n.startsWith(`+`))return``;if(n===`-c`||/^-[^-]*c/u.test(n))return e[t+1]??``;if(shellInlineCommandOptionConsumesNextValue(n))t+=1}return``}function shellInlineCommandOptionConsumesNextValue(e){return shellInlineCommandOptionsWithNextValue.has(e)||/^[+-][^-+]*[oO]$/u.test(e)}function shellCommandWordCandidates(e){return shellCommandSegments(stripHeredocBodies(e.replace(/\\\r?\n/gu,` `)))}function pushShellCandidate(e,t){const n=normalizedShellSegmentWords(t);if(n.length>0)e.push(n)}function normalizedShellSegmentWords(e){const t=e.trim().replace(/^[({]\s*/u,``);if(!t||t.startsWith(`#`))return[];const n=normalizedCommandWords(splitShellWords(t));while(shellControlCommandPrefixes.has(n[0]??``))n.shift();return normalizedCommandWords(stripShellExecutionPrefixes(normalizedCommandWords(n)))}function normalizeExecutableWords(e,t={}){return normalizedCommandWords(stripShellExecutionPrefixes(e,t))}function stripShellExecutionPrefixes(e,t={}){let n=e;n=[...n];let r=Boolean(t.canShimIgnoreEnvironment);for(;;){const e=shellWordBasename(n[0]);if(shellCommandExecutionPrefixes.has(e)){n.shift();continue}if(e===`command`){n.shift();if(!stripCommandBuiltinOptions(n))return n;continue}if(e===`env`){if(!stripEnvCommandOptions(n,{canShimIgnoreEnvironment:r}))return n;r=false;continue}if(e===`time`){n.shift();stripTimeOptions(n);continue}if(e===`timeout`){stripTimeoutOptions(n);continue}return n}}function stripEnvCommandOptions(e,{canShimIgnoreEnvironment:t=true}={}){const n=[...e];const r=e.shift()??``;const i=t&&isSupportedSystemEnvCommand(r);let a=false;for(;;){const t=e[0]??``;if(!t){e.splice(0,e.length,...n);return false}if(t===`--`){e.shift();return true}if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)){e.shift();continue}if(t===`-S`||t===`--split-string`){if(a){e.splice(0,e.length,...n);return false}e.shift();const t=splitShellWords(e.shift()??``);e.unshift(...t);return e.length>0}if(t.startsWith(`-S`)&&t!==`-S`){if(a){e.splice(0,e.length,...n);return false}e.shift();e.unshift(...splitShellWords(t.slice(2)));return e.length>0}if(t.startsWith(`--split-string=`)){if(a){e.splice(0,e.length,...n);return false}e.shift();e.unshift(...splitShellWords(t.slice(15)));return e.length>0}if(t===`-i`||t===`--ignore-environment`){if(!i){e.splice(0,e.length,...n);return false}a=true;e.shift();continue}if(t===`-u`||t===`--unset`||t===`-C`||t===`--chdir`){e.shift();if(e[0])e.shift();continue}if(t.startsWith(`--unset=`)||t.startsWith(`--chdir=`)){e.shift();continue}if(t.startsWith(`-`)&&t!==`-`){if(t.includes(`i`)){if(!i){e.splice(0,e.length,...n);return false}a=true}e.shift();continue}if(a&&!i){e.splice(0,e.length,...n);return false}return true}}function isSupportedSystemEnvCommand(e){return e===`env`||e===`/usr/bin/env`}function shellWordBasename(e){return(e??``).split(`/`).pop()??``}function stripCommandBuiltinOptions(e){for(;;){if(e[0]===`--`){e.shift();return true}if(e[0]===`-p`){e.shift();continue}return e[0]!==`-v`&&e[0]!==`-V`}}function stripTimeOptions(e){while((e[0]??``).startsWith(`-`)){if(e[0]===`--`){e.shift();return}e.shift()}}function stripTimeoutOptions(e){e.shift();for(;;){const t=e[0]??``;if(!t)return;if(t===`--`){e.shift();break}if(t===`-k`||t===`--kill-after`||t===`-s`||t===`--signal`){e.shift();if(e[0])e.shift();continue}if(t.startsWith(`--kill-after=`)||t.startsWith(`--signal=`)){e.shift();continue}if(t.startsWith(`-`)&&t!==`-`){e.shift();continue}break}if(e[0])e.shift()}function splitShellWords(e){const t=[];let n=``;let r=``;let i=false;for(const a of e){if(i){n+=a;i=false;continue}if(a===`\\`&&r!==`'`){i=true;continue}if(r){if(a===r)r=``;else n+=a;continue}if(a===`'`||a===`"`){r=a;continue}if(/\s/u.test(a)){if(n){t.push(n);n=``}continue}n+=a}if(n)t.push(n);return t}function stripHeredocBodies(e){const t=e.split(`
`);const n=[];const r=[];for(const e of t){if(r.length>0){const t=r[0];if(!t)continue;if((t.stripTabs?e.replace(/^\t+/u,``):e)===t.delimiter)r.shift();else if(t.expand)n.push(...extractCommandSubstitutionBodies(e));continue}n.push(e);r.push(...lineHeredocDelimiters(e))}return n.join(`
`)}function lineHeredocDelimiters(e){const t=[];let n=``;let r=false;for(let i=0;i<e.length;i+=1){const a=e[i]??``;const o=e[i+1]??``;if(r){r=false;continue}if(a===`\\`&&n!==`'`){r=true;continue}if(n){if(a===n)n=``;continue}if(a===`'`||a===`"`){n=a;continue}if(a!==`<`||o!==`<`||e[i+2]===`<`)continue;let s=i+2;const c=e[s]===`-`;if(c)s+=1;while(/\s/u.test(e[s]??``))s+=1;const l=readHeredocDelimiter(e,s);if(l.delimiter){t.push({delimiter:l.delimiter,stripTabs:c,expand:!l.quoted});i=l.endIndex}}return t}function readHeredocDelimiter(e,t){let n=``;let r=``;let i=false;let a=false;let o=t;for(;o<e.length;o+=1){const t=e[o]??``;if(i){n+=t;i=false;continue}if(t===`\\`&&r!==`'`){a=true;i=true;continue}if(r){if(t===r)r=``;else n+=t;continue}if(t===`'`||t===`"`){a=true;r=t;continue}if(/\s/u.test(t)||/[;&|()<>]/u.test(t))break;n+=t}return{delimiter:n,endIndex:Math.max(t,o),quoted:a}}function extractCommandSubstitutionBodies(e){const t=[];let n=false;for(let r=0;r<e.length;r+=1){const i=e[r];const a=e[r+1]??``;if(n){n=false;continue}if(i===`\\`){n=true;continue}if(i===`$`&&a===`(`&&e[r+2]!==`(`){const n=readCommandSubstitution(e,r+2);t.push(n.content);r=n.endIndex}}return t}function shellCommandSegments(e){const t=[];let n=``;let r=``;let i=false;let a=false;let o=false;for(let s=0;s<e.length;s+=1){const c=e[s];const l=e[s+1]??``;if(i){n+=c;i=false;continue}if(c===`\\`&&r!==`'`){n+=c;i=true;continue}if(r){if(r===`"`&&c===`$`&&l===`(`&&e[s+2]!==`(`){const r=readCommandSubstitution(e,s+2);t.push(...shellCommandWordCandidates(r.content));s=r.endIndex;n+=`$()`;continue}if(c===r)r=``;n+=c;continue}if(c===`'`||c===`"`){r=c;n+=c;continue}if(c===`#`&&(n.trim()===``||/\s$/u.test(n))){s=skipUntilNewline(e,s);pushShellCandidate(t,n);n=``;continue}if(c===`$`&&l===`(`&&e[s+2]!==`(`){const r=readCommandSubstitution(e,s+2);t.push(...shellCommandWordCandidates(r.content));s=r.endIndex;n+=`$()`;continue}if(n.trim()===``&&startsShellReservedWord(e,s,`case`)){pushShellCandidate(t,n);n=``;a=true;o=true;s+=3;continue}if(a&&n.trim()===``&&startsShellReservedWord(e,s,`esac`)){pushShellCandidate(t,n);n=``;a=false;o=false;s+=3;continue}if(a&&o){if(c===`)`){n=``;o=false;continue}n+=c;continue}if(a&&c===`;`&&l===`;`){pushShellCandidate(t,n);n=``;o=true;s+=1;continue}if(c===`
`||c===`;`||c===`)`){pushShellCandidate(t,n);n=``;continue}if(c===`&`&&l===`&`||c===`|`&&l===`|`){pushShellCandidate(t,n);n=``;s+=1;continue}if(c===`&`&&l!==`>`&&e[s-1]!==`>`){pushShellCandidate(t,n);n=``;continue}if(c===`|`){pushShellCandidate(t,n);n=``;if(l===`&`)s+=1;continue}n+=c}pushShellCandidate(t,n);return t}function readCommandSubstitution(e,t){let n=1;let r=``;let i=false;let a=false;let o=false;let s=``;for(let c=t;c<e.length;c+=1){const t=e[c];const l=e[c+1]??``;if(i){s+=t;i=false;continue}if(t===`\\`&&r!==`'`){s+=t;i=true;continue}if(r){if(t===r)r=``;s+=t;continue}if(t===`'`||t===`"`){r=t;s+=t;continue}if(!a&&startsShellToken(e,c,`case`)){a=true;o=true}else if(a&&startsShellToken(e,c,`esac`)){a=false;o=false}if(t===`$`&&l===`(`){n+=1;s+=`$(`;c+=1;continue}if(t===`(`){n+=1;s+=t;continue}if(a&&t===`;`&&l===`;`){o=true;s+=`;;`;c+=1;continue}if(a&&o&&n===1&&t===`)`){o=false;s+=t;continue}if(t===`)`){n-=1;if(n===0)return{content:s,endIndex:c}}s+=t}return{content:s,endIndex:e.length-1}}function startsShellReservedWord(e,t,n){if(!e.startsWith(n,t))return false;const r=e[t+n.length]??``;return!r||/\s|[;&|()<>]/u.test(r)}function startsShellToken(e,t,n){if(!e.startsWith(n,t))return false;const r=e[t-1]??``;const i=e[t+n.length]??``;return(!r||/\s|[;&|()<>]/u.test(r))&&(!i||/\s|[;&|()<>]/u.test(i))}function skipUntilNewline(e,t){const n=e.indexOf(`
`,t);return n<0?e.length-1:n}function changedGateBaseForCommand(e){const t=[...new Set(changedGateBases(e))];if(t.length>1)throw new Error(`remote changed-gate sync requires one base; received: ${t.join(`, `)}`);const n=t[0]??`origin/main`;const r=remoteAliasForChangedGateBase(n);const i=/^[a-f0-9]{40}$/u.test(n);if(n!==`origin/main`&&!r&&!i)throw new Error(`remote changed-gate sync requires an exact origin/<branch> or full commit SHA base; received: ${n}`);const a=n;const o=gitOutput([`merge-base`,a,`HEAD`]);if(o.status===0&&o.stdout){if(i&&o.stdout!==a)throw new Error(`explicit changed-gate commit must be an ancestor of HEAD: ${a}`);return{remoteAlias:r,resolvedBase:o.stdout}}if(a!==`origin/main`)throw new Error(`could not resolve explicit changed-gate base: ${a}`);return{remoteAlias:``,resolvedBase:`origin/main`}}function remoteAliasForChangedGateBase(e){if(e===`origin/main`||!e.startsWith(`origin/`))return``;const t=`refs/remotes/${e}`;return gitOutput([`check-ref-format`,t]).status===0?t:``}function injectRemoteChangedGateEnvironment(e,t){if(e.args[0]!==`run`||isNativeWindowsRemoteTarget(e.args))return e.args;if(e.start<0||!t.changedGate)return e.args;return replaceRunPayload(e,e.options.has(`shell`)&&e.commandArgs.length===1?[markShellChangedGateAsRemoteChild(e.commandArgs[0]??``)]:markDirectChangedGateAsRemoteChild(e.commandArgs))}function markShellChangedGateAsRemoteChild(e){return`export ${remoteChangedGateEnv.join(` `)}; ${e}`}function markDirectChangedGateAsRemoteChild(e){const t=remoteChangedGateEnv.filter(t=>!e.includes(t));if(t.length===0)return e;const n=[...e];if(shellWordBasename(n[0])!==`env`)return[`env`,...t,...n];n.splice(envAssignmentInsertIndex(n),0,...t);return n}function envAssignmentInsertIndex(e){let t=1;for(;;){const n=e[t]??``;if(!n)return 1;if(n===`--`)return t+1;if(n===`-S`||n===`--split-string`||n.startsWith(`-S`)&&n!==`-S`)return t;if(n===`-u`||n===`--unset`||n===`-C`||n===`--chdir`){t+=2;continue}if(n.startsWith(`--unset=`)||n.startsWith(`--chdir=`)){t+=1;continue}if(n.startsWith(`-`)&&n!==`-`){t+=1;continue}return t}}function isWindowsRemoteTarget(e){return effectiveTargetContext(e).target===`windows`}function isNativeWindowsRemoteTarget(e){const t=effectiveTargetContext(e);return t.target===`windows`&&t.windowsMode!==`wsl2`}function isAwsMacosRemoteTarget(e,t){return e[0]===`run`&&t===`aws`&&optionValue(e,`--target`)===`macos`}function isBrokeredWsl2RemoteTarget(e,t){const n=canonicalProviderName(t);return e[0]===`run`&&(n===`aws`||n===`azure`)&&isWindowsRemoteTarget(e)&&effectiveTargetContext(e).windowsMode===`wsl2`}function isHydratedNativeWindowsProvider(e){return e===`aws`||e===`azure`}function remoteWindowsHydratedNodeModulesBootstrap(){return[`$openclawModulesDir = if ($env:CRABBOX_PNPM_MODULES_DIR) { $env:CRABBOX_PNPM_MODULES_DIR } else { $env:PNPM_CONFIG_MODULES_DIR }`,`if ($openclawModulesDir) {`,`if (-not (Test-Path $openclawModulesDir)) { throw "hydrated pnpm modules directory does not exist: $openclawModulesDir" }`,`$openclawWorkspaceModules = Join-Path (Get-Location).Path "node_modules"`,`$openclawSelfModules = Join-Path $openclawModulesDir "node_modules"`,`if (-not (Test-Path $openclawSelfModules)) { cmd /c mklink /J "$openclawSelfModules" "$openclawModulesDir" | Out-Host; if ($LASTEXITCODE -ne 0) { throw "failed to link hydrated pnpm node_modules" } }`,`if (-not (Test-Path $openclawWorkspaceModules)) { cmd /c mklink /J "$openclawWorkspaceModules" "$openclawModulesDir" | Out-Host; if ($LASTEXITCODE -ne 0) { throw "failed to link workspace node_modules" } }`,`}`].join(`; `)}function injectRemoteWindowsHydratedNodeModulesBootstrap(e,t,n){if(e.args[0]!==`run`||!isHydratedNativeWindowsProvider(n)||!isNativeWindowsRemoteTarget(e.args)||!e.options.has(`id`)||!t.runtimeEntrypoint)return e.args;if(e.start<0)return e.args;return replaceRunCommandWithShell(e,`${remoteWindowsHydratedNodeModulesBootstrap()}; ${renderRunShellCommand(e,powershellJoin)}`)}function remotePosixJsEnvBootstrap(e=false){return[...e?['export COREPACK_HOME="${COREPACK_HOME:-$tool_root/corepack}";','export PNPM_HOME="${PNPM_HOME:-$tool_root/pnpm-home}";',`mkdir -p "$COREPACK_HOME" "$PNPM_HOME" || return 1;`,`export PATH="$PNPM_HOME:$PATH";`,`corepack enable --install-directory "$PNPM_HOME" || return 1;`]:[],`openclaw_crabbox_env() {`,`openclaw_env_args=();`,`openclaw_env_ignore=0;`,`openclaw_env_path_seen=0;`,`while [ "$#" -gt 0 ]; do`,`case "$1" in`,`-i|--ignore-environment) openclaw_env_ignore=1; openclaw_env_args+=("$1"); shift ;;`,'-S|--split-string|-S*|--split-string=*) command env "${openclaw_env_args[@]}" "$@"; return ;;',`-[!-]*i*) openclaw_env_ignore=1; openclaw_env_args+=("$1"); shift ;;`,`-u|--unset|-C|--chdir) openclaw_env_args+=("$1"); shift; if [ "$#" -gt 0 ]; then openclaw_env_args+=("$1"); shift; fi ;;`,`--unset=*|--chdir=*) openclaw_env_args+=("$1"); shift ;;`,'PATH=*) if [ "$openclaw_env_ignore" = "1" ]; then openclaw_env_args+=("PATH=${OPENCLAW_CRABBOX_BOOTSTRAP_PATH:-$PATH}:${1#PATH=}"); else openclaw_env_args+=("$1"); fi; openclaw_env_path_seen=1; shift ;;',`[A-Za-z_]*=*) openclaw_env_args+=("$1"); shift ;;`,`--) openclaw_env_args+=("--"); shift; break ;;`,`*) break ;;`,`esac;`,`done;`,'if [ "$openclaw_env_ignore" = "1" ] && [ "$openclaw_env_path_seen" = "0" ]; then openclaw_env_args+=("PATH=${OPENCLAW_CRABBOX_BOOTSTRAP_PATH:-$PATH}"); fi;','command env "${openclaw_env_args[@]}" "$@";',`};`]}function remoteAwsMacosJsBootstrap({packageManager:e=false,bun:t=false,sourceBootstrap:n=``}={}){const r=[`openclaw_crabbox_bootstrap_macos_js() {`,'tool_root="${OPENCLAW_CRABBOX_MACOS_TOOLCHAIN_DIR:-$HOME/.openclaw-crabbox-toolchain}";',`node_version=${shellQuote(process.env.OPENCLAW_CRABBOX_MACOS_NODE_VERSION?.trim()||`24.22.1`)};`,`arch="$(uname -m)";`,`case "$arch" in arm64) node_arch=arm64 ;; x86_64) node_arch=x64 ;; *) echo "unsupported macOS arch: $arch" >&2; return 2 ;; esac;`,'macos_locale="${OPENCLAW_CRABBOX_MACOS_LOCALE:-en_US.UTF-8}";','case "${LANG:-}" in C.UTF-8|C.utf8|c.UTF-8|c.utf8) export LANG="$macos_locale" ;; esac;','case "${LC_ALL:-}" in C.UTF-8|C.utf8|c.UTF-8|c.utf8) export LC_ALL="$macos_locale" ;; esac;','case "${LC_CTYPE:-}" in C.UTF-8|C.utf8|c.UTF-8|c.utf8) export LC_CTYPE="$macos_locale" ;; esac;','if [ -z "${TMPDIR:-}" ]; then export TMPDIR="/tmp"; fi;',`if [ ! -d "$TMPDIR" ]; then mkdir -p "$TMPDIR" 2>/dev/null || export TMPDIR="/tmp"; fi;`,`if [ ! -d "$TMPDIR" ]; then echo "usable TMPDIR not found: $TMPDIR" >&2; return 1; fi;`,'node_dir="$tool_root/node-v${node_version}-darwin-${node_arch}";',`ready_marker="$node_dir/.openclaw-crabbox-node-ready";`,`export PATH="$node_dir/bin:$PATH";`,`if [ ! -x "$node_dir/bin/node" ] || [ ! -f "$ready_marker" ]; then`,`mkdir -p "$tool_root" || { status=$?; return "$status"; };`,'install_lock="$tool_root/.node-${node_version}-${node_arch}.lock";',`lock_acquired=0;`,`lock_deadline=$((SECONDS + 300));`,`while true; do`,`if mkdir "$install_lock" 2>/dev/null; then lock_acquired=1; printf "%s\\n" "$$" >"$install_lock/pid" || { status=$?; rm -rf "$install_lock"; return "$status"; }; break; fi;`,`if [ -x "$node_dir/bin/node" ] && [ -f "$ready_marker" ]; then break; fi;`,`if [ "$SECONDS" -ge "$lock_deadline" ]; then`,`lock_pid="$(cat "$install_lock/pid" 2>/dev/null || true)";`,`if [ -n "$lock_pid" ] && kill -0 "$lock_pid" 2>/dev/null; then echo "timed out waiting for active macOS Node toolchain install lock: $install_lock pid=$lock_pid" >&2; return 1; fi;`,`echo "reclaiming stale macOS Node toolchain install lock: $install_lock" >&2;`,`rm -rf "$install_lock" || return 1;`,`lock_deadline=$((SECONDS + 300));`,`fi;`,`sleep 1;`,`done;`,`release_install_lock() { if [ "$lock_acquired" = "1" ]; then rm -rf "$install_lock" 2>/dev/null || true; fi; };`,`if [ ! -x "$node_dir/bin/node" ] || [ ! -f "$ready_marker" ]; then`,`tmp_dir="$(mktemp -d)" || { release_install_lock; return 1; };`,'pkg="node-v${node_version}-darwin-${node_arch}.tar.gz";','base_url="https://nodejs.org/dist/v${node_version}";',`curl -fsSL --connect-timeout 10 --max-time 300 --retry 2 --retry-delay 2 -o "$tmp_dir/$pkg" "$base_url/$pkg" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`curl -fsSL --connect-timeout 10 --max-time 60 --retry 2 --retry-delay 2 -o "$tmp_dir/SHASUMS256.txt" "$base_url/SHASUMS256.txt" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`(cd "$tmp_dir" && grep " $pkg$" SHASUMS256.txt | shasum -a 256 -c -) || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`rm -rf "$node_dir" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`tar -xzf "$tmp_dir/$pkg" -C "$tool_root" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`touch "$ready_marker" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`rm -rf "$tmp_dir";`,`fi;`,`release_install_lock;`,`fi;`,`node --version >&2 || return 1;`,...remotePosixJsEnvBootstrap(e),...n?[`${n} || return $?;`]:[]];if(e)r.push(`pnpm --version >&2;`);if(t)r.push(`bun_version=${shellQuote(awsMacosBunVersion)};`,'bun_root="$tool_root/bun-v${bun_version}";',`bun_ready_marker="$bun_root/.openclaw-crabbox-bun-ready";`,`export PATH="$bun_root/bin:$PATH";`,`if [ ! -x "$bun_root/bin/bun" ] || [ ! -f "$bun_ready_marker" ]; then`,`mkdir -p "$tool_root" || { status=$?; return "$status"; };`,'bun_install_lock="$tool_root/.bun-${bun_version}.lock";',`bun_lock_acquired=0;`,`bun_lock_deadline=$((SECONDS + 300));`,`while true; do`,`if mkdir "$bun_install_lock" 2>/dev/null; then bun_lock_acquired=1; printf "%s\\n" "$$" >"$bun_install_lock/pid" || { status=$?; rm -rf "$bun_install_lock"; return "$status"; }; break; fi;`,`if [ -x "$bun_root/bin/bun" ] && [ -f "$bun_ready_marker" ]; then break; fi;`,`if [ "$SECONDS" -ge "$bun_lock_deadline" ]; then`,`bun_lock_pid="$(cat "$bun_install_lock/pid" 2>/dev/null || true)";`,`if [ -n "$bun_lock_pid" ] && kill -0 "$bun_lock_pid" 2>/dev/null; then echo "timed out waiting for active macOS Bun install lock: $bun_install_lock pid=$bun_lock_pid" >&2; return 1; fi;`,`echo "reclaiming stale macOS Bun install lock: $bun_install_lock" >&2;`,`rm -rf "$bun_install_lock" || return 1;`,`bun_lock_deadline=$((SECONDS + 300));`,`fi;`,`sleep 1;`,`done;`,`release_bun_install_lock() { if [ "$bun_lock_acquired" = "1" ]; then rm -rf "$bun_install_lock" 2>/dev/null || true; fi; };`,`if [ ! -x "$bun_root/bin/bun" ] || [ ! -f "$bun_ready_marker" ]; then`,`rm -rf "$bun_root" || { status=$?; release_bun_install_lock; return "$status"; };`,`mkdir -p "$bun_root" || { status=$?; release_bun_install_lock; return "$status"; };`,'npm install --global --prefix "$bun_root" --fetch-timeout=120000 --fetch-retries=2 --fetch-retry-mintimeout=2000 --fetch-retry-maxtimeout=15000 "bun@${bun_version}" || { status=$?; release_bun_install_lock; return "$status"; };',`touch "$bun_ready_marker" || { status=$?; release_bun_install_lock; return "$status"; };`,`fi;`,`release_bun_install_lock;`,`fi;`,`bun --version >&2 || return 1;`);r.push(`export OPENCLAW_CRABBOX_BOOTSTRAP_PATH="$PATH";`);r.push(`};`,`openclaw_crabbox_bootstrap_macos_js`);return r.join(` `)}function remoteWsl2JsBootstrap({packageManager:e=false,sourceBootstrap:t=``}={}){const n=[`openclaw_crabbox_bootstrap_wsl2_js() {`,'tool_root="${OPENCLAW_CRABBOX_WSL2_TOOLCHAIN_DIR:-$HOME/.openclaw-crabbox-toolchain}";',`node_version=${shellQuote(process.env.OPENCLAW_CRABBOX_WSL2_NODE_VERSION?.trim()||`24.22.1`)};`,`arch="$(uname -m)";`,`case "$arch" in arm64|aarch64) node_arch=arm64 ;; x86_64|amd64) node_arch=x64 ;; *) echo "unsupported WSL2 arch: $arch" >&2; return 2 ;; esac;`,'if [ -z "${TMPDIR:-}" ]; then export TMPDIR="/tmp"; fi;',`if [ ! -d "$TMPDIR" ]; then mkdir -p "$TMPDIR" 2>/dev/null || export TMPDIR="/tmp"; fi;`,`if [ ! -d "$TMPDIR" ]; then echo "usable TMPDIR not found: $TMPDIR" >&2; return 1; fi;`,'node_dir="$tool_root/node-v${node_version}-linux-${node_arch}";',`ready_marker="$node_dir/.openclaw-crabbox-node-ready";`,`export PATH="$node_dir/bin:$PATH";`,`if [ ! -x "$node_dir/bin/node" ] || [ ! -f "$ready_marker" ]; then`,`mkdir -p "$tool_root" || { status=$?; return "$status"; };`,'install_lock="$tool_root/.node-${node_version}-${node_arch}.lock";',`lock_acquired=0;`,`lock_deadline=$((SECONDS + 300));`,`while true; do`,`if mkdir "$install_lock" 2>/dev/null; then lock_acquired=1; printf "%s\\n" "$$" >"$install_lock/pid" || { status=$?; rm -rf "$install_lock"; return "$status"; }; break; fi;`,`if [ -x "$node_dir/bin/node" ] && [ -f "$ready_marker" ]; then break; fi;`,`if [ "$SECONDS" -ge "$lock_deadline" ]; then`,`lock_pid="$(cat "$install_lock/pid" 2>/dev/null || true)";`,`if [ -n "$lock_pid" ] && kill -0 "$lock_pid" 2>/dev/null; then echo "timed out waiting for active WSL2 Node toolchain install lock: $install_lock pid=$lock_pid" >&2; return 1; fi;`,`echo "reclaiming stale WSL2 Node toolchain install lock: $install_lock" >&2;`,`rm -rf "$install_lock" || return 1;`,`lock_deadline=$((SECONDS + 300));`,`fi;`,`sleep 1;`,`done;`,`release_install_lock() { if [ "$lock_acquired" = "1" ]; then rm -rf "$install_lock" 2>/dev/null || true; fi; };`,`if [ ! -x "$node_dir/bin/node" ] || [ ! -f "$ready_marker" ]; then`,`tmp_dir="$(mktemp -d)" || { release_install_lock; return 1; };`,'pkg="node-v${node_version}-linux-${node_arch}.tar.gz";','base_url="https://nodejs.org/dist/v${node_version}";',`curl -fsSL --connect-timeout 10 --max-time 300 --retry 2 --retry-delay 2 -o "$tmp_dir/$pkg" "$base_url/$pkg" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`curl -fsSL --connect-timeout 10 --max-time 60 --retry 2 --retry-delay 2 -o "$tmp_dir/SHASUMS256.txt" "$base_url/SHASUMS256.txt" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`(cd "$tmp_dir" && grep " $pkg$" SHASUMS256.txt | sha256sum -c -) || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`rm -rf "$node_dir" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`tar -xzf "$tmp_dir/$pkg" -C "$tool_root" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`touch "$ready_marker" || { status=$?; release_install_lock; rm -rf "$tmp_dir"; return "$status"; };`,`rm -rf "$tmp_dir";`,`fi;`,`release_install_lock;`,`fi;`,`node --version >&2 || return 1;`,...remotePosixJsEnvBootstrap(e),...t?[`${t} || return $?;`]:[]];if(e)n.push(`pnpm --version >&2;`,...t?[]:[`if [ -f pnpm-lock.yaml ] && [ ! -f node_modules/.modules.yaml ]; then pnpm install --frozen-lockfile || return 1; fi;`]);n.push(`export OPENCLAW_CRABBOX_BOOTSTRAP_PATH="$PATH";`);n.push(`};`,`openclaw_crabbox_bootstrap_wsl2_js`);return n.join(` `)}function scopedAwsMacosEnvCommand(e){if(e.length<=1||!isSupportedSystemEnvCommand(e[0]??``))return null;const t=[...e];if(!stripEnvCommandOptions(t,{canShimIgnoreEnvironment:true}))return null;const n=shellWordBasename(t[0]);const r=awsMacosCorepackEntrypoints.has(n)||commandWordsNeedAwsMacosPackageManager(t);const i=jsRuntimeEntrypoints.has(n);const a=awsMacosBunEntrypoints.has(n);if(!i&&!r&&!a)return null;return{runtimeEntrypoint:i?n:``,packageManager:r,bun:a,shellCommand:`openclaw_crabbox_env ${shellJoin(e.slice(1))}`}}function scopedAwsMacosShellEnvCommand(e){const t=shellCommandWordCandidates(e);if(t.length<1)return null;const n=/* @__PURE__ */ new Set;const r={runtimeEntrypoint:``,packageManager:false,bun:false};for(const e of t){const t=scopedAwsMacosEnvCommand(e);if(!t)continue;n.add(shellWordsKey(e));r.runtimeEntrypoint||=t.runtimeEntrypoint;r.packageManager||=t.packageManager;r.bun||=t.bun}if(n.size<1)return null;const i=shellCommandWithEnvShim(e,n);return i?{...r,shellCommand:i}:null}function shellWordsKey(e){return JSON.stringify(e)}function shellCommandWithEnvShim(e,t){let n=false;let r=``;let i=0;for(const a of shellCommandSegmentsWithBounds(e)){const o=leadingShellEnvCommandToken(e,a.start);if(!o||o.start>=a.end)continue;const s=normalizedShellSegmentWords(e.slice(a.start,a.end));if(!t.has(shellWordsKey(s)))continue;r+=e.slice(i,o.start);r+=`openclaw_crabbox_env`;i=o.end;n=true}return n?`${r}${e.slice(i)}`:``}function shellCommandSegmentsWithBounds(e){const t=[];const n=shellHeredocBodyRanges(e);let r=0;let i=0;let a=``;let o=false;for(let s=0;s<e.length;s+=1){const c=n[r];if(c&&s>=c.start){if(i<c.start)t.push({start:i,end:c.start});s=c.end-1;i=c.end;r+=1;continue}const l=e[s];if(o){o=false;continue}if(l===`\\`&&a!==`'`){o=true;continue}if(a){if(l===a)a=``;continue}if(l===`'`||l===`"`){a=l;continue}if(l!==`
`&&l!==`;`&&l!==`)`&&l!==`&`&&l!==`|`)continue;if(l===`&`&&(e[s-1]===`>`||e[s-1]===`<`||e[s+1]===`>`))continue;t.push({start:i,end:s});if((l===`&`||l===`|`)&&e[s+1]===l)s+=1;i=s+1}t.push({start:i,end:e.length});return t}function shellHeredocBodyRanges(e){const t=[];const n=[];let r=0;for(;;){const i=e.indexOf(`
`,r);const a=i>=0?i:e.length;const o=i>=0?i+1:e.length;const s=e.slice(r,a);if(n.length>0){t.push({start:r,end:o});const e=n[0];if(!e)continue;if((e.stripTabs?s.replace(/^\t+/u,``):s)===e.delimiter)n.shift()}else n.push(...lineHeredocDelimiters(s));if(i<0)return t;r=o}}function leadingShellEnvCommandToken(e,t=0){let n=t;for(;;){while(/\s/u.test(e[n]??``))n+=1;if(e[n]===`(`||e[n]===`{`){n+=1;continue}const t=readLeadingShellWord(e,n);if(!t)return null;if(shellControlCommandPrefixes.has(t.word)){n=t.end;continue}if(t.word===`time`){n=skipLeadingTimeCommand(e,t.end);continue}if(isSupportedSystemEnvCommand(t.word))return{start:n,end:t.end};if(!/^[A-Za-z_][A-Za-z0-9_]*=/u.test(t.word))return null;n=t.end}}function skipLeadingTimeCommand(e,t){let n=t;for(;;){while(/\s/u.test(e[n]??``))n+=1;const t=readLeadingShellWord(e,n);if(!t)return n;if(t.word===`--`||t.word.startsWith(`-`)){n=t.end;continue}return n}}function readLeadingShellWord(e,t){let n=``;let r=``;let i=false;for(let a=t;a<e.length;a+=1){const t=e[a]??``;if(i){n+=t;i=false;continue}if(t===`\\`&&r!==`'`){i=true;continue}if(r){if(t===r)r=``;else n+=t;continue}if(t===`'`||t===`"`){r=t;continue}if(/\s/u.test(t)||/[;&|()<>]/u.test(t))return n?{word:n,end:a}:null;n+=t}return n?{word:n,end:e.length}:null}function analyzeRemoteCommand(e){const t=e.commandArgs;const n=e.options.has(`shell`)?null:scopedAwsMacosEnvCommand(t);const r=e.options.has(`shell`)&&t.length===1?scopedAwsMacosShellEnvCommand(t[0]??``):null;const i=n??r;const a=i?commandNeedsAwsMacosPackageManager(t):commandNeedsAwsMacosPackageManager(t,{canShimIgnoreEnvironment:false});const o=i?.packageManager||a;const s=i?.runtimeEntrypoint||commandRuntimeEntrypoint(t);return{bun:i?.bun||commandNeedsAwsMacosBun(t),changedGate:isChangedGateCommand(t),commandArgs:t,packageManager:o,runtimeEntrypoint:s,scopedEnvCommand:i,swift:commandNeedsAwsMacosSwiftToolchain(t)}}function prepareRemoteWsl2JsBootstrapScript(e,t,n,r){const i=awsMacosBunEntrypoints.has(t.runtimeEntrypoint)?``:t.runtimeEntrypoint;if(!isBrokeredWsl2RemoteTarget(e.args,n)||!i&&!t.packageManager)return{args:e.args,cleanup:()=>{},prepared:false};if(e.start<0)return{args:e.args,cleanup:()=>{},prepared:false};const a=mkdtempSync(resolve(tmpdir(),`openclaw-crabbox-wsl2-script-`));const cleanup=()=>rmSync(a,{recursive:true,force:true});try{const n=resolve(a,`script.sh`);const i=t.scopedEnvCommand?.shellCommand??renderRunShellCommand(e);const o=`${remoteWsl2JsBootstrap({packageManager:t.packageManager,sourceBootstrap:r})} || exit $?\n{ ${i}\n}\n`;writeFileSync(n,o,`utf8`);chmodSync(n,448);const s=e.args.slice(0,e.optionEnd);if(!e.options.has(`no-hydrate`))s.push(`--no-hydrate`);s.push(`--script`,n);return{args:s,cleanup,prepared:true}}catch(e){cleanup();throw e}}function injectRemoteAwsMacosJsBootstrap(e,t,n,r){if(!isAwsMacosRemoteTarget(e.args,n)||!t.runtimeEntrypoint&&!t.packageManager&&!t.bun&&!r)return e.args;if(e.start<0)return e.args;const i=t.scopedEnvCommand?.shellCommand??renderRunShellCommand(e);return replaceRunCommandWithShell(e,`${remoteAwsMacosJsBootstrap({packageManager:t.packageManager,bun:t.bun,sourceBootstrap:r})} && { ${i}\n}`)}function remoteAwsMacosSwiftBootstrap(){return[`openclaw_crabbox_require_macos_swift_63() {`,`openclaw_xcode="";`,`for openclaw_candidate in /Applications/Xcode_26*.app /Applications/Xcode-26*.app /Applications/Xcode_2[7-9]*.app /Applications/Xcode-2[7-9]*.app; do if [ -d "$openclaw_candidate" ]; then openclaw_xcode="$openclaw_candidate"; fi; done;`,`if [ -n "$openclaw_xcode" ]; then openclaw_developer="$openclaw_xcode/Contents/Developer"; if [ ! -d "$openclaw_developer" ]; then openclaw_developer="$openclaw_xcode"; fi; sudo xcode-select -s "$openclaw_developer" || return 1; fi;`,`openclaw_swift_version="$(swift --version 2>&1)" || { status=$?; printf "%s\\n" "$openclaw_swift_version" >&2; return "$status"; };`,`printf "%s\\n" "$openclaw_swift_version" >&2;`,`openclaw_swift_major_minor="$(printf "%s\\n" "$openclaw_swift_version" | sed -nE "s/.*Apple Swift version ([0-9]+)\\.([0-9]+).*/\\1 \\2/p" | head -n 1)";`,`if [ -z "$openclaw_swift_major_minor" ]; then echo "[crabbox] OpenClaw macOS app proof requires Swift tools 6.3+; unable to parse swift --version." >&2; return 2; fi;`,`set -- $openclaw_swift_major_minor;`,`if [ "$1" -lt 6 ] || { [ "$1" -eq 6 ] && [ "$2" -lt 3 ]; }; then`,`echo "[crabbox] OpenClaw macOS app proof requires Swift tools 6.3+ (Xcode 26.4+)." >&2;`,`echo "[crabbox] current Swift is $1.$2; select/install Xcode 26.4 or newer." >&2;`,`return 2;`,`fi;`,`openclaw_xcodebuild_version="$(xcodebuild -version 2>&1)" || { printf "%s\\n" "$openclaw_xcodebuild_version" >&2; echo "[crabbox] OpenClaw macOS app proof requires Xcode 26.4+; active developer directory does not provide usable xcodebuild." >&2; return 2; };`,`printf "%s\\n" "$openclaw_xcodebuild_version" >&2;`,`openclaw_xcode_major_minor="$(printf "%s\\n" "$openclaw_xcodebuild_version" | sed -nE "s/^Xcode ([0-9]+)\\.([0-9]+).*/\\1 \\2/p" | head -n 1)";`,`if [ -z "$openclaw_xcode_major_minor" ]; then echo "[crabbox] OpenClaw macOS app proof requires Xcode 26.4+; unable to parse xcodebuild -version." >&2; return 2; fi;`,`set -- $openclaw_xcode_major_minor;`,`if [ "$1" -lt 26 ] || { [ "$1" -eq 26 ] && [ "$2" -lt 4 ]; }; then echo "[crabbox] OpenClaw macOS app proof requires Xcode 26.4+; current xcodebuild is $1.$2." >&2; return 2; fi;`,`};`,`openclaw_crabbox_require_macos_swift_63`].join(` `)}function injectRemoteAwsMacosSwiftBootstrap(e,t,n,r=false){if(!isAwsMacosRemoteTarget(e.args,n)||!r&&!t.swift)return e.args;if(e.start<0)return e.args;return replaceRunCommandWithShell(e,`${remoteAwsMacosSwiftBootstrap()} && { ${renderRunShellCommand(e)}\n}`)}function replaceRunScript(e,t){const n=e.args.slice(0,e.optionEnd);for(const{name:t,index:r}of e.optionEntries.toReversed())if(t===`script`||t===`script-stdin`)n.splice(r,t===`script`&&!e.args[r]?.includes(`=`)?2:1);return[...n,`--script`,t,...e.args.slice(e.optionEnd)]}async function prepareAwsMacosScriptStdinBootstrap(e,t){const n=parseCommandInvocation(help.text,e);const r=n.script;if(!isAwsMacosRemoteTarget(e,t)||r?.name!==`script-stdin`)return{args:e,cleanup:()=>{},prepared:false};const i=await readScriptStdin();const a=mkdtempSync(resolve(tmpdir(),`openclaw-crabbox-macos-script-`));const cleanup=()=>rmSync(a,{recursive:true,force:true});try{const e=resolve(a,`script.sh`);writeFileSync(e,createAwsMacosScriptStdinWrapper(i),`utf8`);chmodSync(e,448);return{args:replaceRunScript(n,e),cleanup,prepared:true}}catch(e){cleanup();throw e}}function createAwsMacosScriptStdinWrapper(e){return wrapRemoteScript(e,remoteAwsMacosScriptBootstrap(awsMacosScriptBootstrapRequirements(e)))}function wrapRemoteScript(e,t){if(!e.startsWith(`#!`))return`${t} || exit $?\n${e}`;const n=uniqueHereDocDelimiter(e);return[`${t} || exit $?`,'tmp_script="$(mktemp "${TMPDIR:-/tmp}/openclaw-crabbox-script.XXXXXX")" || exit $?',`cleanup_openclaw_crabbox_script() { rm -f "$tmp_script"; }`,`trap cleanup_openclaw_crabbox_script EXIT`,`cat >"$tmp_script" <<'${n}'`,e.endsWith(`
`)?e.slice(0,-1):e,n,`chmod 700 "$tmp_script" || exit $?`,`"$tmp_script" "$@"`,``].join(`
`)}function remoteAwsMacosScriptBootstrap(e){const t=[remoteAwsMacosJsBootstrap(e)];if(e.swift)t.push(remoteAwsMacosSwiftBootstrap());return t.join(` && `)}function awsMacosScriptBootstrapRequirements(e){const t={packageManager:false,bun:false,swift:false};const n=e.match(/^[^\r\n]*/u)?.[0]??``;if(n.startsWith(`#!`)){const r=n.slice(2).trim().split(/\s+/u).filter(Boolean);t.packageManager=commandWordsNeedEntrypoint(r,awsMacosCorepackEntrypoints);t.bun=commandWordsNeedEntrypoint(r,awsMacosBunEntrypoints);t.swift=commandWordsNeedAwsMacosSwiftToolchain(r);if(commandWordsShellEntrypoint(r)){const r=e.slice(n.length).replace(/^\r?\n/u,``);t.packageManager||=commandNeedsAwsMacosPackageManager([r]);t.bun||=commandNeedsAwsMacosBun([r]);t.swift||=commandNeedsAwsMacosSwiftToolchain([r])}return t}t.packageManager=commandNeedsAwsMacosPackageManager([e]);t.bun=commandNeedsAwsMacosBun([e]);t.swift=commandNeedsAwsMacosSwiftToolchain([e]);return t}function uniqueHereDocDelimiter(e){let t=0;for(;;){const n=`OPENCLAW_CRABBOX_SCRIPT_${t}`;if(!new RegExp(`^${n}$`,`mu`).test(e))return n;t+=1}}function isSparseCheckout(){const e=gitOutput([`config`,`--bool`,`core.sparseCheckout`]);if(e.status===0&&e.stdout===`true`)return true;const t=gitOutput([`sparse-checkout`,`list`]);return t.status===0&&t.stdout.length>0}function isWorktreeClean(){const e=gitOutput([`status`,`--porcelain=v1`]);return e.status===0&&e.stdout===``}function needsSourceCapsule(e,t){const n=canonicalProviderName(t);const r=parseCommandInvocation(help.text,e);const i=r.optionEntries.findLast(({name:e})=>e===`no-hydrate`);const a=Boolean(i&&(!e[i.index]?.includes(`=`)||/^(?:1|t|T|true|TRUE|True)$/u.test(i.value)));return e[0]===`run`&&!hasOption(e,`--no-sync`)&&!hasOption(e,`--fresh-pr`)&&!isNativeWindowsRemoteTarget(e)&&(n===`blacksmith-testbox`||(n===`aws`||n===`ascii-box`)&&[``,`linux`,`ubuntu`].includes(effectiveTargetContext(e).target)&&!a&&!hasOption(e,`--sync-only`)||analyzeRemoteCommand(r).changedGate)}function shouldUseFullCheckoutForRemoteSync(e,t){if(e[0]!==`run`)return false;if(hasOption(e,`--no-sync`)||hasOption(e,`--fresh-pr`))return false;if(needsSourceCapsule(e,t))return true;const n=isChangedGateCommand(parseCommandInvocation(help.text,e).commandArgs);return isWorktreeClean()&&(isSparseCheckout()||n)}function defaultFullCheckoutSyncRoot(){const e=homedir();if(e)return resolve(e,`.cache`,`openclaw`,`crabbox-sync`);return resolve(tmpdir(),`openclaw-crabbox-sync`)}function fullCheckoutSyncRoot(e=true){const t=process.env.OPENCLAW_CRABBOX_SYNC_TMPDIR?.trim();const n=t?resolve(t):defaultFullCheckoutSyncRoot();if(e)mkdirSync(n,{recursive:true});return n}function parseNonNegativeIntegerEnv(e,t,n){const r=process.env[e]?.trim();if(!r)return t;if(!/^\d+$/u.test(r))throw new Error(`${e} must be a non-negative integer ${n}, got ${JSON.stringify(r)}`);const i=Number(r);if(!Number.isSafeInteger(i))throw new Error(`${e} must be a safe non-negative integer ${n}, got ${JSON.stringify(r)}`);return i}function formatByteCount(e){if(e<1024)return`${e} B`;const t=[`KiB`,`MiB`,`GiB`,`TiB`];let n=e/1024;let r=0;while(n>=1024&&r<t.length-1){n/=1024;r+=1}return`${n.toFixed(n>=10?1:2)} ${t[r]}`}function assertFullCheckoutSyncDisk(e){const t=parseNonNegativeIntegerEnv(`OPENCLAW_CRABBOX_SYNC_MIN_FREE_BYTES`,1073741824,`byte count`);if(t===0)return;const n=statfsSync(e);const r=n.bavail*n.bsize;if(r>=t)return;throw new Error([`insufficient free disk for Crabbox sparse-sync full checkout`,`root=${e}`,`free=${formatByteCount(r)}`,`required=${formatByteCount(t)}`,`set OPENCLAW_CRABBOX_SYNC_TMPDIR to a roomier filesystem or lower OPENCLAW_CRABBOX_SYNC_MIN_FREE_BYTES if you know this checkout fits`].join(`; `))}function prepareFullCheckoutForSync(){const e=fullCheckoutSyncRoot();assertFullCheckoutSyncDisk(e);const t=createStaging(e,repoRoot,`worktree`);const n=resolve(t.payload,`source`);let r=false;function create(){r=true;try{const e=gitOutput([`worktree`,`add`,`--detach`,n,`HEAD`]);if(e.status!==0)throw new Error(`git worktree add failed: ${e.text}`);const t=gitOutput([`-C`,n,`sparse-checkout`,`disable`]);if(t.status!==0)throw new Error(`git sparse-checkout disable failed: ${t.text}`)}catch(e){try{cleanupFullCheckout(n,r);r=false;t.dispose()}catch(n){t.hold(`registration`);throw new AggregateError([e,n],`Full checkout preparation failed; staging retained at `+t.root,{cause:n})}throw e}}create();return{dir:n,staging:t,restoreIfMissing(){try{if(statSync(n).isDirectory())return false}catch{}console.error(`[crabbox] temporary full checkout disappeared; recreating ${n}`);if(r){const e=gitOutput([`worktree`,`remove`,`--force`,n]);if(e.status!==0){t.hold(`registration`);throw new Error(`git worktree remove failed for ${n}; registration cleanup incomplete; remaining staging retained: ${e.text}`)}r=false}rmSync(n,{recursive:true,force:true});create();return true},exists(){try{return statSync(n).isDirectory()}catch{return false}},cleanup(){try{cleanupFullCheckout(n,r)}catch(e){t.hold(`registration`);throw e}r=false;t.dispose()}}}function startFullCheckoutKeepalive(e,t={}){let n=false;const r=t.intervalMs??fullCheckoutKeepaliveIntervalMs();const refresh=()=>{try{if(!e.exists()){if(t.onMissing){if(!n){n=true;console.error(`[crabbox] temporary full checkout disappeared while Crabbox was running; terminating because the child cwd cannot be repaired: ${e.dir}`);t.onMissing()}return}e.restoreIfMissing()}const r=/* @__PURE__ */ new Date;utimesSync(e.dir,r,r)}catch(t){console.error(`[crabbox] warning: failed to refresh temporary full checkout ${e.dir}: ${t instanceof Error?t.message:String(t)}`)}};refresh();if(r<=0)return()=>{};const i=setInterval(refresh,r);i.unref?.();return()=>clearInterval(i)}function fullCheckoutKeepaliveIntervalMs(){return parseNonNegativeIntegerEnv(`OPENCLAW_CRABBOX_SYNC_KEEPALIVE_MS`,5e3,`millisecond interval`)}function cleanupFullCheckout(e,t){if(t){const t=gitOutput([`worktree`,`remove`,`--force`,e]);if(t.status===0)return;throw new Error(`git worktree remove failed for ${e}; registration cleanup incomplete; remaining staging retained: ${t.text}`)}rmSync(e,{recursive:true,force:true})}function assertFullCheckoutAvailableBeforeExit(e){try{if(statSync(e).isDirectory())return true}catch{}console.error(`[crabbox] temporary full checkout vanished before Crabbox finished syncing: ${e}`);return false}function injectFullCheckoutLeaseReclaim(e){if(e[0]!==`run`||!hasOption(e,`--id`)||hasOption(e,`--reclaim`))return e;const t=[...e];t.splice(commandOptionEnd(t),0,`--reclaim`);return t}function injectRemoteTestboxCi(e,t,n){if(e[0]!==`run`||canonicalProviderName(t)!==`blacksmith-testbox`)return e;const r=parseCommandInvocation(help.text,e);if(r.start<0)return e;return replaceRunCommandWithShell(r,`export CI=true; ${n?`${n} || exit $?; `:``}exec node scripts/crabbox-remote-redact.mjs -- bash -c ${shellQuote(renderRunShellCommand(r))}`)}async function applyRunTransforms(e,t,n){const r=canonicalProviderName(n.provider)===`blacksmith-testbox`;const i=canonicalProviderName(n.provider)===`ascii-box`?n.capsule:null;const a=n.capsule?remoteSourceBootstrap(n.capsule,n.changedGateAlias,r):``;const o=injectRemoteChangedGateEnvironment(e,t);const s=n.childCwd===repoRoot?o:absolutizeLocalRunPaths(o);let c=parseCommandInvocation(help.text,s);const l=analyzeRemoteCommand(c);l.packageManager||=Boolean(n.capsule);const u=prepareRemoteWsl2JsBootstrapScript(c,l,n.provider,a);let d=u.args;let sourceScriptCleanup=()=>{};try{if(a&&!u.prepared){c=parseCommandInvocation(help.text,d);const e=c.script;if(e){const t=e.name===`script`?readFileSync(resolve(repoRoot,e.value),`utf8`):await readScriptStdin();const r=mkdtempSync(resolve(tmpdir(),`openclaw-crabbox-source-script-`));const o=resolve(r,`script.sh`);sourceScriptCleanup=()=>rmSync(r,{recursive:true,force:true});writeFileSync(o,i?remoteSourceBootstrap(i,n.changedGateAlias,false,{script:t,delimiter:uniqueHereDocDelimiter(t)}):wrapRemoteScript(t,`${a} || exit $?\nexport CI=true`));chmodSync(o,448);d=replaceRunScript(c,o)}else if(c.start>=0&&!r&&!isAwsMacosRemoteTarget(d,n.provider))d=replaceRunCommandWithShell(c,i?remoteSourceBootstrap(i,n.changedGateAlias,false,{command:renderRunShellCommand(c)}):`${a} || exit $?; ${renderRunShellCommand(c)}`)}c=parseCommandInvocation(help.text,d);d=injectRemoteAwsMacosJsBootstrap(c,l,n.provider,a);c=parseCommandInvocation(help.text,d);d=injectRemoteAwsMacosSwiftBootstrap(c,l,n.provider,l.swift);c=parseCommandInvocation(help.text,d);d=injectRemoteWindowsHydratedNodeModulesBootstrap(c,l,n.provider);return{args:injectRemoteTestboxCi(d,n.provider,a),wsl2ScriptBootstrap:{...u,cleanup(){u.cleanup();sourceScriptCleanup()}}}}catch(e){u.cleanup();sourceScriptCleanup();throw e}}const help=probeCrabboxHelp(binary,[...workloadCommand?args.slice(0,userArgStart):[`run`],`--help`]);const providers=parseProvidersFromHelp(help.text);commandValueOptionsFromHelp=parseCommandValueOptionsFromHelp(help.text);const displayBinary=binary===`crabbox`?`crabbox`:relative(repoRoot,binary);if(help.status!==0||commandValueOptionsFromHelp.size===0){console.error(`[crabbox] bin=${displayBinary} version=${version$1} providers=${providers.join(`,`)||`unknown`}`);console.error(`[crabbox] selected binary failed --help sanity checks`);process.exit(2)}const helpFlags=/* @__PURE__ */ new Set([`--help`,`-h`]);const invocationOptions=workloadCommand?parseCommandInvocation(help.text,args).options:null;if(helpFlags.has(args[0]??``)||helpFlags.has(args[userArgStart]??``)||args[0]===`help`&&args.length<=commandUserArgStart(args.slice(1))+1||[`run`,`warmup`].includes(args[0]??``)&&args[1]===`help`||invocationOptions?.has(`help`)||invocationOptions?.has(`h`)){const e=spawnInvocation(binary,args,process.env,process.platform);const t=spawnSync(e.command,e.args,{cwd:repoRoot,stdio:`inherit`,windowsVerbatimArguments:e.windowsVerbatimArguments});if(t.error)console.error(`[crabbox] ${t.error.message}`);process.exit(t.status??1)}if(args[userArgStart]===`--`)args.splice(userArgStart,1);const providerSelection=selectedProvider(args,providers);if(providerSelection.error){console.error(`[crabbox] ${providerSelection.error}`);if(providerSelection.readiness){console.error(`[crabbox] provider readiness ${formatProviderReadiness(providerSelection.readiness)}`);for(const e of providerRecoveryAdvice(providerSelection.readiness))console.error(`[crabbox] recovery: ${e}`)}process.exit(2)}const provider=providerSelection.provider;const canonicalProvider=canonicalProviderName(provider);const commandProviderValue=commandProvider(args);let normalizedArgs=ensureAwsMacOnDemandMarket(ensureBoatDefaultClass(ensurePolicyProvider(ensureNativeWindowsHydrateJob(ensureAzureWindowsProvider(args,provider,providers)),providerSelection),provider),provider);console.error(`[crabbox] bin=${displayBinary} version=${version$1} provider=${provider||`unknown`} providers=${providers.join(`,`)||`unknown`}`);if(providerSelection.source===`policy`)console.error(`[crabbox] route workload=${providerSelection.workload} selected=${provider} chain=${providerSelection.chain.join(`,`)} readiness=${formatProviderReadiness(providerSelection.readiness??/* @__PURE__ */ new Map)}`);if(provider&&!isProviderAdvertised(provider,providers)){if(providers.length===0){console.error(`[crabbox] could not parse provider list from --help; refusing to run with --provider without validation`);process.exit(2)}console.error(`[crabbox] selected binary does not advertise provider ${provider}; choose a supported provider`);process.exit(2)}if(canonicalProvider===`blacksmith-testbox`){if([`run`,`warmup`].includes(normalizedArgs[0]??``)){const e=parseCommandInvocation(help.text,normalizedArgs).optionEntries.findLast(({name:e})=>e===`blacksmith-ref`);if(e&&e.value!==`main`){console.error(`[crabbox] Testbox workflow ref must be main so allocations use current spending limits. Omit --blacksmith-ref; the source capsule preserves the checkout being tested.`);process.exit(2)}normalizedArgs.splice(commandOptionEnd(normalizedArgs),0,`--blacksmith-ref=main`)}if(normalizedArgs[0]===`run`&&parseCommandInvocation(help.text,normalizedArgs).scriptRequested){console.error(`[crabbox] provider=blacksmith-testbox does not support --script or --script-stdin. Run a synced script as trailing argv, use --shell, or choose an SSH provider for uploaded scripts.`);process.exit(2)}if(normalizedArgs[0]===`run`&&hasOption(normalizedArgs,`--no-sync`)){console.error(`[crabbox] provider=blacksmith-testbox does not support --no-sync. Omit the flag only when source synchronization is intended.`);process.exit(2)}if(isWindowsRemoteTarget(normalizedArgs)){console.error([`[crabbox] provider=blacksmith-testbox supports Linux Testbox proof only; it cannot run Windows or WSL2 targets.`,`[crabbox] use provider=azure or provider=aws for brokered Crabbox Windows/WSL2 proof, provider=parallels for local Windows, or dispatch .github/workflows/windows-testbox-probe.yml for Blacksmith Windows runner probes.`].join(`
`));process.exit(2)}}enforceBrokeredCloud(normalizedArgs,provider,Boolean(commandProviderValue),providerSelection.readiness?.get(canonicalProvider));if(canonicalProvider===`blacksmith-testbox`){const e=process.env.CRABBOX_PROVIDER?.trim();console.error(`[crabbox] provider=blacksmith-testbox ${commandProviderValue?`explicit`:e?`from CRABBOX_PROVIDER`:`from config`}; if queued or unavailable, stop this task's allocation and use PR CI or a safe local scope. Keep platform-specific proof pending; do not chain providers.`);console.error(`[crabbox] delegated Testbox proof uses the wrapper exitCode and timing JSON; the linked Actions run can show cancelled during external lease cleanup`);enforceCrabboxOwnedBlacksmithLease(normalizedArgs)}let testboxLeaseFreshness;try{testboxLeaseFreshness=prepareTestboxLeaseFreshness({operation:normalizedArgs[0]??``,options:new Map(parseCommandInvocation(help.text,normalizedArgs).optionEntries.map(({name:e,value:t,index:n})=>[e,normalizedArgs[n]?.includes(`=`)||commandValueOptionsFromHelp.has(e)?t:`true`])),command:normalizedArgs,env:{...process.env,CI:process.env.CI||`true`},provider:canonicalProvider,repoRoot});if(testboxLeaseFreshness){normalizedArgs.splice(commandOptionEnd(normalizedArgs),0,`--timing-json`);console.error(JSON.stringify({event:`testbox-admission`,...testboxLeaseFreshness.attribution,leaseId:testboxLeaseFreshness.id||void 0}))}}catch(e){console.error(`[crabbox] ${e instanceof Error?e.message:String(e)}`);process.exit(2)}let childCwd=repoRoot;let cleanupChildCwd=()=>{};let fullCheckout=null;let stopFullCheckoutKeepalive=()=>{};let cleanupSucceeded;let sourceCapsule=null;let sourceStaging;let remoteChangedGateAlias=``;let capturedLeaseId=``;let scriptBootstrap={args:normalizedArgs,cleanup:()=>{},prepared:false};let wsl2ScriptBootstrap={args:normalizedArgs,cleanup:()=>{},prepared:false};const preparationAbort=new AbortController;const childKillGraceMs=resolveChildKillGraceMs(process.env);let runningChild;let childTreeSettled=true;let childTreeShutdownStarted=false;let childSettlement;let cancellationSignal;const signalExitCodes=/* @__PURE__ */ new Map([[`SIGHUP`,129],[`SIGINT`,130],[`SIGTERM`,143]]);for(const e of signalExitCodes.keys())process.on(e,()=>{cancellationSignal??=e;if(runningChild)exitAfterChildTreeTermination(runningChild,e,signalExitCodes.get(cancellationSignal)??1);else preparationAbort.abort()});process.once(`exit`,cleanupOnce);async function readScriptStdin(){return(await buffer(addAbortSignal(preparationAbort.signal,process.stdin))).toString(`utf8`)}async function preparationCheckpoint(e){await setImmediate();await setImmediate();if(cancellationSignal){if(e!==void 0){const t=e instanceof Error?e.message:typeof e===`string`?e:`unknown preparation error`;console.error(`[crabbox] preparation interrupted: ${t}`)}cleanupOnce();process.exit(signalExitCodes.get(cancellationSignal)??1)}}try{scriptBootstrap=await prepareAwsMacosScriptStdinBootstrap(normalizedArgs,provider);normalizedArgs=scriptBootstrap.args;if(shouldUseFullCheckoutForRemoteSync(normalizedArgs,provider)){const e=analyzeRemoteCommand(parseCommandInvocation(help.text,normalizedArgs));const t=changedGateBaseForCommand(e.commandArgs);if(needsSourceCapsule(normalizedArgs,provider)){const e=fullCheckoutSyncRoot();assertFullCheckoutSyncDisk(e);sourceCapsule=prepareCrabboxSourceCapsule({repoRoot,syncRoot:e,reuseMirror:canonicalProvider===`blacksmith-testbox`,seedFromBase:canonicalProvider===`ascii-box`,syncPlan:spawnInvocation(binary,[`sync-plan`,`--json`,`--limit`,`2147483647`],process.env,process.platform),base:t.resolvedBase});sourceStaging=sourceCapsule.staging}const n=sourceCapsule;const r=n?{dir:n.directory,staging:n.staging,cleanup:n.cleanup,exists:()=>pathExists(n.directory),restoreIfMissing(){if(!pathExists(n.directory))throw new Error(`frozen source checkout disappeared; rerun from the local candidate`);return false}}:prepareFullCheckoutForSync();fullCheckout=r;sourceStaging=r.staging;cleanupChildCwd=()=>r.cleanup();childCwd=r.dir;normalizedArgs=injectFullCheckoutLeaseReclaim(normalizedArgs);childCwd=realpathSync(r.dir);remoteChangedGateAlias=t.remoteAlias;console.error(`[crabbox] isolated checkout sync; syncing from temporary full checkout ${r.dir}`);if(e.changedGate&&n)console.error(`[crabbox] remote changed gate detected; overlaying the local worktree as changes from ${n.baseSha}`)}}catch(e){await preparationCheckpoint(e);cleanupOnce();throw e}function cleanupOnce(){if(cleanupSucceeded!==void 0)return cleanupSucceeded;cleanupSucceeded=false;if(!childTreeSettled){failManagedCleanup();try{sourceStaging?.hold(`writers`)}catch{}console.error(childCwd===repoRoot?`[crabbox] child cleanup is unverified; local inputs remain in place`:`[crabbox] child cleanup is unverified; temporary source retained at ${childCwd}`);process.exitCode||=1;return false}let e=true;let t=true;for(const[t,n]of[[`checkout keepalive`,stopFullCheckoutKeepalive],[`remote script`,wsl2ScriptBootstrap.cleanup],[`script stdin`,scriptBootstrap.cleanup]])try{n()}catch(n){e=false;console.error(`[crabbox] ${t} cleanup failed: ${n instanceof Error?n.message:String(n)}`)}if([`blacksmith-testbox`,`aws`,`ascii-box`].includes(canonicalProvider)){t=restoreTemporaryLeaseClaim(normalizedArgs,capturedLeaseId);e=t&&e}try{const e=preserveCrabboxArtifacts(childCwd,repoRoot);if(e)sourceStaging?.preserved(e)}catch(e){try{sourceStaging?.hold(`artifacts`)}catch{}console.error(`[crabbox] artifact preservation failed: ${e instanceof Error?e.message:String(e)}; temporary checkout retained at ${childCwd}. Recover .crabbox/runs and .crabbox/captures from this checkout before removing it.`);process.exitCode||=1;return false}if(!t){try{sourceStaging?.hold(`claims`)}catch{}console.error(`[crabbox] lease ownership restoration failed; temporary checkout retained at ${childCwd}. Restore the retained lease to ${repoRoot} or stop it before removing this checkout.`);process.exitCode||=1;return false}try{cleanupChildCwd()}catch(t){e=false;console.error(`[crabbox] temporary checkout cleanup failed at ${childCwd}: ${t instanceof Error?t.message:String(t)}`)}cleanupSucceeded=e;if(!e)process.exitCode||=1;return e}const scriptStdinPrepared=scriptBootstrap.prepared;const invocation=parseCommandInvocation(help.text,normalizedArgs);const commandFacts=analyzeRemoteCommand(invocation);const runtimeEntrypoint=commandFacts.runtimeEntrypoint;if(normalizedArgs[0]===`run`&&provider===`aws`&&(runtimeEntrypoint||scriptStdinPrepared)){if(isAwsMacosRemoteTarget(normalizedArgs,provider))console.error(`[crabbox] provider=aws macOS raw boxes may lack Node/Corepack/pnpm/Bun for ${runtimeEntrypoint||`--script-stdin`}; bootstrapping pinned user-local JavaScript tooling before the command`);else{const e=optionValue(normalizedArgs,`--id`);const t=e?`pnpm crabbox:hydrate -- --id ${e}`:`pnpm crabbox:warmup, then pnpm crabbox:hydrate -- --id <id>`;console.error(`[crabbox] warning: provider=aws raw boxes may lack Node/Corepack/pnpm/Bun for ${runtimeEntrypoint}; hydrate first (${t}) or pass --provider blacksmith-testbox for OpenClaw CI-like proof; not switching providers automatically`)}}if(normalizedArgs[0]===`run`&&isBrokeredWsl2RemoteTarget(normalizedArgs,provider)){const e=awsMacosBunEntrypoints.has(runtimeEntrypoint)?``:runtimeEntrypoint;if(e||commandFacts.packageManager)console.error(`[crabbox] provider=${provider} WSL2 raw boxes may lack Node/Corepack/pnpm for ${e||`package-manager`}; using no-hydrate pinned user-local JavaScript tooling before the command`)}const childEnv={...process.env};if(sourceCapsule?.configPath)childEnv.CRABBOX_CONFIG=sourceCapsule.configPath;if(canonicalProvider===`blacksmith-testbox`&&!childEnv.CI)childEnv.CI=`true`;if(isLocalContainerProvider(provider)&&!childEnv.CRABBOX_LOCAL_CONTAINER_DOCKER_SOCKET&&!hasOption(normalizedArgs,`--local-container-docker-socket`)){childEnv.CRABBOX_LOCAL_CONTAINER_DOCKER_SOCKET=`1`;console.error(`[crabbox] provider=docker enabling host Docker socket pass-through for OpenClaw Docker tests`)}if(isLocalContainerProvider(provider)&&process.platform===`linux`&&!childEnv.CRABBOX_LOCAL_CONTAINER_WORK_ROOT&&!hasOption(normalizedArgs,`--local-container-work-root`)){childEnv.CRABBOX_LOCAL_CONTAINER_WORK_ROOT=`/tmp/openclaw-crabbox-docker-work`;console.error(`[crabbox] provider=docker using short host-visible work root for OpenClaw Docker tests`)}try{const e=await applyRunTransforms(invocation,commandFacts,{changedGateAlias:remoteChangedGateAlias,capsule:sourceCapsule,childCwd,provider});wsl2ScriptBootstrap=e.wsl2ScriptBootstrap;normalizedArgs=e.args}catch(e){await preparationCheckpoint(e);cleanupOnce();throw e}const childArgs=normalizedArgs;let fullCheckoutKeepaliveIntervalMsValue=0;if(fullCheckout)try{fullCheckoutKeepaliveIntervalMsValue=fullCheckoutKeepaliveIntervalMs()}catch(e){cleanupOnce();throw e}const childInvocation=spawnInvocation(binary,childArgs,childEnv,process.platform);const captureLeaseTimingJSON=[`blacksmith-testbox`,`aws`,`ascii-box`].includes(canonicalProvider)&&hasOption(normalizedArgs,`--timing-json`);const reusedRunLeaseId=normalizedArgs[0]===`run`?optionValue(normalizedArgs,`--id`):``;const childStartedAtMs=Date.now();const FAST_FAIL_HINT_WINDOW_MS=15e3;const spawnManagedChild=await loadManagedChildSpawner();await preparationCheckpoint();try{testboxLeaseFreshness?.assertCurrent()}catch(e){cleanupOnce();throw e}if(sourceStaging?.recorded){let e;try{e=captureClaimNamespace(childCwd,childEnv)}catch(e){console.error(`[crabbox] staging claim namespace unavailable; orphan recovery will remain protected: `+(e instanceof Error?e.message:String(e)))}const t=optionValue(normalizedArgs,`--id`);sourceStaging.admitted(e,t?[t]:void 0)}try{await claimManagedCleanup();await preparationCheckpoint()}catch(e){if(e instanceof ManagedCleanupCancelled)cancellationSignal??=e.signal;await preparationCheckpoint(e);cleanupOnce();throw e}const child=spawnManagedChild(childInvocation.command,childInvocation.args,{cwd:childCwd,stdio:[`inherit`,`inherit`,captureLeaseTimingJSON?`pipe`:`inherit`],detached:process.platform!==`win32`,env:childEnv,windowsVerbatimArguments:childInvocation.windowsVerbatimArguments});runningChild=child;childTreeSettled=false;const childStderr=child.stderr;if(childStderr){const e=new StringDecoder(`utf8`);let t=``;let n=false;const observeText=e=>{let r=e;while(r){const e=r.indexOf(`
`);const i=e>=0?r.slice(0,e):r;if(!n){t+=i;if(t.length>MAX_TIMING_JSON_LINE_CHARS){t=``;n=true}}if(e<0)return;if(!n)observeLeaseTimingJSONLine(t);t=``;n=false;r=r.slice(e+1)}};childStderr.on(`data`,t=>{const n=process.stderr.write(t);observeText(e.write(t));if(!n){childStderr.pause();process.stderr.once(`drain`,()=>childStderr.resume())}});childStderr.on(`end`,()=>{observeText(e.end());if(t&&!n)observeLeaseTimingJSONLine(t)})}child.on(`exit`,(e,t)=>{if(childTreeShutdownStarted)return;childTreeShutdownStarted=true;finishChildExit(e,t)});async function finishChildExit(e,t){const n=await settleChildTree(child,t??void 0);let r=e;const i=!fullCheckout||assertFullCheckoutAvailableBeforeExit(fullCheckout.dir);if(n&&!t&&(e===0||capturedLeaseId))try{recordTestboxLeaseFreshness(testboxLeaseFreshness,capturedLeaseId,e??1)}catch(e){console.error(`[crabbox] failed to record Testbox lease freshness: ${e instanceof Error?e.message:String(e)}`);r=2}const a=cleanupOnce();const o=(r??1)||(n&&i&&a?0:1);if(testboxLeaseFreshness)console.error(JSON.stringify({event:`testbox-completion`,...testboxLeaseFreshness.attribution,leaseId:capturedLeaseId||testboxLeaseFreshness.id||void 0,sourceTree:sourceCapsule?.tree,elapsedMs:Date.now()-childStartedAtMs,exitCode:cancellationSignal||t?signalExitCodes.get(cancellationSignal??t)??1:o,signal:cancellationSignal||t,settled:n}));if(cancellationSignal||t)process.exit(signalExitCodes.get(cancellationSignal??t)??1);if(o!==0&&reusedRunLeaseId&&Date.now()-childStartedAtMs<FAST_FAIL_HINT_WINDOW_MS)console.error(`[crabbox] run --id ${reusedRunLeaseId} failed fast; reusable leases expire after their idle timeout and rejected flags also exit immediately. Check the first error line above, verify the lease with \`node scripts/crabbox-wrapper.mjs list\`, or warm a fresh one with \`node scripts/crabbox-wrapper.mjs warmup\`.`);process.exit(o)}child.on(`error`,e=>{if(childTreeShutdownStarted)return;childTreeShutdownStarted=true;console.error(`[crabbox] failed to execute ${displayBinary}: ${e.message}`);(async()=>{if(child.pid)await settleChildTree(child,`SIGTERM`);else childTreeSettled=true;cleanupOnce();process.exit(2)})()});if(fullCheckout)try{stopFullCheckoutKeepalive=startFullCheckoutKeepalive(fullCheckout,{intervalMs:fullCheckoutKeepaliveIntervalMsValue,onMissing:()=>{exitAfterChildTreeTermination(child,`SIGTERM`,1)}})}catch(e){await settleChildTree(child,`SIGTERM`);cleanupOnce();throw e}function settleChildTree(e,t){return childSettlement??=finalizeManagedChild(e,t,{platform:process.platform,runTaskkill:spawnSync,forceKillDelayMs:childKillGraceMs,drainTimeoutMs:childKillGraceMs,onTerminated:()=>{try{sourceStaging?.settled(capturedLeaseId?[capturedLeaseId]:void 0)}catch(e){console.error(`[crabbox] staging settlement receipt failed: `+(e instanceof Error?e.message:String(e)))}}}).then(()=>{childTreeSettled=true;runningChild=void 0;return true},e=>{childTreeSettled=!hasUnjoinedWork(e);if(childTreeSettled)runningChild=void 0;console.error(`[crabbox] child cleanup failed: ${e instanceof Error?e.message:String(e)}`);process.exitCode||=1;return false})}async function exitAfterChildTreeTermination(e,t,n){if(childTreeShutdownStarted)return;childTreeShutdownStarted=true;await settleChildTree(e,t);cleanupOnce();process.exit(n)}function resolveChildKillGraceMs(e){if(!e.VITEST||!e.OPENCLAW_TEST_CRABBOX_CHILD_KILL_GRACE_MS)return 5e3;const t=Number.parseInt(e.OPENCLAW_TEST_CRABBOX_CHILD_KILL_GRACE_MS,10);return Number.isFinite(t)&&t>=0?t:5e3}function resolveMetadataProbeTimeoutMs(e){if(!e.VITEST||!e.OPENCLAW_TEST_CRABBOX_METADATA_PROBE_TIMEOUT_MS)return CRABBOX_METADATA_PROBE_TIMEOUT_MS;const t=Number.parseInt(e.OPENCLAW_TEST_CRABBOX_METADATA_PROBE_TIMEOUT_MS,10);return Number.isFinite(t)&&t>0?t:CRABBOX_METADATA_PROBE_TIMEOUT_MS}export{};