just-bash 2.15.0-executor.0 → 2.15.1-executor.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1411,7 +1411,7 @@ ${e} ()
1411
1411
  `,127):z(`bash: ${t}: command not found
1412
1412
  `,127);if("error"in c)return c.error==="permission_denied"?z(`bash: ${t}: Permission denied
1413
1413
  `,126):z(`bash: ${t}: No such file or directory
1414
- `,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let p=r||i.state.groupStdin||"",h=o(),d={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:h,stdin:p,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,executorInvokeTool:i.executorInvokeTool},m=i7(d,t);try{let g=()=>Rt(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(n,m));return u.trusted?await yt.runTrustedAsync(()=>g()):await g()}catch(g){if(g instanceof K||g instanceof fe)throw g;return z(`${t}: ${Me(Ve(g))}
1414
+ `,127);if("script"in c)return t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;t.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(t,f));let p=r||i.state.groupStdin||"",h=o(),d={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:h,stdin:p,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,executorInvokeTool:i.executorInvokeTool,executorExecFn:i.executorExecFn},m=i7(d,t);try{let g=()=>Rt(i.requireDefenseContext,"command",`${t} execution`,()=>u.execute(n,m));return u.trusted?await yt.runTrustedAsync(()=>g()):await g()}catch(g){if(g instanceof K||g instanceof fe)throw g;return z(`${t}: ${Me(Ve(g))}
1415
1415
  `)}}Dt();we();_t();async function qu(e,t){let n=e.state.inCondition;e.state.inCondition=!0;let r="",s="",i=0;try{for(let o of t){let a=await e.executeStatement(o);r+=a.stdout,s+=a.stderr,i=a.exitCode}}finally{e.state.inCondition=n}return{stdout:r,stderr:s,exitCode:i}}we();Yt();function mi(e,t,n,r){if(e instanceof Ct)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:"rethrow",stdout:t,stderr:n,error:e}):{action:"break",stdout:t,stderr:n};if(e instanceof vt)return t+=e.stdout,n+=e.stderr,e.levels>1&&r>1?(e.levels--,e.stdout=t,e.stderr=n,{action:"rethrow",stdout:t,stderr:n,error:e}):{action:"continue",stdout:t,stderr:n};if(e instanceof wt||e instanceof Mt||e instanceof de||e instanceof K)return e.prependOutput(t,n),{action:"rethrow",stdout:t,stderr:n,error:e};let s=Ve(e);return{action:"error",stdout:t,stderr:`${n}${s}
1416
1416
  `,exitCode:1}}we();Yt();async function da(e,t,n="",r=""){let s=n,i=r,o=0;try{for(let a of t){let l=await e.executeStatement(a);s+=l.stdout,i+=l.stderr,o=l.exitCode}}catch(a){if(xi(a)||a instanceof Mt||a instanceof de||a instanceof K||a instanceof In)throw a.prependOutput(s,i),a;return{stdout:s,stderr:`${i}${Ve(a)}
1417
1417
  `,exitCode:1}}return{stdout:s,stderr:i,exitCode:o}}async function d7(e,t){let n="",r="";for(let s of t.clauses){let i=await qu(e,s.condition);if(n+=i.stdout,r+=i.stderr,i.exitCode===0)return da(e,s.body,n,r)}return t.elseBody?da(e,t.elseBody,n,r):H(n,r,0)}async function m7(e,t){let n=await Wn(e,t.redirections);if(n)return n;let r="",s="",i=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t.variable))return z(`bash: \`${t.variable}': not a valid identifier
@@ -1451,7 +1451,7 @@ sys 0m0.000s
1451
1451
  `,1)}e.state.groupStdin=c;let u=H(s,i,o);return Ze(e,u,t.redirections)}async function O7(e,t,n,r,s){let i;try{i=await e.fs.readFile(t)}catch{return z(`bash: ${t}: No such file or directory
1452
1452
  `,127)}if(i.startsWith("#!")){let g=i.indexOf(`
1453
1453
  `);g!==-1&&(i=i.slice(g+1))}let o=new Map(e.state.env),a=e.state.cwd,l={...e.state.options},c=e.state.loopDepth,u=e.state.parentHasLoopContext,f=e.state.lastArg,p=e.state.bashPid,h=e.state.groupStdin,d=e.state.currentSource;e.state.parentHasLoopContext=c>0,e.state.loopDepth=0,e.state.bashPid=e.state.nextVirtualPid++,r&&(e.state.groupStdin=r),e.state.currentSource=t,e.state.env.set("0",t),e.state.env.set("#",String(n.length)),e.state.env.set("@",n.join(" ")),e.state.env.set("*",n.join(" "));for(let g=0;g<n.length&&g<9;g++)e.state.env.set(String(g+1),n[g]);for(let g=n.length+1;g<=9;g++)e.state.env.delete(String(g));let m=()=>{e.state.env=o,e.state.cwd=a,e.state.options=l,e.state.loopDepth=c,e.state.parentHasLoopContext=u,e.state.lastArg=f,e.state.bashPid=p,e.state.groupStdin=h,e.state.currentSource=d};try{let y=new le().parse(i),b=await s(y);return m(),b}catch(g){if(m(),g instanceof de||g instanceof K)throw g;if(g.name==="ParseException")return z(`bash: ${t}: ${g.message}
1454
- `);throw g}}var gi=class{ctx;constructor(t,n){this.ctx={state:n,fs:t.fs,commands:t.commands,limits:t.limits,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,executorInvokeTool:t.executorInvokeTool}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||yt.isInSandboxedContext())return;let n=`interpreter ${t} attempted outside defense context`;throw new fe(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:yt.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(t){this.assertDefenseContext("execution");let n="",r="",s=0,i=this.ctx.limits.maxOutputSize,o=(a,l)=>{n.length+r.length+a.length+l.length>i&&Un(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),n+=a,r+=l};for(let a of t.statements)try{let l=await this.executeStatement(a);o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s))}catch(l){if(l instanceof de)throw l.prependOutput(n,r),l;if(l instanceof Xt)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof K)throw l;if(l instanceof Mt)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof It)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof $t)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof Pe){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof zr){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof Ct||l instanceof vt){if(this.ctx.state.loopDepth>0)throw l.prependOutput(n,r),l;o(l.stdout,l.stderr);continue}throw l instanceof wt&&l.prependOutput(n,r),l}return{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)}}async executeUserScript(t,n,r=""){return O7(this.ctx,t,n,r,s=>this.executeScript(s))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new Hr;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Un(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),t.deferredError)throw new bt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return ge;this.ctx.state.errexitSafe=!1;let n="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText}
1454
+ `);throw g}}var gi=class{ctx;constructor(t,n){this.ctx={state:n,fs:t.fs,commands:t.commands,limits:t.limits,execFn:t.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:t.fetch,sleep:t.sleep,trace:t.trace,coverage:t.coverage,requireDefenseContext:t.requireDefenseContext??!1,jsBootstrapCode:t.jsBootstrapCode,executorInvokeTool:t.executorInvokeTool,executorExecFn:t.executorExecFn}}assertDefenseContext(t){if(!this.ctx.requireDefenseContext||yt.isInSandboxedContext())return;let n=`interpreter ${t} attempted outside defense context`;throw new fe(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:yt.getCurrentExecutionId()})}buildExportedEnv(){let t=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(t)for(let i of t)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(t){this.assertDefenseContext("execution");let n="",r="",s=0,i=this.ctx.limits.maxOutputSize,o=(a,l)=>{n.length+r.length+a.length+l.length>i&&Un(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),n+=a,r+=l};for(let a of t.statements)try{let l=await this.executeStatement(a);o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s))}catch(l){if(l instanceof de)throw l.prependOutput(n,r),l;if(l instanceof Xt)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof K)throw l;if(l instanceof Mt)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof It)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof $t)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)};if(l instanceof Pe){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof zr){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof Ct||l instanceof vt){if(this.ctx.state.loopDepth>0)throw l.prependOutput(n,r),l;o(l.stdout,l.stderr);continue}throw l instanceof wt&&l.prependOutput(n,r),l}return{stdout:n,stderr:r,exitCode:s,env:xt(this.ctx.state.env)}}async executeUserScript(t,n,r=""){return O7(this.ctx,t,n,r,s=>this.executeScript(s))}async executeStatement(t){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new Hr;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&Un(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),t.deferredError)throw new bt(t.deferredError.message,t.line??1,1);if(this.ctx.state.options.noexec)return ge;this.ctx.state.errexitSafe=!1;let n="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&t.sourceText&&(r+=`${t.sourceText}
1455
1455
  `);let s=0,i=-1,o=!1;for(let c=0;c<t.pipelines.length;c++){let u=t.pipelines[c],f=c>0?t.operators[c-1]:null;if(f==="&&"&&s!==0||f==="||"&&s===0)continue;let p=await this.executePipeline(u);n+=p.stdout,r+=p.stderr,s=p.exitCode,i=c,o=u.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s))}let a=i<t.pipelines.length-1,l=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||l,this.ctx.state.options.errexit&&s!==0&&i===t.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!l)throw new Mt(s,n,r);return H(n,r,s)}async executePipeline(t){return v7(this.ctx,t,(n,r)=>this.executeCommand(n,r))}async executeCommand(t,n){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${t.type}`),t.type){case"SimpleCommand":return this.executeSimpleCommand(t,n);case"If":return d7(this.ctx,t);case"For":return m7(this.ctx,t);case"CStyleFor":return g7(this.ctx,t);case"While":return y7(this.ctx,t,n);case"Until":return b7(this.ctx,t);case"Case":return w7(this.ctx,t);case"Subshell":return this.executeSubshell(t,n);case"Group":return this.executeGroup(t,n);case"FunctionDef":return _6(this.ctx,t);case"ArithmeticCommand":return this.executeArithmeticCommand(t);case"ConditionalCommand":return this.executeConditionalCommand(t);default:return ge}}async executeSimpleCommand(t,n){try{return await this.executeSimpleCommandInner(t,n)}catch(r){if(r instanceof Nn)return z(r.stderr);throw r}}async executeSimpleCommandInner(t,n){if(t.line!==void 0&&(this.ctx.state.currentLine=t.line),this.ctx.state.shoptOptions.expand_aliases&&t.name){let x=t,A=100;for(;A>0;){let $=this.expandAlias(x);if($===x)break;x=$,A--}this.aliasExpansionStack.clear(),x!==t&&(t=x)}this.ctx.state.expansionStderr="";let r=await k7(this.ctx,t);if(r.error)return r.error;let s=r.tempAssignments,i=r.xtraceOutput;if(!t.name){if(t.redirections.length>0){let A=await Wn(this.ctx,t.redirections);if(A)return A;let $=H("",i,0);return Ze(this.ctx,$,t.redirections)}this.ctx.state.lastArg="";let x=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",H("",x,this.ctx.state.lastExitCode)}let o=t.name&&Zu(t.name,["local","declare","typeset","export","readonly"]),a=Array.from(s.keys());if(a.length>0&&!o){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let x of a)this.ctx.state.tempExportedVars.add(x)}let l=await oa(this.ctx,t.redirections);if(l){for(let[x,A]of s)A===void 0?this.ctx.state.env.delete(x):this.ctx.state.env.set(x,A);return l}let c=-1;for(let x of t.redirections){if((x.operator==="<<"||x.operator==="<<-")&&x.target.type==="HereDoc"){let A=x.target,$=await se(this.ctx,A.content);A.stripTabs&&($=$.split(`
1456
1456
  `).map(F=>F.replace(/^\t+/,"")).join(`
1457
1457
  `));let O=x.fd??0;O!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),Nt(this.ctx),this.ctx.state.fileDescriptors.set(O,$)):n=$;continue}if(x.operator==="<<<"&&x.target.type==="Word"){n=`${await se(this.ctx,x.target)}
@@ -1483,11 +1483,11 @@ ${t}
1483
1483
  esac${kn(e.redirections)}`}function YS(e){let t=e.patterns.map(Ft).join(" | "),n=pn(e.body);return n?`${t})
1484
1484
  ${n}
1485
1485
  ${e.terminator}`:`${t})
1486
- ${e.terminator}`}function JS(e){return`(${pn(e.body)})${kn(e.redirections)}`}function eC(e){return`{ ${pn(e.body)}; }${kn(e.redirections)}`}function tC(e){return`((${ze(e.expression.expression)}))${kn(e.redirections)}`}function nC(e){return`[[ ${Fr(e.expression)} ]]${kn(e.redirections)}`}function rC(e){let t=W7(e.body);return`${e.name}() ${t}${kn(e.redirections)}`}function ze(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${ze(e.left)} ${e.operator} ${ze(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${ze(e.operand)}`:`${ze(e.operand)}${e.operator}`;case"ArithTernary":return`${ze(e.condition)} ? ${ze(e.consequent)} : ${ze(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${ze(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${ze(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${ze(e.target)}[${ze(e.subscript)}]`:ze(e.target)} ${e.operator} ${ze(e.value)}`;case"ArithDynamicElement":return`${ze(e.nameExpr)}[${ze(e.subscript)}]`;case"ArithGroup":return`(${ze(e.expression)})`;case"ArithNested":return`$((${ze(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${ze(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(ze).join("");case"ArithDoubleSubscript":return`${e.array}[${ze(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function Fr(e){switch(e.type){case"CondBinary":return`${Ft(e.left)} ${e.operator} ${Ft(e.right)}`;case"CondUnary":return`${e.operator} ${Ft(e.operand)}`;case"CondNot":return`! ${Fr(e.operand)}`;case"CondAnd":return`${Fr(e.left)} && ${Fr(e.right)}`;case"CondOr":return`${Fr(e.left)} || ${Fr(e.right)}`;case"CondGroup":return`( ${Fr(e.expression)} )`;case"CondWord":return Ft(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var Ju=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;executorInvokeTool;executorSetup;executorApproval;executorSDK;executorInitPromise;transformPlugins=[];state;constructor(t={}){let n=t.fs??new Ir(t.files);this.fs=n,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
1486
+ ${e.terminator}`}function JS(e){return`(${pn(e.body)})${kn(e.redirections)}`}function eC(e){return`{ ${pn(e.body)}; }${kn(e.redirections)}`}function tC(e){return`((${ze(e.expression.expression)}))${kn(e.redirections)}`}function nC(e){return`[[ ${Fr(e.expression)} ]]${kn(e.redirections)}`}function rC(e){let t=W7(e.body);return`${e.name}() ${t}${kn(e.redirections)}`}function ze(e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return e.hasDollarPrefix?`$${e.name}`:e.name;case"ArithSpecialVar":return`$${e.name}`;case"ArithBinary":return`${ze(e.left)} ${e.operator} ${ze(e.right)}`;case"ArithUnary":return e.prefix?`${e.operator}${ze(e.operand)}`:`${ze(e.operand)}${e.operator}`;case"ArithTernary":return`${ze(e.condition)} ? ${ze(e.consequent)} : ${ze(e.alternate)}`;case"ArithAssignment":return`${e.subscript?`${e.variable}[${ze(e.subscript)}]`:e.stringKey!==void 0?`${e.variable}[${e.stringKey}]`:e.variable} ${e.operator} ${ze(e.value)}`;case"ArithDynamicAssignment":return`${e.subscript?`${ze(e.target)}[${ze(e.subscript)}]`:ze(e.target)} ${e.operator} ${ze(e.value)}`;case"ArithDynamicElement":return`${ze(e.nameExpr)}[${ze(e.subscript)}]`;case"ArithGroup":return`(${ze(e.expression)})`;case"ArithNested":return`$((${ze(e.expression)}))`;case"ArithCommandSubst":return`$(${e.command})`;case"ArithBracedExpansion":return`\${${e.content}}`;case"ArithArrayElement":return e.stringKey!==void 0?`${e.array}[${e.stringKey}]`:e.index?`${e.array}[${ze(e.index)}]`:e.array;case"ArithDynamicBase":return`\${${e.baseExpr}}#${e.value}`;case"ArithDynamicNumber":return`\${${e.prefix}}${e.suffix}`;case"ArithConcat":return e.parts.map(ze).join("");case"ArithDoubleSubscript":return`${e.array}[${ze(e.index)}]`;case"ArithNumberSubscript":return`${e.number}[${e.errorToken}]`;case"ArithSyntaxError":return e.errorToken;case"ArithSingleQuote":return`'${e.content}'`;default:{let t=e;throw new Error(`Unsupported arithmetic expression type: ${t.type}`)}}}function Fr(e){switch(e.type){case"CondBinary":return`${Ft(e.left)} ${e.operator} ${Ft(e.right)}`;case"CondUnary":return`${e.operator} ${Ft(e.operand)}`;case"CondNot":return`! ${Fr(e.operand)}`;case"CondAnd":return`${Fr(e.left)} && ${Fr(e.right)}`;case"CondOr":return`${Fr(e.left)} || ${Fr(e.right)}`;case"CondGroup":return`( ${Fr(e.expression)} )`;case"CondWord":return Ft(e.word);default:{let t=e;throw new Error(`Unsupported conditional expression type: ${t.type}`)}}}var Ju=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;executorInvokeTool;executorSetup;executorApproval;executorSDK;executorInitPromise;executorExecFn;transformPlugins=[];state;constructor(t={}){let n=t.fs??new Ir(t.files);this.fs=n,this.useDefaultLayout=!t.cwd&&!t.files;let r=t.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
1487
1487
  `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(t.env??{})]);if(this.limits=R7({...t.executionLimits,...t.maxCallDepth!==void 0&&{maxCallDepth:t.maxCallDepth},...t.maxCommandCount!==void 0&&{maxCommandCount:t.maxCommandCount},...t.maxLoopIterations!==void 0&&{maxLoopIterations:t.maxLoopIterations}}),t.fetch?this.secureFetch=t.fetch:t.network&&(this.secureFetch=Yu(t.network)),this.sleepFn=t.sleep,this.traceFn=t.trace,this.logger=t.logger,this.defenseInDepthConfig=t.defenseInDepth??!0,this.coverageWriter=t.coverage,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:t.processInfo?.pid??1,virtualPpid:t.processInfo?.ppid??0,virtualUid:t.processInfo?.uid??1e3,virtualGid:t.processInfo?.gid??1e3,bashPid:t.processInfo?.pid??1,nextVirtualPid:(t.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(t.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",fc(this.state.options)),this.state.env.set("BASHOPTS",pc(this.state.shoptOptions)),Gm(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&n instanceof Ir)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let i of Dm(t.commands))this.registerCommand(i);if(t.fetch||t.network)for(let i of _m())this.registerCommand(i);if(t.python)for(let i of Fm())this.registerCommand(i);if(t.javascript||t.executor){for(let o of Lm())this.registerCommand(o);let i=typeof t.javascript=="object"?t.javascript:Object.create(null);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap)}if(t.executor?.tools){let i=t.executor.tools;this.executorInvokeTool=async(o,a)=>{if(!Object.hasOwn(i,o))throw new Error(`Unknown tool: ${o}`);let l=i[o],c;try{c=a?JSON.parse(a):void 0}catch{c=void 0}let u=await l.execute(c);return u!==void 0?JSON.stringify(u):""}}if(t.executor?.setup&&(this.executorSetup=t.executor.setup),t.executor?.onToolApproval&&(this.executorApproval=t.executor.onToolApproval),t.customCommands)for(let i of t.customCommands)Mm(i)?this.registerCommand(Um(i)):this.registerCommand({...i,trusted:i.trusted??!0})}registerCommand(t){this.commands.set(t.name,t);let n=this.fs;if(typeof n.writeFileSync=="function"){let r=`#!/bin/bash
1488
1488
  # Built-in command: ${t.name}
1489
- `;try{n.writeFileSync(`/bin/${t.name}`,r)}catch{}try{n.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=G7(t.stdout),t.stderr=G7(t.stderr),t}async ensureExecutorReady(){if(!(!this.executorSetup||this.executorSDK)){if(this.executorInitPromise){await this.executorInitPromise;return}this.executorInitPromise=(async()=>{let t="./executor-init.js",{initExecutorSDK:n}=await import(t),r=this.executorSetup;if(!r)return;let{sdk:s,invokeTool:i}=await n(r,this.executorApproval,this.fs,()=>this.state.cwd,()=>this.state.env,()=>this.limits);this.executorSDK=s,this.executorInvokeTool=i})(),await this.executorInitPromise}}async exec(t,n){if(await this.ensureExecutorReady(),this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
1490
- `,exitCode:1,env:an(this.state.env,n?.env)};if(!t.trim())return{stdout:"",stderr:"",exitCode:0,env:an(this.state.env,n?.env)};this.logger?.info("exec",{command:t});let r=n?.cwd??this.state.cwd,s,i=r;if(n?.cwd)if(n.env&&"PWD"in n.env)s=n.env.PWD;else if(n?.env&&!("PWD"in n.env))try{s=await this.fs.realpath(r),i=s}catch{s=r}else s=r;let o=n?.replaceEnv?new Map:new Map(this.state.env);if(n?.env)for(let[f,p]of Object.entries(n.env))o.set(f,p);s!==void 0&&o.set("PWD",s);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:n?.stdin,signal:n?.signal,extraArgs:n?.args},l=t;n?.rawScript||(l=V7(t));let c=this.defenseInDepthConfig?yt.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let p=wn(l,{maxHeredocSize:this.limits.maxHeredocSize}),h;if(this.transformPlugins.length>0){let b=Object.create(null);for(let w of this.transformPlugins){let x=w.transform({ast:p,metadata:b});p=x.ast,x.metadata&&(b=wr(b,x.metadata))}h=b}let d={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,executorInvokeTool:this.executorInvokeTool},y=await new gi(d,a).executeScript(p);return h&&(y.metadata=h),this.logResult(y)};return u?await u.run(f):await f()}catch(f){if(f instanceof de)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:an(this.state.env,n?.env)});if(f instanceof Xt)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:an(this.state.env,n?.env)});if(f instanceof Pe)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:an(this.state.env,n?.env)});if(f instanceof Hr)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:an(this.state.env,n?.env)});if(f instanceof K)return this.logResult({stdout:f.stdout,stderr:Me(f.stderr),exitCode:K.EXIT_CODE,env:an(this.state.env,n?.env)});if(f instanceof fe)return this.logResult({stdout:"",stderr:`bash: security violation: ${Me(f.message)}
1489
+ `;try{n.writeFileSync(`/bin/${t.name}`,r)}catch{}try{n.writeFileSync(`/usr/bin/${t.name}`,r)}catch{}}}logResult(t){return this.logger&&(t.stdout&&this.logger.debug("stdout",{output:t.stdout}),t.stderr&&this.logger.info("stderr",{output:t.stderr}),this.logger.info("exit",{exitCode:t.exitCode})),t.stdout=G7(t.stdout),t.stderr=G7(t.stderr),t}async ensureExecutorReady(){if(!(!this.executorSetup||this.executorSDK)){if(this.executorInitPromise){await this.executorInitPromise;return}this.executorInitPromise=(async()=>{let t="./executor-init.js",{initExecutorSDK:n}=await import(t),r=this.executorSetup;if(!r)return;let{sdk:s,executeViaSdk:i}=await n(r,this.executorApproval,this.fs,()=>this.state.cwd,()=>this.state.env,()=>this.limits);this.executorSDK=s,this.executorExecFn=i})(),await this.executorInitPromise}}async exec(t,n){if(await this.ensureExecutorReady(),this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
1490
+ `,exitCode:1,env:an(this.state.env,n?.env)};if(!t.trim())return{stdout:"",stderr:"",exitCode:0,env:an(this.state.env,n?.env)};this.logger?.info("exec",{command:t});let r=n?.cwd??this.state.cwd,s,i=r;if(n?.cwd)if(n.env&&"PWD"in n.env)s=n.env.PWD;else if(n?.env&&!("PWD"in n.env))try{s=await this.fs.realpath(r),i=s}catch{s=r}else s=r;let o=n?.replaceEnv?new Map:new Map(this.state.env);if(n?.env)for(let[f,p]of Object.entries(n.env))o.set(f,p);s!==void 0&&o.set("PWD",s);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:n?.stdin,signal:n?.signal,extraArgs:n?.args},l=t;n?.rawScript||(l=V7(t));let c=this.defenseInDepthConfig?yt.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let p=wn(l,{maxHeredocSize:this.limits.maxHeredocSize}),h;if(this.transformPlugins.length>0){let b=Object.create(null);for(let w of this.transformPlugins){let x=w.transform({ast:p,metadata:b});p=x.ast,x.metadata&&(b=wr(b,x.metadata))}h=b}let d={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,executorInvokeTool:this.executorInvokeTool,executorExecFn:this.executorExecFn},y=await new gi(d,a).executeScript(p);return h&&(y.metadata=h),this.logResult(y)};return u?await u.run(f):await f()}catch(f){if(f instanceof de)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:an(this.state.env,n?.env)});if(f instanceof Xt)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:an(this.state.env,n?.env)});if(f instanceof Pe)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:an(this.state.env,n?.env)});if(f instanceof Hr)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:an(this.state.env,n?.env)});if(f instanceof K)return this.logResult({stdout:f.stdout,stderr:Me(f.stderr),exitCode:K.EXIT_CODE,env:an(this.state.env,n?.env)});if(f instanceof fe)return this.logResult({stdout:"",stderr:`bash: security violation: ${Me(f.message)}
1491
1491
  `,exitCode:1,env:an(this.state.env,n?.env)});if(f.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${Me(f.message)}
1492
1492
  `,exitCode:2,env:an(this.state.env,n?.env)});if(f instanceof tr)return this.logResult({stdout:"",stderr:`bash: ${Me(f.message)}
1493
1493
  `,exitCode:2,env:an(this.state.env,n?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${Me(f.message)}
@@ -0,0 +1,99 @@
1
+ import{a as F,b as W}from"./chunk-B6O2PIY4.js";import"./chunk-XHM67O4N.js";import"./chunk-CWQS3NFK.js";import{a as T,b as E}from"./chunk-A5O5YHGN.js";import"./chunk-IPJHKYVM.js";import{a as M}from"./chunk-OJDRYQWQ.js";import{b as L}from"./chunk-5QMZ5MUS.js";import{a as O,b as k}from"./chunk-3THT3N7L.js";import{a as j}from"./chunk-44UOCSGV.js";import{b as B}from"./chunk-74CEPOFO.js";import"./chunk-DXB73IDG.js";import{AsyncLocalStorage as H}from"node:async_hooks";import{randomBytes as q}from"node:crypto";import{fileURLToPath as N}from"node:url";import{Worker as D}from"node:worker_threads";var _=1e4,I=6e4,R=new H,J=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
2
+
3
+ Usage: js-exec [OPTIONS] [-c CODE | FILE] [ARGS...]
4
+
5
+ Options:
6
+ -c CODE Execute inline code
7
+ -m, --module Enable ES module mode (import/export)
8
+ --strip-types Strip TypeScript type annotations
9
+ --version, -V Show version
10
+ --help Show this help
11
+
12
+ Examples:
13
+ js-exec -c "console.log(1 + 2)"
14
+ js-exec script.js
15
+ js-exec app.ts
16
+ echo 'console.log("hello")' | js-exec
17
+
18
+ File Extension Auto-Detection:
19
+ .js script mode (module mode if top-level await detected)
20
+ .mjs ES module mode
21
+ .ts, .mts ES module mode + TypeScript stripping
22
+
23
+ Node.js Compatibility:
24
+ Code written for Node.js largely works here. Both require and import
25
+ are supported, the node: prefix works, and standard globals like process,
26
+ console, and fetch are available. All I/O is synchronous.
27
+
28
+ Available modules:
29
+ fs, path, child_process, process, console,
30
+ os, url, assert, util, events, buffer, stream,
31
+ string_decoder, querystring
32
+
33
+ fs (global, require('fs'), or import from 'node:fs'):
34
+ readFileSync, writeFileSync, appendFileSync, copyFileSync, renameSync
35
+ readdirSync, mkdirSync, rmSync, unlinkSync, rmdirSync
36
+ statSync, lstatSync, existsSync, realpathSync, chmodSync
37
+ symlinkSync, readlinkSync, readFileBuffer
38
+ fs.promises.readFile, fs.promises.writeFile, fs.promises.access, ...
39
+
40
+ path: join, resolve, dirname, basename, extname, normalize,
41
+ relative, isAbsolute, parse, format, sep, delimiter
42
+
43
+ child_process:
44
+ execSync(cmd) throws on non-zero exit, returns stdout
45
+ spawnSync(cmd, args) returns { stdout, stderr, status }
46
+
47
+ process (also global): argv, cwd(), exit(), env, platform, arch,
48
+ version, versions
49
+
50
+ os: platform(), arch(), homedir(), tmpdir(), type(), hostname(),
51
+ EOL, cpus(), endianness()
52
+
53
+ url: URL, URLSearchParams, parse(), format()
54
+
55
+ assert: ok(), equal(), strictEqual(), deepEqual(), throws(),
56
+ doesNotThrow(), fail()
57
+
58
+ util: format(), inspect(), promisify(), types, inherits()
59
+
60
+ events: EventEmitter (on, once, emit, off, removeListener, ...)
61
+
62
+ buffer: Buffer.from(), Buffer.alloc(), Buffer.concat(),
63
+ Buffer.isBuffer(), toString(), slice(), equals()
64
+
65
+ stream: Readable, Writable, Duplex, Transform, PassThrough, pipeline
66
+
67
+ string_decoder: StringDecoder (write, end)
68
+
69
+ querystring: parse(), stringify(), escape(), unescape()
70
+
71
+ Other Globals:
72
+ console log (stdout), error/warn (stderr)
73
+ fetch(url, opts) HTTP; returns Promise<Response> (Web Fetch API)
74
+ URL, URLSearchParams, Headers, Request, Response
75
+ Buffer Buffer.from(), Buffer.alloc(), etc.
76
+
77
+ Not Available:
78
+ http, https, net, tls, crypto, zlib, dns, cluster, worker_threads,
79
+ vm, v8, readline, and other Node.js built-in modules that require
80
+ native bindings. Use fetch() for HTTP requests.
81
+
82
+ Limits:
83
+ Memory: 64 MB per execution
84
+ Timeout: 10 s (60 s with network; configurable via maxJsTimeoutMs)
85
+ Engine: QuickJS (compiled to WebAssembly)
86
+ `;function z(t){let e={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1};if(t.length===0)return e;for(let r=0;r<t.length;r++){let o=t[r];if(o==="-m"||o==="--module"){e.isModule=!0;continue}if(o==="--strip-types"){e.stripTypes=!0;continue}if(o==="-c")return r+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
87
+ `,exitCode:2}:(e.code=t[r+1],e.scriptArgs=t.slice(r+2),e);if(o==="--version"||o==="-V")return e.showVersion=!0,e;if(o.startsWith("-")&&o!=="-"&&o!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${o}'
88
+ `,exitCode:2};if(o==="--")return r+1<t.length&&(e.scriptFile=t[r+1],e.scriptArgs=t.slice(r+2)),e;if(!o.startsWith("-"))return e.scriptFile=o,e.scriptArgs=t.slice(r+1),e}return e}var i=null,b=null,a=[],n=null,V=N(new URL("./worker.js",import.meta.url));function w(){for(;a.length>0&&a[0].canceled;)a.shift();if(n||a.length===0)return;let t=a.shift();if(!t)return;n=t,G().postMessage(n.input)}function Q(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let r=t;if(typeof r.protocolToken!="string"||r.protocolToken!==e)return{success:!1,error:"Malformed worker response: invalid protocol token"};if(typeof r.success!="boolean")return{success:!1,error:"Malformed worker response: missing success flag"};if(r.success){let o={success:!0},s=t;return typeof s.executorResult=="string"&&(o.executorResult=s.executorResult),Array.isArray(s.executorLogs)&&(o.executorLogs=s.executorLogs),o}return{success:!1,error:typeof r.error=="string"&&r.error.length>0?r.error:"Worker execution failed"}}function G(){if(b&&(E(b),b=null),i)return i;let t=L.runTrusted(()=>new D(V));return i=t,t.on("message",e=>{if(i===t){if(n){let r=Q(e,n.input.protocolToken);n.resolve(r),n=null}a.length>0?w():K()}}),t.on("error",e=>{if(i===t){if(n){let r=k(j(e));n.resolve({success:!1,error:r}),n=null}for(let r of a)r.resolve({success:!1,error:"Worker crashed"});a.length=0,i=null}}),t.on("exit",()=>{i===t&&(i=null,n&&(n.resolve({success:!1,error:"Worker exited unexpectedly"}),n=null),a.length>0&&w())}),t}function K(){b=T(()=>{i&&!n&&a.length===0&&(i.terminate(),i=null)},5e3)}async function X(t,e,r,o=[],s,d,f){return R.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
89
+ `,exitCode:1}:Y(t,e,r,o,s,d,f)}async function Y(t,e,r,o=[],s,d,f){let y=F(),u=e.exec,h=u?(m,P)=>R.run(!0,()=>u(m,P)):void 0,l=new W(y,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,h,e.executorInvokeTool),x=e.limits?.maxJsTimeoutMs??_,g=e.fetch?Math.max(x,I):x,c={protocolToken:q(16).toString("hex"),sharedBuffer:y,jsCode:t,cwd:e.cwd,env:M(e.env),args:o,scriptPath:r,bootstrapCode:s,isModule:d,stripTypes:f,timeoutMs:g,hasExecutorTools:e.executorInvokeTool!==void 0},A,U=new Promise(m=>{A=m}),S={input:c,resolve:()=>{}},$=T(()=>{if(n===S){let m=i;m&&(i=null,m.terminate()),n=null,w()}else S.canceled=!0,n||w();S.resolve({success:!1,error:`Execution timeout: exceeded ${g}ms limit`})},g);S.resolve=m=>{E($),A(m)},a.push(S),w();let[v,C]=await Promise.all([l.run(g),U.catch(m=>({success:!1,error:k(j(m))}))]);return!C.success&&C.error?{stdout:v.stdout,stderr:`${v.stderr}js-exec: ${k(C.error)}
90
+ `,exitCode:v.exitCode||1}:v}async function de(t,e,r){if(R.getStore())return{result:null,error:"js-exec: recursive invocation is not supported"};let o=F(),s=new W(o,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,void 0,r),d=e.limits?.maxJsTimeoutMs??_,f=e.fetch?Math.max(d,I):d,u={protocolToken:q(16).toString("hex"),sharedBuffer:o,jsCode:t,cwd:e.cwd,env:M(e.env),args:[],executorMode:!0,timeoutMs:f},h,l=new Promise(c=>{h=c}),x={input:u,resolve:()=>{}},g=T(()=>{if(n===x){let c=i;c&&(i=null,c.terminate()),n=null,w()}else x.canceled=!0,n||w();x.resolve({success:!1,error:`Execution timeout: exceeded ${f}ms limit`})},f);x.resolve=c=>{E(g),h(c)},a.push(x),w();let[,p]=await Promise.all([s.run(f),l.catch(c=>({success:!1,error:k(j(c))}))]);if("executorLogs"in p||"executorResult"in p){if(p.error)return{result:null,error:p.error,logs:p.executorLogs};let c;if(p.executorResult!==void 0)try{c=JSON.parse(p.executorResult)}catch{c=p.executorResult}return{result:c??null,logs:p.executorLogs}}return{result:null,error:p.error||"Unknown execution error"}}var fe={name:"js-exec",async execute(t,e){if(B(t))return{stdout:J,stderr:"",exitCode:0};let r=z(t);if("exitCode"in r)return r;if(r.showVersion)return{stdout:`QuickJS (quickjs-emscripten)
91
+ `,stderr:"",exitCode:0};let o,s;if(r.code!==null)o=r.code,s="-c";else if(r.scriptFile!==null){let u=e.fs.resolvePath(e.cwd,r.scriptFile);if(!await e.fs.exists(u))return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': No such file or directory
92
+ `,exitCode:2};try{o=await e.fs.readFile(u),s=u}catch(h){return{stdout:"",stderr:`js-exec: can't open file '${r.scriptFile}': ${O(h.message)}
93
+ `,exitCode:2}}}else if(e.stdin.trim())o=e.stdin,s="<stdin>";else return{stdout:"",stderr:`js-exec: no input provided (use -c CODE or provide a script file)
94
+ `,exitCode:2};let d=r.isModule,f=r.stripTypes;if(s&&s!=="-c"&&s!=="<stdin>"&&((s.endsWith(".mjs")||s.endsWith(".mts")||s.endsWith(".ts"))&&(d=!0),(s.endsWith(".ts")||s.endsWith(".mts"))&&(f=!0)),!d&&/\bawait\s+[\w([`]/.test(o)&&(d=!0),e.executorExecFn){let u=await e.executorExecFn(o),h=u.logs??[];return{stdout:h.filter(l=>!l.startsWith("[error]")&&!l.startsWith("[warn]")).map(l=>`${l.replace(/^\[(log|info|debug)\] /,"")}
95
+ `).join(""),stderr:u.error?`${u.error}
96
+ `:h.filter(l=>l.startsWith("[error]")||l.startsWith("[warn]")).map(l=>`${l.replace(/^\[(error|warn)\] /,"")}
97
+ `).join(""),exitCode:u.error?1:0}}let y=e.jsBootstrapCode;return X(o,e,s,r.scriptArgs,y,d,f)}},pe={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node
98
+
99
+ ${J}`,exitCode:1}}};export{de as executeForExecutor,fe as jsExecCommand,pe as nodeStubCommand};
@@ -1214,9 +1214,9 @@ ${this.commandName}: execution timeout exceeded
1214
1214
  `,exitCode:2}}}else if(e.stdin.trim())r=e.stdin,s="<stdin>";else return{stdout:"",stderr:`python3: no input provided (use -c CODE, -m MODULE, or provide a script file)
1215
1215
  `,exitCode:2};return BB(r,e,s,n.scriptArgs)}},WB={name:"python",async execute(t,e){return BA.execute(t,e)}}});var Ry={};J(Ry,{executeForExecutor:()=>QB,jsExecCommand:()=>XB,nodeStubCommand:()=>JB});function qB(t){let e={code:null,scriptFile:null,showVersion:!1,scriptArgs:[],isModule:!1,stripTypes:!1};if(t.length===0)return e;for(let n=0;n<t.length;n++){let r=t[n];if(r==="-m"||r==="--module"){e.isModule=!0;continue}if(r==="--strip-types"){e.stripTypes=!0;continue}if(r==="-c")return n+1>=t.length?{stdout:"",stderr:`js-exec: option requires an argument -- 'c'
1216
1216
  `,exitCode:2}:(e.code=t[n+1],e.scriptArgs=t.slice(n+2),e);if(r==="--version"||r==="-V")return e.showVersion=!0,e;if(r.startsWith("-")&&r!=="-"&&r!=="--")return{stdout:"",stderr:`js-exec: unrecognized option '${r}'
1217
- `,exitCode:2};if(r==="--")return n+1<t.length&&(e.scriptFile=t[n+1],e.scriptArgs=t.slice(n+2)),e;if(!r.startsWith("-"))return e.scriptFile=r,e.scriptArgs=t.slice(n+1),e}return e}function ei(){for(;Ar.length>0&&Ar[0].canceled;)Ar.shift();if(Kt||Ar.length===0)return;let t=Ar.shift();if(!t)return;Kt=t,GB().postMessage(Kt.input)}function HB(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;return typeof n.protocolToken!="string"||n.protocolToken!==e?{success:!1,error:"Malformed worker response: invalid protocol token"}:typeof n.success!="boolean"?{success:!1,error:"Malformed worker response: missing success flag"}:n.success?{success:!0}:{success:!1,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}function GB(){if(Bf&&(Ot(Bf),Bf=null),Fn)return Fn;let t=it.runTrusted(()=>new qA.Worker(VB));return Fn=t,t.on("message",e=>{if(Fn===t){if(Kt){let n=HB(e,Kt.input.protocolToken);Kt.resolve(n),Kt=null}Ar.length>0?ei():KB()}}),t.on("error",e=>{if(Fn===t){if(Kt){let n=Pt(tt(e));Kt.resolve({success:!1,error:n}),Kt=null}for(let n of Ar)n.resolve({success:!1,error:"Worker crashed"});Ar.length=0,Fn=null}}),t.on("exit",()=>{Fn===t&&(Fn=null,Kt&&(Kt.resolve({success:!1,error:"Worker exited unexpectedly"}),Kt=null),Ar.length>0&&ei())}),t}function KB(){Bf=Qt(()=>{Fn&&!Kt&&Ar.length===0&&(Fn.terminate(),Fn=null)},5e3)}async function ZB(t,e,n,r=[],s,i,o){return Py.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
1217
+ `,exitCode:2};if(r==="--")return n+1<t.length&&(e.scriptFile=t[n+1],e.scriptArgs=t.slice(n+2)),e;if(!r.startsWith("-"))return e.scriptFile=r,e.scriptArgs=t.slice(n+1),e}return e}function ei(){for(;Ar.length>0&&Ar[0].canceled;)Ar.shift();if(Kt||Ar.length===0)return;let t=Ar.shift();if(!t)return;Kt=t,GB().postMessage(Kt.input)}function HB(t,e){if(!t||typeof t!="object")return{success:!1,error:"Malformed worker response"};let n=t;if(typeof n.protocolToken!="string"||n.protocolToken!==e)return{success:!1,error:"Malformed worker response: invalid protocol token"};if(typeof n.success!="boolean")return{success:!1,error:"Malformed worker response: missing success flag"};if(n.success){let r={success:!0},s=t;return typeof s.executorResult=="string"&&(r.executorResult=s.executorResult),Array.isArray(s.executorLogs)&&(r.executorLogs=s.executorLogs),r}return{success:!1,error:typeof n.error=="string"&&n.error.length>0?n.error:"Worker execution failed"}}function GB(){if(Bf&&(Ot(Bf),Bf=null),Fn)return Fn;let t=it.runTrusted(()=>new qA.Worker(VB));return Fn=t,t.on("message",e=>{if(Fn===t){if(Kt){let n=HB(e,Kt.input.protocolToken);Kt.resolve(n),Kt=null}Ar.length>0?ei():KB()}}),t.on("error",e=>{if(Fn===t){if(Kt){let n=Pt(tt(e));Kt.resolve({success:!1,error:n}),Kt=null}for(let n of Ar)n.resolve({success:!1,error:"Worker crashed"});Ar.length=0,Fn=null}}),t.on("exit",()=>{Fn===t&&(Fn=null,Kt&&(Kt.resolve({success:!1,error:"Worker exited unexpectedly"}),Kt=null),Ar.length>0&&ei())}),t}function KB(){Bf=Qt(()=>{Fn&&!Kt&&Ar.length===0&&(Fn.terminate(),Fn=null)},5e3)}async function ZB(t,e,n,r=[],s,i,o){return Py.getStore()?{stdout:"",stderr:`js-exec: recursive invocation is not supported
1218
1218
  `,exitCode:1}:YB(t,e,n,r,s,i,o)}async function YB(t,e,n,r=[],s,i,o){let a=$l(),l=e.exec,c=l?(S,N)=>Py.run(!0,()=>l(S,N)):void 0,u=new Mi(a,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,c,e.executorInvokeTool),f=e.limits?.maxJsTimeoutMs??VA,h=e.fetch?Math.max(f,HA):f,d={protocolToken:(0,Iy.randomBytes)(16).toString("hex"),sharedBuffer:a,jsCode:t,cwd:e.cwd,env:Mt(e.env),args:r,scriptPath:n,bootstrapCode:s,isModule:i,stripTypes:o,timeoutMs:h,hasExecutorTools:e.executorInvokeTool!==void 0},m,g=new Promise(S=>{m=S}),y={input:d,resolve:()=>{}},w=Qt(()=>{if(Kt===y){let S=Fn;S&&(Fn=null,S.terminate()),Kt=null,ei()}else y.canceled=!0,Kt||ei();y.resolve({success:!1,error:`Execution timeout: exceeded ${h}ms limit`})},h);y.resolve=S=>{Ot(w),m(S)},Ar.push(y),ei();let[b,E]=await Promise.all([u.run(h),g.catch(S=>({success:!1,error:Pt(tt(S))}))]);return!E.success&&E.error?{stdout:b.stdout,stderr:`${b.stderr}js-exec: ${Pt(E.error)}
1219
- `,exitCode:b.exitCode||1}:b}async function QB(t,e,n){if(Py.getStore())return{result:null,error:"js-exec: recursive invocation is not supported"};let r=$l(),s=new Mi(r,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,void 0,n),i=e.limits?.maxJsTimeoutMs??VA,o=e.fetch?Math.max(i,HA):i,l={protocolToken:(0,Iy.randomBytes)(16).toString("hex"),sharedBuffer:r,jsCode:t,cwd:e.cwd,env:Mt(e.env),args:[],executorMode:!0,timeoutMs:o},c,u=new Promise(d=>{c=d}),f={input:l,resolve:()=>{}},h=Qt(()=>{if(Kt===f){let d=Fn;d&&(Fn=null,d.terminate()),Kt=null,ei()}else f.canceled=!0,Kt||ei();f.resolve({success:!1,error:`Execution timeout: exceeded ${o}ms limit`})},o);f.resolve=d=>{Ot(h),c(d)},Ar.push(f),ei();let[,p]=await Promise.all([s.run(o),u.catch(d=>({success:!1,error:Pt(tt(d))}))]);if("executorResult"in p&&p.executorResult!==void 0){let d;try{d=JSON.parse(p.executorResult)}catch{d=p.executorResult}return{result:d,logs:p.executorLogs}}return{result:null,error:p.error||"Unknown execution error",logs:"executorLogs"in p?p.executorLogs:void 0}}var WA,Iy,jA,qA,eW,VA,HA,Py,GA,Fn,Bf,Ar,Kt,VB,XB,JB,$y=O(()=>{"use strict";WA=require("node:async_hooks"),Iy=require("node:crypto"),jA=require("node:url"),qA=require("node:worker_threads");vn();mr();On();tn();Kr();le();ky();zf();eW={},VA=1e4,HA=6e4,Py=new WA.AsyncLocalStorage,GA=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
1219
+ `,exitCode:b.exitCode||1}:b}async function QB(t,e,n){if(Py.getStore())return{result:null,error:"js-exec: recursive invocation is not supported"};let r=$l(),s=new Mi(r,e.fs,e.cwd,"js-exec",e.fetch,e.limits?.maxOutputSize??0,void 0,n),i=e.limits?.maxJsTimeoutMs??VA,o=e.fetch?Math.max(i,HA):i,l={protocolToken:(0,Iy.randomBytes)(16).toString("hex"),sharedBuffer:r,jsCode:t,cwd:e.cwd,env:Mt(e.env),args:[],executorMode:!0,timeoutMs:o},c,u=new Promise(d=>{c=d}),f={input:l,resolve:()=>{}},h=Qt(()=>{if(Kt===f){let d=Fn;d&&(Fn=null,d.terminate()),Kt=null,ei()}else f.canceled=!0,Kt||ei();f.resolve({success:!1,error:`Execution timeout: exceeded ${o}ms limit`})},o);f.resolve=d=>{Ot(h),c(d)},Ar.push(f),ei();let[,p]=await Promise.all([s.run(o),u.catch(d=>({success:!1,error:Pt(tt(d))}))]);if("executorLogs"in p||"executorResult"in p){if(p.error)return{result:null,error:p.error,logs:p.executorLogs};let d;if(p.executorResult!==void 0)try{d=JSON.parse(p.executorResult)}catch{d=p.executorResult}return{result:d??null,logs:p.executorLogs}}return{result:null,error:p.error||"Unknown execution error"}}var WA,Iy,jA,qA,eW,VA,HA,Py,GA,Fn,Bf,Ar,Kt,VB,XB,JB,$y=O(()=>{"use strict";WA=require("node:async_hooks"),Iy=require("node:crypto"),jA=require("node:url"),qA=require("node:worker_threads");vn();mr();On();tn();Kr();le();ky();zf();eW={},VA=1e4,HA=6e4,Py=new WA.AsyncLocalStorage,GA=`js-exec - Sandboxed JavaScript/TypeScript runtime with Node.js-compatible APIs
1220
1220
 
1221
1221
  Usage: js-exec [OPTIONS] [-c CODE | FILE] [ARGS...]
1222
1222
 
@@ -1305,7 +1305,10 @@ Limits:
1305
1305
  `,stderr:"",exitCode:0};let r,s;if(n.code!==null)r=n.code,s="-c";else if(n.scriptFile!==null){let l=e.fs.resolvePath(e.cwd,n.scriptFile);if(!await e.fs.exists(l))return{stdout:"",stderr:`js-exec: can't open file '${n.scriptFile}': No such file or directory
1306
1306
  `,exitCode:2};try{r=await e.fs.readFile(l),s=l}catch(c){return{stdout:"",stderr:`js-exec: can't open file '${n.scriptFile}': ${Ie(c.message)}
1307
1307
  `,exitCode:2}}}else if(e.stdin.trim())r=e.stdin,s="<stdin>";else return{stdout:"",stderr:`js-exec: no input provided (use -c CODE or provide a script file)
1308
- `,exitCode:2};let i=n.isModule,o=n.stripTypes;s&&s!=="-c"&&s!=="<stdin>"&&((s.endsWith(".mjs")||s.endsWith(".mts")||s.endsWith(".ts"))&&(i=!0),(s.endsWith(".ts")||s.endsWith(".mts"))&&(o=!0)),!i&&/\bawait\s+[\w([`]/.test(r)&&(i=!0);let a=e.jsBootstrapCode;return ZB(r,e,s,n.scriptArgs,a,i,o)}},JB={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node
1308
+ `,exitCode:2};let i=n.isModule,o=n.stripTypes;if(s&&s!=="-c"&&s!=="<stdin>"&&((s.endsWith(".mjs")||s.endsWith(".mts")||s.endsWith(".ts"))&&(i=!0),(s.endsWith(".ts")||s.endsWith(".mts"))&&(o=!0)),!i&&/\bawait\s+[\w([`]/.test(r)&&(i=!0),e.executorExecFn){let l=await e.executorExecFn(r),c=l.logs??[];return{stdout:c.filter(u=>!u.startsWith("[error]")&&!u.startsWith("[warn]")).map(u=>`${u.replace(/^\[(log|info|debug)\] /,"")}
1309
+ `).join(""),stderr:l.error?`${l.error}
1310
+ `:c.filter(u=>u.startsWith("[error]")||u.startsWith("[warn]")).map(u=>`${u.replace(/^\[(error|warn)\] /,"")}
1311
+ `).join(""),exitCode:l.error?1:0}}let a=e.jsBootstrapCode;return ZB(r,e,s,n.scriptArgs,a,i,o)}},JB={name:"node",async execute(){return{stdout:"",stderr:`node: this sandbox uses js-exec instead of node
1309
1312
 
1310
1313
  ${GA}`,exitCode:1}}}});function _y(t){let e=t.indexOf("=");if(e>=0){let n=t.slice(0,e),r=t.slice(e+1);return n?`${encodeURIComponent(n)}=${encodeURIComponent(r)}`:encodeURIComponent(r)}return encodeURIComponent(t)}function Fy(t){let e=t.indexOf("=");if(e<0)return null;let n=t.slice(0,e),r=t.slice(e+1),s,i,o=r.match(/;type=([^;]+)$/);o&&(i=o[1],r=r.slice(0,-o[0].length));let a=r.match(/;filename=([^;]+)/);return a&&(s=a[1],r=r.replace(a[0],"")),(r.startsWith("@")||r.startsWith("<"))&&(s=s??r.slice(1).split("/").pop()),{name:n,value:r,filename:s,contentType:i}}function KA(t,e){let n=`----CurlFormBoundary${Date.now().toString(36)}`,r=[];for(let s of t){let i=s.value;if(i.startsWith("@")||i.startsWith("<")){let a=i.slice(1);i=e.get(a)??""}let o=`--${n}\r
1311
1314
  `;s.filename?(o+=`Content-Disposition: form-data; name="${s.name}"; filename="${s.filename}"\r
@@ -2025,7 +2028,7 @@ ${t} ()
2025
2028
  `,127):q(`bash: ${e}: command not found
2026
2029
  `,127);if("error"in c)return c.error==="permission_denied"?q(`bash: ${e}: Permission denied
2027
2030
  `,126):q(`bash: ${e}: No such file or directory
2028
- `,127);if("script"in c)return e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,f));let h=r||i.state.groupStdin||"",p=o(),d={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:p,stdin:h,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,executorInvokeTool:i.executorInvokeTool},m=Dk(d,e);try{let g=()=>pn(i.requireDefenseContext,"command",`${e} execution`,()=>u.execute(n,m));return u.trusted?await it.runTrustedAsync(()=>g()):await g()}catch(g){if(g instanceof te||g instanceof be)throw g;return q(`${e}: ${Ie(tt(g))}
2031
+ `,127);if("script"in c)return e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,c.path)),await a(c.path,n,r);let{cmd:u,path:f}=c;e.includes("/")||(i.state.hashTable||(i.state.hashTable=new Map),i.state.hashTable.set(e,f));let h=r||i.state.groupStdin||"",p=o(),d={fs:i.fs,cwd:i.state.cwd,env:i.state.env,exportedEnv:p,stdin:h,limits:i.limits,exec:i.execFn,fetch:i.fetch,getRegisteredCommands:()=>Array.from(i.commands.keys()),sleep:i.sleep,trace:i.trace,fileDescriptors:i.state.fileDescriptors,xpgEcho:i.state.shoptOptions.xpg_echo,coverage:i.coverage,signal:i.state.signal,requireDefenseContext:i.requireDefenseContext,jsBootstrapCode:i.jsBootstrapCode,executorInvokeTool:i.executorInvokeTool,executorExecFn:i.executorExecFn},m=Dk(d,e);try{let g=()=>pn(i.requireDefenseContext,"command",`${e} execution`,()=>u.execute(n,m));return u.trusted?await it.runTrustedAsync(()=>g()):await g()}catch(g){if(g instanceof te||g instanceof be)throw g;return q(`${e}: ${Ie(tt(g))}
2029
2032
  `)}}Mn();_e();Un();async function vw(t,e){let n=t.state.inCondition;t.state.inCondition=!0;let r="",s="",i=0;try{for(let o of e){let a=await t.executeStatement(o);r+=a.stdout,s+=a.stderr,i=a.exitCode}}finally{t.state.inCondition=n}return{stdout:r,stderr:s,exitCode:i}}_e();On();function Hl(t,e,n,r){if(t instanceof Sn)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"break",stdout:e,stderr:n};if(t instanceof An)return e+=t.stdout,n+=t.stderr,t.levels>1&&r>1?(t.levels--,t.stdout=e,t.stderr=n,{action:"rethrow",stdout:e,stderr:n,error:t}):{action:"continue",stdout:e,stderr:n};if(t instanceof fn||t instanceof Bn||t instanceof Ne||t instanceof te)return t.prependOutput(e,n),{action:"rethrow",stdout:e,stderr:n,error:t};let s=tt(t);return{action:"error",stdout:e,stderr:`${n}${s}
2030
2033
  `,exitCode:1}}_e();On();async function _h(t,e,n="",r=""){let s=n,i=r,o=0;try{for(let a of e){let l=await t.executeStatement(a);s+=l.stdout,i+=l.stderr,o=l.exitCode}}catch(a){if(ec(a)||a instanceof Bn||a instanceof Ne||a instanceof te||a instanceof Yr)throw a.prependOutput(s,i),a;return{stdout:s,stderr:`${i}${tt(a)}
2031
2034
  `,exitCode:1}}return{stdout:s,stderr:i,exitCode:o}}async function Vk(t,e){let n="",r="";for(let s of e.clauses){let i=await vw(t,s.condition);if(n+=i.stdout,r+=i.stderr,i.exitCode===0)return _h(t,s.body,n,r)}return e.elseBody?_h(t,e.elseBody,n,r):K(n,r,0)}async function Hk(t,e){let n=await ps(t,e.redirections);if(n)return n;let r="",s="",i=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return q(`bash: \`${e.variable}': not a valid identifier
@@ -2065,7 +2068,7 @@ sys 0m0.000s
2065
2068
  `,1)}t.state.groupStdin=c;let u=K(s,i,o);return Nt(t,u,e.redirections)}async function aN(t,e,n,r,s){let i;try{i=await t.fs.readFile(e)}catch{return q(`bash: ${e}: No such file or directory
2066
2069
  `,127)}if(i.startsWith("#!")){let g=i.indexOf(`
2067
2070
  `);g!==-1&&(i=i.slice(g+1))}let o=new Map(t.state.env),a=t.state.cwd,l={...t.state.options},c=t.state.loopDepth,u=t.state.parentHasLoopContext,f=t.state.lastArg,h=t.state.bashPid,p=t.state.groupStdin,d=t.state.currentSource;t.state.parentHasLoopContext=c>0,t.state.loopDepth=0,t.state.bashPid=t.state.nextVirtualPid++,r&&(t.state.groupStdin=r),t.state.currentSource=e,t.state.env.set("0",e),t.state.env.set("#",String(n.length)),t.state.env.set("@",n.join(" ")),t.state.env.set("*",n.join(" "));for(let g=0;g<n.length&&g<9;g++)t.state.env.set(String(g+1),n[g]);for(let g=n.length+1;g<=9;g++)t.state.env.delete(String(g));let m=()=>{t.state.env=o,t.state.cwd=a,t.state.options=l,t.state.loopDepth=c,t.state.parentHasLoopContext=u,t.state.lastArg=f,t.state.bashPid=h,t.state.groupStdin=p,t.state.currentSource=d};try{let y=new ve().parse(i),w=await s(y);return m(),w}catch(g){if(m(),g instanceof Ne||g instanceof te)throw g;if(g.name==="ParseException")return q(`bash: ${e}: ${g.message}
2068
- `);throw g}}var Gl=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode,executorInvokeTool:e.executorInvokeTool}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||it.isInSandboxedContext())return;let n=`interpreter ${e} attempted outside defense context`;throw new be(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:it.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(e)for(let i of e)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(e){this.assertDefenseContext("execution");let n="",r="",s=0,i=this.ctx.limits.maxOutputSize,o=(a,l)=>{n.length+r.length+a.length+l.length>i&&fs(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),n+=a,r+=l};for(let a of e.statements)try{let l=await this.executeStatement(a);o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s))}catch(l){if(l instanceof Ne)throw l.prependOutput(n,r),l;if(l instanceof sr)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof te)throw l;if(l instanceof Bn)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof Nn)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof Tn)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof ot){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof no){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof Sn||l instanceof An){if(this.ctx.state.loopDepth>0)throw l.prependOutput(n,r),l;o(l.stdout,l.stderr);continue}throw l instanceof fn&&l.prependOutput(n,r),l}return{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)}}async executeUserScript(e,n,r=""){return aN(this.ctx,e,n,r,s=>this.executeScript(s))}async executeStatement(e){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new ro;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&fs(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),e.deferredError)throw new an(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return Re;this.ctx.state.errexitSafe=!1;let n="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&(r+=`${e.sourceText}
2071
+ `);throw g}}var Gl=class{ctx;constructor(e,n){this.ctx={state:n,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep,trace:e.trace,coverage:e.coverage,requireDefenseContext:e.requireDefenseContext??!1,jsBootstrapCode:e.jsBootstrapCode,executorInvokeTool:e.executorInvokeTool,executorExecFn:e.executorExecFn}}assertDefenseContext(e){if(!this.ctx.requireDefenseContext||it.isInSandboxedContext())return;let n=`interpreter ${e} attempted outside defense context`;throw new be(n,{timestamp:Date.now(),type:"missing_defense_context",message:n,path:"DefenseInDepthBox.context",stack:new Error().stack,executionId:it.getCurrentExecutionId()})}buildExportedEnv(){let e=this.ctx.state.exportedVars,n=this.ctx.state.tempExportedVars,r=new Set;if(e)for(let i of e)r.add(i);if(n)for(let i of n)r.add(i);if(r.size===0)return Object.create(null);let s=Object.create(null);for(let i of r){let o=this.ctx.state.env.get(i);o!==void 0&&(s[i]=o)}return s}async executeScript(e){this.assertDefenseContext("execution");let n="",r="",s=0,i=this.ctx.limits.maxOutputSize,o=(a,l)=>{n.length+r.length+a.length+l.length>i&&fs(`total output size exceeded (>${i} bytes), increase executionLimits.maxOutputSize`,"output_size"),n+=a,r+=l};for(let a of e.statements)try{let l=await this.executeStatement(a);o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s))}catch(l){if(l instanceof Ne)throw l.prependOutput(n,r),l;if(l instanceof sr)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof te)throw l;if(l instanceof Bn)return o(l.stdout,l.stderr),s=l.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof Nn)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof Tn)return o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s)),{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)};if(l instanceof ot){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof no){o(l.stdout,l.stderr),s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s));continue}if(l instanceof Sn||l instanceof An){if(this.ctx.state.loopDepth>0)throw l.prependOutput(n,r),l;o(l.stdout,l.stderr);continue}throw l instanceof fn&&l.prependOutput(n,r),l}return{stdout:n,stderr:r,exitCode:s,env:Mt(this.ctx.state.env)}}async executeUserScript(e,n,r=""){return aN(this.ctx,e,n,r,s=>this.executeScript(s))}async executeStatement(e){if(this.assertDefenseContext("statement"),this.ctx.state.signal?.aborted)throw new ro;if(this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&fs(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands"),e.deferredError)throw new an(e.deferredError.message,e.line??1,1);if(this.ctx.state.options.noexec)return Re;this.ctx.state.errexitSafe=!1;let n="",r="";this.ctx.state.options.verbose&&!this.ctx.state.suppressVerbose&&e.sourceText&&(r+=`${e.sourceText}
2069
2072
  `);let s=0,i=-1,o=!1;for(let c=0;c<e.pipelines.length;c++){let u=e.pipelines[c],f=c>0?e.operators[c-1]:null;if(f==="&&"&&s!==0||f==="||"&&s===0)continue;let h=await this.executePipeline(u);n+=h.stdout,r+=h.stderr,s=h.exitCode,i=c,o=u.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env.set("?",String(s))}let a=i<e.pipelines.length-1,l=this.ctx.state.errexitSafe;if(this.ctx.state.errexitSafe=a||o||l,this.ctx.state.options.errexit&&s!==0&&i===e.pipelines.length-1&&!o&&!this.ctx.state.inCondition&&!l)throw new Bn(s,n,r);return K(n,r,s)}async executePipeline(e){return nN(this.ctx,e,(n,r)=>this.executeCommand(n,r))}async executeCommand(e,n){switch(this.assertDefenseContext("command"),this.ctx.coverage?.hit(`bash:cmd:${e.type}`),e.type){case"SimpleCommand":return this.executeSimpleCommand(e,n);case"If":return Vk(this.ctx,e);case"For":return Hk(this.ctx,e);case"CStyleFor":return Gk(this.ctx,e);case"While":return Kk(this.ctx,e,n);case"Until":return Zk(this.ctx,e);case"Case":return Yk(this.ctx,e);case"Subshell":return this.executeSubshell(e,n);case"Group":return this.executeGroup(e,n);case"FunctionDef":return hk(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return Re}}async executeSimpleCommand(e,n){try{return await this.executeSimpleCommandInner(e,n)}catch(r){if(r instanceof Zr)return q(r.stderr);throw r}}async executeSimpleCommandInner(e,n){if(e.line!==void 0&&(this.ctx.state.currentLine=e.line),this.ctx.state.shoptOptions.expand_aliases&&e.name){let E=e,S=100;for(;S>0;){let N=this.expandAlias(E);if(N===E)break;E=N,S--}this.aliasExpansionStack.clear(),E!==e&&(e=E)}this.ctx.state.expansionStderr="";let r=await rN(this.ctx,e);if(r.error)return r.error;let s=r.tempAssignments,i=r.xtraceOutput;if(!e.name){if(e.redirections.length>0){let S=await ps(this.ctx,e.redirections);if(S)return S;let N=K("",i,0);return Nt(this.ctx,N,e.redirections)}this.ctx.state.lastArg="";let E=(this.ctx.state.expansionStderr||"")+i;return this.ctx.state.expansionStderr="",K("",E,this.ctx.state.lastExitCode)}let o=e.name&&Cw(e.name,["local","declare","typeset","export","readonly"]),a=Array.from(s.keys());if(a.length>0&&!o){this.ctx.state.tempExportedVars=this.ctx.state.tempExportedVars||new Set;for(let E of a)this.ctx.state.tempExportedVars.add(E)}let l=await kh(this.ctx,e.redirections);if(l){for(let[E,S]of s)S===void 0?this.ctx.state.env.delete(E):this.ctx.state.env.set(E,S);return l}let c=-1;for(let E of e.redirections){if((E.operator==="<<"||E.operator==="<<-")&&E.target.type==="HereDoc"){let S=E.target,N=await he(this.ctx,S.content);S.stripTabs&&(N=N.split(`
2070
2073
  `).map($=>$.replace(/^\t+/,"")).join(`
2071
2074
  `));let I=E.fd??0;I!==0?(this.ctx.state.fileDescriptors||(this.ctx.state.fileDescriptors=new Map),kn(this.ctx),this.ctx.state.fileDescriptors.set(I,N)):n=N;continue}if(E.operator==="<<<"&&E.target.type==="Word"){n=`${await he(this.ctx,E.target)}
@@ -2097,11 +2100,11 @@ ${e}
2097
2100
  esac${Vr(t.redirections)}`}function vV(t){let e=t.patterns.map(ln).join(" | "),n=Nr(t.body);return n?`${e})
2098
2101
  ${n}
2099
2102
  ${t.terminator}`:`${e})
2100
- ${t.terminator}`}function CV(t){return`(${Nr(t.body)})${Vr(t.redirections)}`}function kV(t){return`{ ${Nr(t.body)}; }${Vr(t.redirections)}`}function NV(t){return`((${xt(t.expression.expression)}))${Vr(t.redirections)}`}function TV(t){return`[[ ${Zi(t.expression)} ]]${Vr(t.redirections)}`}function OV(t){let e=yN(t.body);return`${t.name}() ${e}${Vr(t.redirections)}`}function xt(t){switch(t.type){case"ArithNumber":return String(t.value);case"ArithVariable":return t.hasDollarPrefix?`$${t.name}`:t.name;case"ArithSpecialVar":return`$${t.name}`;case"ArithBinary":return`${xt(t.left)} ${t.operator} ${xt(t.right)}`;case"ArithUnary":return t.prefix?`${t.operator}${xt(t.operand)}`:`${xt(t.operand)}${t.operator}`;case"ArithTernary":return`${xt(t.condition)} ? ${xt(t.consequent)} : ${xt(t.alternate)}`;case"ArithAssignment":return`${t.subscript?`${t.variable}[${xt(t.subscript)}]`:t.stringKey!==void 0?`${t.variable}[${t.stringKey}]`:t.variable} ${t.operator} ${xt(t.value)}`;case"ArithDynamicAssignment":return`${t.subscript?`${xt(t.target)}[${xt(t.subscript)}]`:xt(t.target)} ${t.operator} ${xt(t.value)}`;case"ArithDynamicElement":return`${xt(t.nameExpr)}[${xt(t.subscript)}]`;case"ArithGroup":return`(${xt(t.expression)})`;case"ArithNested":return`$((${xt(t.expression)}))`;case"ArithCommandSubst":return`$(${t.command})`;case"ArithBracedExpansion":return`\${${t.content}}`;case"ArithArrayElement":return t.stringKey!==void 0?`${t.array}[${t.stringKey}]`:t.index?`${t.array}[${xt(t.index)}]`:t.array;case"ArithDynamicBase":return`\${${t.baseExpr}}#${t.value}`;case"ArithDynamicNumber":return`\${${t.prefix}}${t.suffix}`;case"ArithConcat":return t.parts.map(xt).join("");case"ArithDoubleSubscript":return`${t.array}[${xt(t.index)}]`;case"ArithNumberSubscript":return`${t.number}[${t.errorToken}]`;case"ArithSyntaxError":return t.errorToken;case"ArithSingleQuote":return`'${t.content}'`;default:{let e=t;throw new Error(`Unsupported arithmetic expression type: ${e.type}`)}}}function Zi(t){switch(t.type){case"CondBinary":return`${ln(t.left)} ${t.operator} ${ln(t.right)}`;case"CondUnary":return`${t.operator} ${ln(t.operand)}`;case"CondNot":return`! ${Zi(t.operand)}`;case"CondAnd":return`${Zi(t.left)} && ${Zi(t.right)}`;case"CondOr":return`${Zi(t.left)} || ${Zi(t.right)}`;case"CondGroup":return`( ${Zi(t.expression)} )`;case"CondWord":return ln(t.word);default:{let e=t;throw new Error(`Unsupported conditional expression type: ${e.type}`)}}}var fa=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;executorInvokeTool;executorSetup;executorApproval;executorSDK;executorInitPromise;transformPlugins=[];state;constructor(e={}){let n=e.fs??new os(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
2103
+ ${t.terminator}`}function CV(t){return`(${Nr(t.body)})${Vr(t.redirections)}`}function kV(t){return`{ ${Nr(t.body)}; }${Vr(t.redirections)}`}function NV(t){return`((${xt(t.expression.expression)}))${Vr(t.redirections)}`}function TV(t){return`[[ ${Zi(t.expression)} ]]${Vr(t.redirections)}`}function OV(t){let e=yN(t.body);return`${t.name}() ${e}${Vr(t.redirections)}`}function xt(t){switch(t.type){case"ArithNumber":return String(t.value);case"ArithVariable":return t.hasDollarPrefix?`$${t.name}`:t.name;case"ArithSpecialVar":return`$${t.name}`;case"ArithBinary":return`${xt(t.left)} ${t.operator} ${xt(t.right)}`;case"ArithUnary":return t.prefix?`${t.operator}${xt(t.operand)}`:`${xt(t.operand)}${t.operator}`;case"ArithTernary":return`${xt(t.condition)} ? ${xt(t.consequent)} : ${xt(t.alternate)}`;case"ArithAssignment":return`${t.subscript?`${t.variable}[${xt(t.subscript)}]`:t.stringKey!==void 0?`${t.variable}[${t.stringKey}]`:t.variable} ${t.operator} ${xt(t.value)}`;case"ArithDynamicAssignment":return`${t.subscript?`${xt(t.target)}[${xt(t.subscript)}]`:xt(t.target)} ${t.operator} ${xt(t.value)}`;case"ArithDynamicElement":return`${xt(t.nameExpr)}[${xt(t.subscript)}]`;case"ArithGroup":return`(${xt(t.expression)})`;case"ArithNested":return`$((${xt(t.expression)}))`;case"ArithCommandSubst":return`$(${t.command})`;case"ArithBracedExpansion":return`\${${t.content}}`;case"ArithArrayElement":return t.stringKey!==void 0?`${t.array}[${t.stringKey}]`:t.index?`${t.array}[${xt(t.index)}]`:t.array;case"ArithDynamicBase":return`\${${t.baseExpr}}#${t.value}`;case"ArithDynamicNumber":return`\${${t.prefix}}${t.suffix}`;case"ArithConcat":return t.parts.map(xt).join("");case"ArithDoubleSubscript":return`${t.array}[${xt(t.index)}]`;case"ArithNumberSubscript":return`${t.number}[${t.errorToken}]`;case"ArithSyntaxError":return t.errorToken;case"ArithSingleQuote":return`'${t.content}'`;default:{let e=t;throw new Error(`Unsupported arithmetic expression type: ${e.type}`)}}}function Zi(t){switch(t.type){case"CondBinary":return`${ln(t.left)} ${t.operator} ${ln(t.right)}`;case"CondUnary":return`${t.operator} ${ln(t.operand)}`;case"CondNot":return`! ${Zi(t.operand)}`;case"CondAnd":return`${Zi(t.left)} && ${Zi(t.right)}`;case"CondOr":return`${Zi(t.left)} || ${Zi(t.right)}`;case"CondGroup":return`( ${Zi(t.expression)} )`;case"CondWord":return ln(t.word);default:{let e=t;throw new Error(`Unsupported conditional expression type: ${e.type}`)}}}var fa=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;traceFn;logger;defenseInDepthConfig;coverageWriter;jsBootstrapCode;executorInvokeTool;executorSetup;executorApproval;executorSDK;executorInitPromise;executorExecFn;transformPlugins=[];state;constructor(e={}){let n=e.fs??new os(e.files);this.fs=n,this.useDefaultLayout=!e.cwd&&!e.files;let r=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s=new Map([["HOME",this.useDefaultLayout?"/home/user":"/"],["PATH","/usr/bin:/bin"],["IFS",`
2101
2104
  `],["OSTYPE","linux-gnu"],["MACHTYPE","x86_64-pc-linux-gnu"],["HOSTTYPE","x86_64"],["HOSTNAME","localhost"],["PWD",r],["OLDPWD",r],["OPTIND","1"],...Object.entries(e.env??{})]);if(this.limits=lN({...e.executionLimits,...e.maxCallDepth!==void 0&&{maxCallDepth:e.maxCallDepth},...e.maxCommandCount!==void 0&&{maxCommandCount:e.maxCommandCount},...e.maxLoopIterations!==void 0&&{maxLoopIterations:e.maxLoopIterations}}),e.fetch?this.secureFetch=e.fetch:e.network&&(this.secureFetch=Ow(e.network)),this.sleepFn=e.sleep,this.traceFn=e.trace,this.logger=e.logger,this.defenseInDepthConfig=e.defenseInDepth??!0,this.coverageWriter=e.coverage,this.state={env:s,cwd:r,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",startTime:Date.now(),lastBackgroundPid:0,virtualPid:e.processInfo?.pid??1,virtualPpid:e.processInfo?.ppid??0,virtualUid:e.processInfo?.uid??1e3,virtualGid:e.processInfo?.gid??1e3,bashPid:e.processInfo?.pid??1,nextVirtualPid:(e.processInfo?.pid??1)+1,currentLine:1,options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1,posix:!1,allexport:!1,noclobber:!1,noglob:!1,noexec:!1,vi:!1,emacs:!1},shoptOptions:{extglob:!1,dotglob:!1,nullglob:!1,failglob:!1,globstar:!1,globskipdots:!0,nocaseglob:!1,nocasematch:!1,expand_aliases:!1,lastpipe:!1,xpg_echo:!1},inCondition:!1,loopDepth:0,exportedVars:new Set(["HOME","PATH","PWD","OLDPWD",...Object.keys(e.env||{})]),readonlyVars:new Set(["SHELLOPTS","BASHOPTS"]),hashTable:new Map},this.state.env.set("SHELLOPTS",Wy(this.state.options)),this.state.env.set("BASHOPTS",jy(this.state.shoptOptions)),A5(n,this.useDefaultLayout,{pid:this.state.virtualPid,ppid:this.state.virtualPpid,uid:this.state.virtualUid,gid:this.state.virtualGid}),r!=="/"&&n instanceof os)try{n.mkdirSync(r,{recursive:!0})}catch{}for(let i of h5(e.commands))this.registerCommand(i);if(e.fetch||e.network)for(let i of p5())this.registerCommand(i);if(e.python)for(let i of m5())this.registerCommand(i);if(e.javascript||e.executor){for(let o of y5())this.registerCommand(o);let i=typeof e.javascript=="object"?e.javascript:Object.create(null);i.bootstrap&&(this.jsBootstrapCode=i.bootstrap)}if(e.executor?.tools){let i=e.executor.tools;this.executorInvokeTool=async(o,a)=>{if(!Object.hasOwn(i,o))throw new Error(`Unknown tool: ${o}`);let l=i[o],c;try{c=a?JSON.parse(a):void 0}catch{c=void 0}let u=await l.execute(c);return u!==void 0?JSON.stringify(u):""}}if(e.executor?.setup&&(this.executorSetup=e.executor.setup),e.executor?.onToolApproval&&(this.executorApproval=e.executor.onToolApproval),e.customCommands)for(let i of e.customCommands)w5(i)?this.registerCommand(E5(i)):this.registerCommand({...i,trusted:i.trusted??!0})}registerCommand(e){this.commands.set(e.name,e);let n=this.fs;if(typeof n.writeFileSync=="function"){let r=`#!/bin/bash
2102
2105
  # Built-in command: ${e.name}
2103
- `;try{n.writeFileSync(`/bin/${e.name}`,r)}catch{}try{n.writeFileSync(`/usr/bin/${e.name}`,r)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e.stdout=SN(e.stdout),e.stderr=SN(e.stderr),e}async ensureExecutorReady(){if(!(!this.executorSetup||this.executorSDK)){if(this.executorInitPromise){await this.executorInitPromise;return}this.executorInitPromise=(async()=>{let e="./executor-init.js",{initExecutorSDK:n}=await import(e),r=this.executorSetup;if(!r)return;let{sdk:s,invokeTool:i}=await n(r,this.executorApproval,this.fs,()=>this.state.cwd,()=>this.state.env,()=>this.limits);this.executorSDK=s,this.executorInvokeTool=i})(),await this.executorInitPromise}}async exec(e,n){if(await this.ensureExecutorReady(),this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
2104
- `,exitCode:1,env:dr(this.state.env,n?.env)};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:dr(this.state.env,n?.env)};this.logger?.info("exec",{command:e});let r=n?.cwd??this.state.cwd,s,i=r;if(n?.cwd)if(n.env&&"PWD"in n.env)s=n.env.PWD;else if(n?.env&&!("PWD"in n.env))try{s=await this.fs.realpath(r),i=s}catch{s=r}else s=r;let o=n?.replaceEnv?new Map:new Map(this.state.env);if(n?.env)for(let[f,h]of Object.entries(n.env))o.set(f,h);s!==void 0&&o.set("PWD",s);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:n?.stdin,signal:n?.signal,extraArgs:n?.args},l=e;n?.rawScript||(l=xN(e));let c=this.defenseInDepthConfig?it.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let h=Dn(l,{maxHeredocSize:this.limits.maxHeredocSize}),p;if(this.transformPlugins.length>0){let w=Object.create(null);for(let b of this.transformPlugins){let E=b.transform({ast:h,metadata:w});h=E.ast,E.metadata&&(w=ys(w,E.metadata))}p=w}let d={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,executorInvokeTool:this.executorInvokeTool},y=await new Gl(d,a).executeScript(h);return p&&(y.metadata=p),this.logResult(y)};return u?await u.run(f):await f()}catch(f){if(f instanceof Ne)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:dr(this.state.env,n?.env)});if(f instanceof sr)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:dr(this.state.env,n?.env)});if(f instanceof ot)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:dr(this.state.env,n?.env)});if(f instanceof ro)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:dr(this.state.env,n?.env)});if(f instanceof te)return this.logResult({stdout:f.stdout,stderr:Ie(f.stderr),exitCode:te.EXIT_CODE,env:dr(this.state.env,n?.env)});if(f instanceof be)return this.logResult({stdout:"",stderr:`bash: security violation: ${Ie(f.message)}
2106
+ `;try{n.writeFileSync(`/bin/${e.name}`,r)}catch{}try{n.writeFileSync(`/usr/bin/${e.name}`,r)}catch{}}}logResult(e){return this.logger&&(e.stdout&&this.logger.debug("stdout",{output:e.stdout}),e.stderr&&this.logger.info("stderr",{output:e.stderr}),this.logger.info("exit",{exitCode:e.exitCode})),e.stdout=SN(e.stdout),e.stderr=SN(e.stderr),e}async ensureExecutorReady(){if(!(!this.executorSetup||this.executorSDK)){if(this.executorInitPromise){await this.executorInitPromise;return}this.executorInitPromise=(async()=>{let e="./executor-init.js",{initExecutorSDK:n}=await import(e),r=this.executorSetup;if(!r)return;let{sdk:s,executeViaSdk:i}=await n(r,this.executorApproval,this.fs,()=>this.state.cwd,()=>this.state.env,()=>this.limits);this.executorSDK=s,this.executorExecFn=i})(),await this.executorInitPromise}}async exec(e,n){if(await this.ensureExecutorReady(),this.state.callDepth===0&&(this.state.commandCount=0),this.state.commandCount++,this.state.commandCount>this.limits.maxCommandCount)return{stdout:"",stderr:`bash: maximum command count (${this.limits.maxCommandCount}) exceeded (possible infinite loop). Increase with executionLimits.maxCommandCount option.
2107
+ `,exitCode:1,env:dr(this.state.env,n?.env)};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:dr(this.state.env,n?.env)};this.logger?.info("exec",{command:e});let r=n?.cwd??this.state.cwd,s,i=r;if(n?.cwd)if(n.env&&"PWD"in n.env)s=n.env.PWD;else if(n?.env&&!("PWD"in n.env))try{s=await this.fs.realpath(r),i=s}catch{s=r}else s=r;let o=n?.replaceEnv?new Map:new Map(this.state.env);if(n?.env)for(let[f,h]of Object.entries(n.env))o.set(f,h);s!==void 0&&o.set("PWD",s);let a={...this.state,env:o,cwd:i,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options},hashTable:this.state.hashTable,groupStdin:n?.stdin,signal:n?.signal,extraArgs:n?.args},l=e;n?.rawScript||(l=xN(e));let c=this.defenseInDepthConfig?it.getInstance(this.defenseInDepthConfig):null,u=c?.activate();try{let f=async()=>{let h=Dn(l,{maxHeredocSize:this.limits.maxHeredocSize}),p;if(this.transformPlugins.length>0){let w=Object.create(null);for(let b of this.transformPlugins){let E=b.transform({ast:h,metadata:w});h=E.ast,E.metadata&&(w=ys(w,E.metadata))}p=w}let d={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn,trace:this.traceFn,coverage:this.coverageWriter,requireDefenseContext:c?.isEnabled()===!0,jsBootstrapCode:this.jsBootstrapCode,executorInvokeTool:this.executorInvokeTool,executorExecFn:this.executorExecFn},y=await new Gl(d,a).executeScript(h);return p&&(y.metadata=p),this.logResult(y)};return u?await u.run(f):await f()}catch(f){if(f instanceof Ne)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:dr(this.state.env,n?.env)});if(f instanceof sr)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:f.exitCode,env:dr(this.state.env,n?.env)});if(f instanceof ot)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:1,env:dr(this.state.env,n?.env)});if(f instanceof ro)return this.logResult({stdout:f.stdout,stderr:f.stderr,exitCode:124,env:dr(this.state.env,n?.env)});if(f instanceof te)return this.logResult({stdout:f.stdout,stderr:Ie(f.stderr),exitCode:te.EXIT_CODE,env:dr(this.state.env,n?.env)});if(f instanceof be)return this.logResult({stdout:"",stderr:`bash: security violation: ${Ie(f.message)}
2105
2108
  `,exitCode:1,env:dr(this.state.env,n?.env)});if(f.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${Ie(f.message)}
2106
2109
  `,exitCode:2,env:dr(this.state.env,n?.env)});if(f instanceof ti)return this.logResult({stdout:"",stderr:`bash: ${Ie(f.message)}
2107
2110
  `,exitCode:2,env:dr(this.state.env,n?.env)});if(f instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${Ie(f.message)}