@lmctl-ai/lmctl 0.2.183 → 0.2.185

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,7 @@ All notable public-preview changes for `@lmctl-ai/lmctl` are recorded here.
5
5
  ## Unreleased
6
6
 
7
7
  - Preserve runtime error exit 1 when implicit dry preflight blocks execution, replaying captured core stdout before the unchanged located error. Static/check errors stay 2; explicit dry and usage semantics are unchanged. require now stops with runtime exit 1, including opt-out runs; explicit exit codes and signals are retained.
8
+ - Extend recover resumepoint check warnings (Issue 031): warn when plain assignments to outer bindings (initialized or uninitialized) are skipped by earlier resumepoints and read later. Container mutations (push, pop, index assigns) stay documented-only without check warnings.
8
9
  - Fix prompt stall notice repetition (Issue 043): emit the stall notice once per stall episode when quiet beyond the threshold, re-arming only after assistant text or tool activity resumes. Suppresses repeating notices during prolonged quiet periods.
9
10
 
10
11
  - Fix dry preflight guard coverage after console output and lm_error; logs remain planned and recorded errors remain nonfatal. Bound implicit execution by 16,000 checkpoints and a 100 ms backstop (explicit timeout overrides these), reaching ordinary recursive guards without replaying expensive computation in full. Capped dry loops still cannot roll back effects before a later real failure.
package/build-info.json CHANGED
@@ -1 +1 @@
1
- {"sha": "404af37a775de13e0117f2cd695d43d29b4abc30", "dirty": false, "builtAt": "2026-10-09T22:31:16.000Z"}
1
+ {"sha": "e2fc9d81630fe2de8874db46f732133a32b9c2dc", "dirty": false, "builtAt": "2026-10-09T23:52:12.000Z"}
@@ -390,7 +390,7 @@ fn clamp(val, low, high) {
390
390
  }
391
391
  return val;
392
392
  }
393
- `,pu=null;ps=new WeakMap,wi=new WeakMap,nh=["get_property","has_property","get_properties","set_property"];ua=class{sources=new Map;loaded=!1;path="the registered property source";hint="Define it in the property source";tree={};known=[];constructor(e,n){this.tree.Directory=e,this.tree.NonInteractive=n.LMCTL_NON_INTERACTIVE==="1"}addSource(e,n,r){this.sources.has(e)||(this.sources.set(e,n),this.known.push(...r))}load(e){if(this.loaded)return;let n={};for(let r of this.sources.values()){let s;try{s=r()}catch(i){throw Error(`Property '${e}': ${i instanceof Error?i.message:String(i)}`)}this.path=s.path,this.hint=s.hint??"Define it in the property source";for(let[i,o]of Object.entries(s.properties)){if(i==="Directory"||i==="NonInteractive"||Object.hasOwn(n,i))throw Error(`Property '${i}' conflicts with a read-only invocation fact or another source in ${this.path}`);bt(n,i,structuredClone(o))}}for(let[r,s]of Object.entries(n))bt(this.tree,r,s);this.loaded=!0}find(e,n=!0){let r=Su(Tu(e),this.known);n&&!["Directory","NonInteractive"].includes(r.split(".")[0])&&this.load(r);let s=this.tree;for(let i of r.split(".")){if(!s||typeof s!="object"||!Object.hasOwn(s,i))return{found:!1,value:void 0,key:r};s=s[i]}return{found:!0,value:s,key:r}}missing(e){throw Error(`Property '${e}' is not defined in ${this.path}; ${this.hint}`)}get(e,...n){let r=this.find(e);return r.found?Gn(r.value,r.key):n.length?n[0]:this.missing(r.key)}has(e){return this.find(e).found}copy(e=""){if(!e)return this.load("<all>"),Gn(this.tree,"");let n=this.find(e);if(!n.found)return this.missing(n.key);if(!n.value||typeof n.value!="object"||Array.isArray(n.value)||n.value instanceof Date)throw Error(`Property '${n.key}' is not a table; get_properties requires a table`);return Gn(n.value,n.key)}set(e,n){let r=Su(Tu(e),this.known);if(["Directory","NonInteractive"].includes(r.split(".")[0]))throw Error(`Property '${r}' is read-only`);let s=Gn(n,r),i=this.find(r),o=this.tree,a=r.split(".");for(let u of a.slice(0,-1)){if(Object.hasOwn(o,u)||bt(o,u,{}),!o[u]||typeof o[u]!="object"||Array.isArray(o[u])||o[u]instanceof Date)throw Error(`Property '${u}' is a value, not a table`);o=o[u]}let l=i.found?Gn(i.value,r):null,c=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)&&!(u instanceof Date);if(i.found&&c(i.value)!==c(s))throw Error(`Property '${r}' cannot change between a table and a value`);return bt(o,a.at(-1),s),l}view(e=""){let n=i=>{let o=e?e+"."+i:i,a=this.find(o);if(!a.found)return this.missing(a.key);if(a.value&&typeof a.value=="object"&&!Array.isArray(a.value)&&!(a.value instanceof Date))return this.view(a.key);let l=Gn(a.value,a.key),c=u=>{if(u&&typeof u=="object"){for(let d of Object.values(u))c(d);Object.freeze(u)}return u};return c(l)},r=()=>{throw Error(`PROPS${e?"."+e:""} is read-only; use set_property`)},s=new Proxy({},{get:(i,o)=>typeof o=="symbol"||o==="then"?void 0:o==="toJSON"?()=>this.copy(e):n(o),ownKeys:()=>(e||this.load("<keys>"),Object.keys(e?this.find(e).value:this.tree)),getOwnPropertyDescriptor:(i,o)=>{if(typeof o!="string")return;!e&&!["Directory","NonInteractive"].includes(o)&&this.load("<keys>");let a=e?this.find(e).value:this.tree;return Object.hasOwn(a,o)?{enumerable:!0,configurable:!0}:void 0},set:r,deleteProperty:r,defineProperty:r,setPrototypeOf:r});return ps.set(s,n),wi.set(s,()=>this.copy(e)),s}};En=new uh;px=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;wn=class{variables=new Set;shadowedGlobals=new Set;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolvingScope(e){return this.variables.has(e)?this:this.parent?.resolvingScope(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}resolveInScope(e){return this.variables.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.resolveInScope(e):!1}},Iu=class{diagnostics=[];hostFunctions=new Map;knownHostReferences=new Map;options;functions=new Map;currentScope=new wn;loopDepth=0;inFunction=!1;hasConcurrency=!1;usedGlobals=new Set;usedProperties=!1;loadedPackages=new Set;functionPackages=new WeakMap;recoverLabels=new Set;hasRecover=!1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recoverContexts=[];constructor(e,n={}){this.options=n;for(let[r,s]of e.entries())this.hostFunctions.set(r,s),this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.usedGlobals.clear(),this.usedProperties=!1,this.loadedPackages=new Set,this.functionPackages=new WeakMap,this.recoverLabels.clear(),this.hasRecover=!1,this.recoverContexts=[],this.recoverScopedReads=new WeakMap,this.recoverScopedWrites=new WeakMap,this.loopDepth=0,this.inFunction=!1,this.currentScope=new wn,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,s]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);this.checkRecoverSiblings(e.statements),this.collectKnownHostReferences(e);for(let r of e.statements)r.kind==="FunctionDeclStmt"?this.functionPackages.set(r,new Set(this.loadedPackages)):this.checkStmt(r);let n=this.loadedPackages;for(let r of e.statements)r.kind==="FunctionDeclStmt"&&(this.loadedPackages=this.functionPackages.get(r),this.checkStmt(r));return this.loadedPackages=n,this.diagnostics}collectKnownHostReferences(e){this.knownHostReferences.clear();let n=new Map,r=new Map,s=(a,l)=>{n.set(a,(n.get(a)??0)+1),l&&r.set(a,l)},i=a=>{if(!(!a||typeof a!="object")){if(a.kind==="AssignExpr")s(a.target,a.value);else if(a.kind==="VarDeclStmt")s(a.name,a.initializer);else if(a.kind==="TupleAssignExpr")for(let l of a.targets)s(l);else if(a.kind==="TupleVarDeclStmt")for(let l of a.names)s(l);else if(a.kind==="ForInStmt")s(a.name);else if(a.kind==="FunctionDeclStmt")for(let l of a.params)s(l);for(let l of Object.values(a))Array.isArray(l)?l.forEach(i):l&&typeof l=="object"&&i(l)}};i(e);let o=(a,l=new Set)=>{if(l.has(a))return;if(l.add(a),!n.has(a))return this.hostFunctions.get(a);if(n.get(a)!==1)return;let c=r.get(a);for(;c?.kind==="GroupingExpr";)c=c.expression;return c?.kind==="IdentifierExpr"?o(c.name,l):void 0};for(let a of n.keys()){let l=o(a);l&&this.knownHostReferences.set(a,l)}}addError(e,n,r,s){this.diagnostics.push({message:e,line:n,column:r,severity:"error",file:s})}isPropsBinding(e){return e==="PROPS"||e.endsWith(".PROPS")}checkReservedBinding(e,n){e.some(r=>r==="RESUMEPOINT"||r.endsWith(".RESUMEPOINT"))&&this.addError("'RESUMEPOINT' is reserved; rename this binding (RESUMEPOINT is read-only)",n.line,n.column,n.file)}checkRecoverSiblings(e){let n=!1;for(let r of e)r.kind==="RecoverStmt"&&(n&&this.addError("Only one recover statement is allowed in this statement list",r.line,r.column,r.file),n=!0)}noteRecoverWrite(e,n,r){let s=this.currentScope.resolvingScope(e),i=this.recoverContexts.find(a=>a.scope===s);if(!i)return;if(r){let a=this.recoverScopedWrites.get(r);a||this.recoverScopedWrites.set(r,a=new Map),a.set(e,i.stmt)}if(!n){i.noInitializer.add(e);return}let o=i.assigned.get(e);o||i.assigned.set(e,o=new Set),o.add(i.point)}noteRecoverRead(e,n=e){let r=this.currentScope.resolvingScope(e.name),s=this.recoverContexts.find(a=>a.scope===r);s&&this.recoverScopedReads.set(n,s.stmt);let i=s?.assigned.get(e.name);if(!s||!i||i.has(s.point)||s.noInitializer.has(e.name)||s.warned.has(e.name))return;s.warned.add(e.name);let o=[...i].sort((a,l)=>a-l).map(a=>s.points[a]).join(", ");this.diagnostics.push({severity:"warning",message:`Variable '${e.name}' read in resumepoint '${s.points[s.point]}' is assigned only in earlier resumepoint(s): ${o}; resuming here may skip initialization`,line:e.line,column:e.column,file:e.file})}packageBindingCollision(e){return this.options.sourcePackages?.has(e.split(".").at(-1))??!1}collectFunction(e){for(let r of[e.name,...e.params])this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a function or parameter",e.line,e.column,e.file);if((this.isPropsBinding(e.name)||e.params.includes("PROPS"))&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name,...e.params],e),!e.isStdlib&&this.options.reservedFunctionPrefixes?.some(r=>e.name.startsWith(r))){this.addError(`Function name '${e.name}' uses a reserved built-in prefix`,e.line,e.column,e.file);return}if(this.functions.has(e.name)){let r=this.functions.get(e.name);if(r.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(r.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=r.file?`${r.file}:${r.line}`:`line ${r.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let n=new Set;for(let r of e.params)n.has(r)&&this.addError(`Duplicate parameter name '${r}' in function '${e.name}'`,e.line,e.column,e.file),n.add(r);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"PackageStmt":{(this.currentScope.parent||this.inFunction)&&this.addError("package must be the first file-level statement",e.line,e.column,e.file),(this.options.reservedFunctionPrefixes?.some(n=>e.name.startsWith(n))||this.options.builtinProviderNames?.includes(e.name))&&this.addError("Package name '"+e.name+"' uses a reserved built-in name/prefix",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),(e.name==="ARGV"||this.currentScope.resolve(e.name)||this.functions.has(e.name))&&this.addError("Package name collision: '"+e.name+"' is already a variable or function",e.line,e.column,e.file),this.loadedPackages.add(e.name);break}case"ImportStmt":{this.addError("Import must be at file top level; move the literal include before use",e.line,e.column,e.file);break}case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let n=this.currentScope,r=this.inFunction;this.inFunction=!0,this.currentScope=new wn(n,!0);for(let i of e.params)this.currentScope.define(i);let s=this.loopDepth;this.loopDepth=0,this.checkRecoverSiblings(e.body.statements);for(let i of e.body.statements)this.checkStmt(i);this.loopDepth=s,this.inFunction=r,this.currentScope=n;break}case"VarDeclStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a variable",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.currentScope.hasInCurrent(e.name)&&!(this.options.builtinGlobals?.includes(e.name)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(e.name))&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer,!0),this.currentScope.define(e.name),this.currentScope.shadowedGlobals.add(e.name),this.noteRecoverWrite(e.name,e.initializer!==void 0&&e.initializer!==null);break}case"TupleVarDeclStmt":{e.names.some(n=>this.isPropsBinding(n))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.names,e),this.checkExpr(e.initializer);for(let n of e.names)this.packageBindingCollision(n)&&this.addError("Package name collision: '"+n+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.hasInCurrent(n)&&!(this.options.builtinGlobals?.includes(n)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(n))&&this.addError(`Variable '${n}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(n),this.currentScope.shadowedGlobals.add(n),this.noteRecoverWrite(n,!0);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForInStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a loop binding",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.checkExpr(e.iterable);let n=this.currentScope;if(this.currentScope=new wn(n),this.currentScope.define(e.name),this.loopDepth++,e.body.kind==="BlockStmt")for(let r of e.body.statements)this.checkStmt(r);else this.checkStmt(e.body);this.loopDepth--,this.currentScope=n;break}case"ForStmt":{let n=s=>{if(!(!s||typeof s!="object")){if(s.kind==="CommandExpr"){let i=s;this.addError("command: not allowed in a loop header; assign argv before the loop",i.line,i.column,i.file);return}for(let i of Object.values(s))Array.isArray(i)?i.forEach(n):n(i)}};n(e.init);let r=this.currentScope;this.currentScope=new wn(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,e.update&&this.checkExpr(e.update),this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value,!0);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let n=this.currentScope;this.currentScope=new wn(n),this.checkRecoverSiblings(e.statements);for(let r of e.statements)this.checkStmt(r);this.currentScope=n;break}case"RecoverStmt":{this.hasRecover=!0,this.loopDepth>0&&this.addError("recover is not allowed lexically inside a loop body",e.line,e.column,e.file);let n=new Set;for(let i of e.points)n.has(i.name)&&this.addError(`Duplicate resumepoint '${i.name}'`,i.line,i.column,i.file),n.add(i.name),this.recoverLabels.add(i.name);let r=this.currentScope;this.currentScope=new wn(r);let s={stmt:e,scope:this.currentScope,points:e.points.map(i=>i.name),point:0,assigned:new Map,noInitializer:new Set,warned:new Set};this.recoverContexts.push(s),e.points.forEach((i,o)=>{s.point=o,this.checkRecoverSiblings(i.statements);for(let a of i.statements)this.checkStmt(a)}),this.recoverContexts.pop(),this.currentScope=r;break}case"SyncAssignStmt":{this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value),this.noteRecoverWrite(e.target,!0,e);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let n=e.call;n.args.length===0&&this.addError(`Synchronized call '${n.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let r=this.hostFunctions.get(n.callee);(!r||!r.isContainerMutation)&&this.addError(`Synchronized call '${n.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr,e.expr.kind==="AssignExpr"||e.expr.kind==="CommandExpr"&&e.expr.mode==="system");break}}}checkReadPath(e){let n=e.args[0];for(;n.kind==="GroupingExpr";)n=n.expression;if(n.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof n.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!W.statSync(n.value).isFile())throw new Error("path is not a regular file");W.accessSync(n.value,W.constants.R_OK)}catch(r){this.addError(`Cannot read file ${JSON.stringify(n.value)}: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,e.file)}}optionLiteral(e){if(e.kind==="GroupingExpr")return this.optionLiteral(e.expression);if(e.kind==="LiteralExpr")return{type:e.value===null?"null":typeof e.value,value:e.value};if(e.kind==="ArrayExpr"||e.kind==="TupleExpr")return{type:"list"};if(e.kind==="ObjectExpr")return{type:"map"};if(e.kind==="UnaryExpr"&&e.operator==="-"&&e.operand.kind==="LiteralExpr"&&typeof e.operand.value=="number")return{type:"number",value:-e.operand.value}}optionSuggestion(e,n){let r=a=>a.toLowerCase().replace(/[_-]/g,"");function s(a,l){let c=Array.from({length:l.length+1},(u,d)=>d);for(let u=1;u<=a.length;u++){let d=[u];for(let m=1;m<=l.length;m++)d[m]=Math.min(d[m-1]+1,c[m]+1,c[m-1]+(a[u-1]===l[m-1]?0:1));c=d}return c[l.length]}let i=n.filter(a=>a.name!=="*"),o=a=>{let l=r(e),c=r(a),u=0;for(;u<l.length&&u<c.length&&l[u]===c[u];)u++;return s(l,c)/Math.max(1,l.length,c.length)-u/Math.max(1,l.length)};return i.sort((a,l)=>o(a.name)-o(l.name)),i[0]?`; did you mean '${i[0].name}'?`:""}checkHostOptions(e,n){for(let[r,s]of n.entries()){if(!s.keys)continue;let i=e.args[r];for(;i?.kind==="GroupingExpr";)i=i.expression;if(i?.kind!=="ObjectExpr")continue;let o=new Set,a=s.open||s.keys.some(l=>l.name==="*"&&(l.type==="any"||l.type==="open"));for(let l of i.properties){let c=l.line??i.line,u=l.column??i.column,d=l.file??i.file;o.has(l.key)&&this.addError(`Duplicate option '${l.key}' in '${e.callee}' argument '${s.name}'`,c,u,d),o.add(l.key);let m=s.keys.find(h=>h.name===l.key);if(!m){a||this.addError(`Unknown option '${l.key}' in '${e.callee}' argument '${s.name}'${this.optionSuggestion(l.key,s.keys)}`,c,u,d);continue}let p=this.optionLiteral(l.value);if(!p||!m.type||m.type==="any"||m.type==="open")continue;let f=m.type.split("|").map(h=>h.trim().replace(/^array$/,"list").replace(/^object$/,"map")),g=["string","number","boolean","null","list","map"];f.every(h=>g.includes(h))&&!f.includes(p.type)&&this.addError(`Option '${l.key}' expects ${m.type}, got ${p.type}`,l.value.line,l.value.column,l.value.file),m.values&&p.type!=="list"&&p.type!=="map"&&!m.values.includes(p.value)&&this.addError(`Option '${l.key}' has a literal value outside its declared values`,l.value.line,l.value.column,l.value.file)}for(let l of s.keys)l.required&&l.name!=="*"&&!o.has(l.name)&&this.addError(`Missing required option '${l.name}' in '${e.callee}' argument '${s.name}'`,i.line,i.column,i.file)}}checkPackageMember(e,n){let r=e.split(".")[0],s=this.options.sourcePackages?.get(r);if(!this.loadedPackages.has(r)&&this.currentScope.resolve(r)){this.addError("Map member calls are not supported; use a named function",n.line,n.column,n.file);return}if(!this.loadedPackages.has(r)){this.addError("package "+r+" not loaded: import it before use; import order matters, leaf packages first",n.line,n.column,n.file);return}s?.members.includes(e)||this.addError("Unknown package member '"+e+"'"+this.optionSuggestion(e,(s?.members??[]).map(i=>({name:i}))),n.line,n.column,n.file)}checkPropertyPath(e,n){let r;try{r=Tu(e)}catch(c){this.addError(c.message,n.line,n.column,n.file);return}let s=this.options.propertyDeclarations;if(!s||(r=Su(r,s.known),s.known.includes(r)||s.closedTables?.includes(r)))return;let o=r.split(".")[0],a=this.optionSuggestion(r,s.known.map(c=>({name:c}))),l=(s.closedTables??[]).some(c=>/\d+$/.test(c)&&c.replace(/\d+$/,"")===o.replace(/\d+$/,""));(s.closedTables?.includes(o)||l)&&this.addError(`Unknown property '${e}'${a}`,n.line,n.column,n.file)}checkExpr(e,n=!1){switch(e.kind){case"CommandExpr":e.words.length||this.addError("command: a program is required",e.line,e.column,e.file),n||this.addError("command: allowed only as a simple initializer, return value, or standalone system statement",e.line,e.column,e.file);for(let r of e.words)for(let s of r.pieces)typeof s!="string"&&this.checkExpr(s.expression);e.mode==="system"&&this.checkExpr({kind:"CallExpr",callee:"system",args:[{kind:"ArrayExpr",elements:[],line:e.line,column:e.column}],line:e.line,column:e.column,file:e.file});break;case"InterpolatedStringExpr":for(let r of e.parts)typeof r!="string"&&this.checkExpr(r.expression);break;case"LiteralExpr":break;case"IdentifierExpr":{if(e.name.includes(".")){this.checkPackageMember(e.name,e),this.loadedPackages.has(e.name.split(".")[0])&&!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError("Package variable '"+e.name+"' used before declaration",e.line,e.column,e.file);break}(e.name==="PROPS"||e.name==="expand"||nh.includes(e.name))&&(this.usedProperties=!0);let r=this.currentScope.resolvingScope(e.name);r&&!r.parent&&this.options.globals?.includes(e.name)&&this.usedGlobals.add(e.name),this.noteRecoverRead(e),!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(Object.hasOwn(la,e.name)?_i(e.name,"Undeclared variable"):this.options.propertyDeclarations?.removedGlobals?.[e.name]?`'${e.name}' was replaced by ${this.options.propertyDeclarations.removedGlobals[e.name]}; declare a local variable if intended`:`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.packageBindingCollision(e.target)&&this.addError("Package name collision: '"+e.target+"' is a variable",e.line,e.column,e.file),e.target.includes(".")&&this.checkPackageMember(e.target,e),this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.checkExpr(e.value,n&&e.value.kind!=="AssignExpr"),this.currentScope.resolveInScope(e.target)||this.currentScope.define(e.target),this.currentScope.resolvingScope(e.target)?.shadowedGlobals.add(e.target),this.noteRecoverWrite(e.target,!0,e);break}case"TupleAssignExpr":{e.targets.some(r=>this.isPropsBinding(r))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.targets,e),this.checkExpr(e.value);for(let r of e.targets)this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.resolveInScope(r)||this.currentScope.define(r),this.currentScope.resolvingScope(r)?.shadowedGlobals.add(r),this.noteRecoverWrite(r,!0,e);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"ConditionalExpr":{this.checkExpr(e.condition),this.checkExpr(e.trueArm),this.checkExpr(e.falseArm);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{let r=da(e);r&&this.checkPropertyPath(r,e),this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{if(e.callee==="system"){let a=l=>l.kind==="LiteralExpr"?typeof l.value=="string":l.kind==="InterpolatedStringExpr"?!0:l.kind==="GroupingExpr"?a(l.expression):l.kind==="BinaryExpr"&&l.operator==="+"?a(l.left)||a(l.right):!1;e.args[0]&&a(e.args[0])&&this.addError("command: system(string) is not supported; write system PROGRAM ARGS or system([program, args...]); for an explicit shell invoke bash -c with a script field",e.line,e.column,e.file)}if(e.callee.includes(".")&&(Object.hasOwn(la,e.callee)&&!this.options.sourcePackages?.has(e.callee.split(".")[0])?this.addError(_i(e.callee),e.line,e.column,e.file):this.checkPackageMember(e.callee,e)),nh.includes(e.callee)&&(this.usedProperties=!0,e.args[0]?.kind==="LiteralExpr"&&typeof e.args[0].value=="string"&&e.args[0].value!==""&&this.checkPropertyPath(e.args[0].value,e.args[0])),e.callee==="expand"){let a=e.args[0];if(a?.kind==="LiteralExpr"&&typeof a.value=="string")try{let l=mi(a.value),c=e.args[1];for(;c?.kind==="GroupingExpr";)c=c.expression;let u=e.args[1]?c?.kind==="ObjectExpr"?new Set(c.properties.map(m=>m.key)):void 0:new Set,d=new Set;for(let m of l)typeof m!="string"&&(m.kind==="property"?(this.usedProperties=!0,this.checkPropertyPath(m.key,a)):m.kind==="variable"&&u&&!u.has(m.name)&&d.add(m.name));if(d.size){let m=[...d].map(p=>`${p} (not defined)`).join("; ");this.addError(`expand: missing references: ${m}; assign a temporary variable first and pass it in vars.`,a.line,a.column,a.file)}}catch(l){this.addError(l.message,a.line,a.column,a.file)}else this.usedProperties=!0}let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(_i(e.callee),e.line,e.column,e.file);let s=this.hostFunctions.get(e.callee)??this.knownHostReferences.get(e.callee),i=a=>{if(a.kind==="AssignExpr")return a.target==="dryrun"||i(a.value);if(a.kind==="TupleAssignExpr")return a.targets.includes("dryrun")||i(a.value);for(let l of Object.values(a))if(l&&typeof l=="object"&&(Array.isArray(l)?l.some(c=>c&&typeof c=="object"&&i(c)):i(l)))return!0;return!1};(s||!r||r.isHost)&&e.args.some(i)&&this.addError(`dryrun is supplied by the language; omit it from '${e.callee}' arguments`,e.line,e.column,e.file);let o=s?.signature?.publicArity??s?.arity;!r&&typeof o=="number"&&e.args.length!==o&&this.addError(`Function '${e.callee}' expects ${o} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),typeof o=="object"&&(e.args.length<o.min||e.args.length>(o.max??1/0))&&this.addError(`Function '${e.callee}' expects ${o.min}..${o.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),(this.hostFunctions.has(e.callee)||s?.signature?.dryrunIndex!==void 0)&&(s?.signature?.publicParams?this.checkHostOptions(e,s.signature.publicParams):s?.params&&this.checkHostOptions(e,s.params)),this.options.checkFiles&&s?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let a of e.args)this.checkExpr(a);r||this.noteRecoverRead({...e,kind:"IdentifierExpr",name:e.callee},e);break}}}};Jn=class{value;constructor(e){this.value=e}},Ot=class{},Lt=class{},Vn=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Qe=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,n){this.values.set(e,n)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}hasInScope(e){return this.values.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.hasInScope(e):!1}writeTarget(e){return this.values.has(e)?this:!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)?this.parent.writeTarget(e):this}set(e,n){if(this.values.has(e)){this.values.set(e,n);return}if(!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)){this.parent.set(e,n);return}this.values.set(e,n)}},ma=class{holderTaskId;depth=0;waiters=[];acquire(e=0,n=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((r,s)=>{let i;n>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${n}ms (possible deadlock)`)))},n));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,r()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,n=0,r=1e4){await this.acquire(n,r);try{return await e()}finally{this.release()}}},Au=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let n=this.bindingLocks.get(e);return n||(n=new ma,this.bindingLocks.set(e,n)),n}getObjectLock(e){let n=this.objectLocks.get(e);return n||(n=new ma,this.objectLocks.set(e,n)),n}},he=Object.freeze({readonly:!0}),bx=t=>{for(let e of Object.values(t))Object.freeze(e);return Object.freeze(t)},vx=bx({warning:{readonly:!0,control:"warning",dummyType:"string"},which:he,get_property:he,has_property:he,get_properties:he,expand:he,set_property:{dummyType:"null"},read:he,read_file:he,read_lines:{readonly:!0,dummyType:"array"},read_json:{readonly:!0,dummyType:"map"},read_csv:{readonly:!0,dummyType:"array"},file_exists:{readonly:!0,dummyType:"boolean"},glob:{readonly:!0,dummyType:"array"},list_dir:{readonly:!0,dummyType:"array"},csv_parse:{readonly:!0,dummyType:"array"},csv_stringify:{readonly:!0,dummyType:"string"},basename:{readonly:!0,dummyType:"string"},dirname:{readonly:!0,dummyType:"string"},path_join:{readonly:!0,dummyType:"string"},abs_path:{readonly:!0,dummyType:"string"},write:{dummyType:"boolean"},write_file:{dummyType:"boolean"},write_file_exclusive:{dummyType:"boolean"},write_lines:{dummyType:"boolean"},write_json:{dummyType:"boolean"},write_csv:{dummyType:"boolean"},append_file:{dummyType:"boolean"},delete_file:{dummyType:"boolean"},remove_file:{dummyType:"boolean"},mkdir:{dummyType:"boolean"},rmdir:{dummyType:"boolean"},copy_file:{dummyType:"boolean"},move_file:{dummyType:"boolean"},temp_file:{dummyType:"null"},env:{readonly:!0,frozen:"env"},getenv:{readonly:!0,frozen:"env"},set_env:{dummyType:"boolean"},list:{readonly:!0,dummyType:"array"},array:{readonly:!0,dummyType:"array"},push:he,pop:he,shift:he,unshift:he,insert:he,remove_at:he,concat:{readonly:!0,dummyType:"array"},reverse:{readonly:!0,dummyType:"array"},sort:{readonly:!0,dummyType:"array"},unique:{readonly:!0,dummyType:"array"},flatten:{readonly:!0,dummyType:"array"},first:he,last:he,sum:{readonly:!0,dummyType:"number"},avg:{readonly:!0,dummyType:"number"},map:{readonly:!0,dummyType:"map"},hash:{readonly:!0,dummyType:"map"},from_entries:{readonly:!0,dummyType:"map"},clear:he,size:{readonly:!0,dummyType:"number"},len:{readonly:!0,dummyType:"number"},keys:{readonly:!0,dummyType:"array"},values:{readonly:!0,dummyType:"array"},entries:{readonly:!0,dummyType:"array"},items:{readonly:!0,dummyType:"array"},has_key:{readonly:!0,dummyType:"boolean"},get:he,getstr:{readonly:!0,dummyType:"string"},getnum:{readonly:!0,dummyType:"number"},getbool:{readonly:!0,dummyType:"boolean"},getlist:{readonly:!0,dummyType:"array"},set:he,delete_key:he,merge:{readonly:!0,dummyType:"map"},clone:he,pluck:{readonly:!0,dummyType:"array"},filter_by:{readonly:!0,dummyType:"array"},find_by:he,json_parse:he,json_parse_safe:he,json_stringify:{readonly:!0,dummyType:"string"},regex_test:{readonly:!0,dummyType:"boolean"},regex_match:{readonly:!0,dummyType:"array"},regex_find_all:{readonly:!0,dummyType:"array"},regex_replace:{readonly:!0,dummyType:"string"},split_regex:{readonly:!0,dummyType:"array"},split:{readonly:!0,dummyType:"array"},lines:{readonly:!0,dummyType:"array"},last_line_as_status:he,words:{readonly:!0,dummyType:"array"},join:{readonly:!0,dummyType:"string"},trim:{readonly:!0,dummyType:"string"},strip:{readonly:!0,dummyType:"string"},trim_start:{readonly:!0,dummyType:"string"},lstrip:{readonly:!0,dummyType:"string"},trim_end:{readonly:!0,dummyType:"string"},rstrip:{readonly:!0,dummyType:"string"},to_upper:{readonly:!0,dummyType:"string"},upper:{readonly:!0,dummyType:"string"},to_lower:{readonly:!0,dummyType:"string"},lower:{readonly:!0,dummyType:"string"},upper_first:{readonly:!0,dummyType:"string"},title_case:{readonly:!0,dummyType:"string"},contains:{readonly:!0,dummyType:"boolean"},includes:{readonly:!0,dummyType:"boolean"},starts_with:{readonly:!0,dummyType:"boolean"},startswith:{readonly:!0,dummyType:"boolean"},ends_with:{readonly:!0,dummyType:"boolean"},endswith:{readonly:!0,dummyType:"boolean"},index_of:{readonly:!0,dummyType:"number"},last_index_of:{readonly:!0,dummyType:"number"},count_matches:{readonly:!0,dummyType:"number"},substr:{readonly:!0,dummyType:"string"},substring:{readonly:!0,dummyType:"string"},slice:he,char_at:{readonly:!0,dummyType:"string"},char_code:{readonly:!0,dummyType:"number"},from_char_code:{readonly:!0,dummyType:"string"},replace:{readonly:!0,dummyType:"string"},replace_all:{readonly:!0,dummyType:"string"},repeat:{readonly:!0,dummyType:"string"},pad_start:{readonly:!0,dummyType:"string"},pad_end:{readonly:!0,dummyType:"string"},reverse_str:{readonly:!0,dummyType:"string"},is_empty:{readonly:!0,dummyType:"boolean"},is_digit:{readonly:!0,dummyType:"boolean"},is_alpha:{readonly:!0,dummyType:"boolean"},is_alnum:{readonly:!0,dummyType:"boolean"},is_array:{readonly:!0,dummyType:"boolean"},is_string:{readonly:!0,dummyType:"boolean"},is_number:{readonly:!0,dummyType:"boolean"},is_map:{readonly:!0,dummyType:"boolean"},is_function:{readonly:!0,dummyType:"boolean"},format:{readonly:!0,dummyType:"string"},sprintf:{readonly:!0,dummyType:"string"},cmd_render:{readonly:!0,dummyType:"string"},range:{readonly:!0,dummyType:"array"},abs:{readonly:!0,dummyType:"number"},min:{readonly:!0,dummyType:"number"},max:{readonly:!0,dummyType:"number"},floor:{readonly:!0,dummyType:"number"},ceil:{readonly:!0,dummyType:"number"},round:{readonly:!0,dummyType:"number"},sqrt:{readonly:!0,dummyType:"number"},pow:{readonly:!0,dummyType:"number"},sha256:{readonly:!0,dummyType:"string"},now:{readonly:!0,dummyType:"number",frozen:"now"},timestamp:{readonly:!0,dummyType:"number",frozen:"timestamp"},date:{readonly:!0,dummyType:"string",frozen:"date"},strftime:{readonly:!0,dummyType:"string"},coalesce:he,if_null:he,if_else:he,str:{readonly:!0,dummyType:"string"},num:{readonly:!0,dummyType:"number"},type:{readonly:!0,dummyType:"string"},require:{readonly:!0,control:"require"},assert:{readonly:!0,control:"assert"},error:{readonly:!0,control:"error",dummyType:"string"},exit:{readonly:!0,control:"exit",dummyType:"null"},print:{control:"print",dummyType:"string",taints:!1},println:{control:"println",dummyType:"string",taints:!1},printf:{control:"printf",dummyType:"string",taints:!1},system:{dummyType:"SystemResult",process:!0},run_script:{dummyType:"map"},http_get:{dummyType:"string"},random:{dummyType:"number"},sleep_ms:{dummyType:"null"},prompt_human:{dummyType:"null"},prompt_human_config:{dummyType:"map"}}),Ex={stdout:"",stderr:"",code:0,signal:null,timed_out:!1,duration_ms:0,pid:null,dry:!0};De=Symbol("core dry policy"),Cu=Symbol("dry invocation"),Nu=Symbol("implicit preflight work limit"),Ou=Symbol("implicit preflight stdout");Pt=class extends Error{isControlFlow=!0;exitCode=0};pa=class{entries=[];lastSite={line:1,column:1};failure;recordedDiagnostics=[];recordError(e,n=this.lastSite){this.sealed||(this.check(),this.recordedDiagnostics.push({...n,severity:"error",message:e}))}scriptExit;sealed=!1;loopLimit;platform;timeout;deadline=1/0;wallClock;environment;planBytes=0;work=0;workLimit;replay;cleanups=new Map;own(e){this.cleanups.has(e)||this.cleanups.set(e,{started:!1})}dispose(e){this.own(e);let n=this.cleanups.get(e);return n.started||(n.started=!0,n.value=e.dispose(),Ge(n.value)&&Promise.resolve(n.value).catch(()=>{})),n.value}controller=new AbortController;truncation;onStart;start(){Number.isFinite(this.deadline)||(this.deadline=performance.now()+this.timeout,this.onStart?.())}constructor(e={}){if(this.replay=e[Ou],this.workLimit=e[Nu]??1/0,this.platform=e.hostContext?.platform??e.platform??process.platform,this.wallClock=e.dryrunClockMs??Date.now(),!Number.isFinite(this.wallClock))throw Error("Dry wall clock must be finite");this.environment=Object.freeze(Object.assign(Object.create(null),e.hostContext?.env??process.env)),this.loopLimit=e.dryLoopLimit??10,this.timeout=e.dryrunTimeoutMs??5e3;for(let n of[this.loopLimit,this.timeout])if(!Number.isSafeInteger(n)||n<=0)throw Error("Dry bounds must be positive safe integers")}hasTaintedValues=!1;get tainted(){return this.hasTaintedValues}at(e){this.lastSite={file:e.file,line:e.line,column:e.column},++this.work>this.workLimit&&this.truncate("work budget exceeded"),this.check()}check(){if(this.truncation)throw new Pt(this.truncation);if(this.sealed)throw new Pt("Dry pass finished");performance.now()>=this.deadline&&this.truncate("time budget exceeded")}truncate(e){this.truncation??="dry run truncated: "+e,this.sealed=!0,this.controller.abort();for(let n of[...this.cleanups.keys()].reverse())try{this.dispose(n)}catch{}throw new Pt(this.truncation)}async wait(e){let n=Promise.resolve(e);n.catch(()=>{}),this.check();let r;try{let s=await Promise.race([n,new Promise((i,o)=>{let a=()=>{r&&(clearTimeout(r),r=void 0);let l=this.deadline-performance.now();if(l<=0)try{this.truncate("time budget exceeded")}catch(c){o(c)}else r=setTimeout(a,Math.min(2147483647,Math.max(1,l)))};this.onStart=a,a()})]);return this.check(),s}finally{r&&clearTimeout(r),this.onStart=void 0}}loop(e,n){return this.at(n),e<this.loopLimit?!1:(this.append({seq:this.entries.length+1,kind:"loop",file:n.file??"<main>",line:n.line,column:n.column,iterations:e,limit:this.loopLimit,message:"loop truncated at "+this.loopLimit,simulated:!1}),this.hasTaintedValues=!0,!0)}propertyView;propertyLoads=[];prepareProperties(e){if(e&&["Directory","NonInteractive"].includes(e.split(".")[0]))return;let n=this.propertyLoads.map(r=>r());return n.some(Ge)?Promise.all(n):void 0}fail(e,n=this.lastSite){throw this.check(),this.failure??={site:{...n},message:e,untrusted:this.tainted},new Pt(e)}finishExit(e,n=this.lastSite){this.scriptExit??={site:{...n},code:e}}captureFailure(e,n=this.lastSite){if(this.truncation)return;if(performance.now()>=this.deadline){try{this.truncate("time budget exceeded")}catch{}return}let r=wx(e);if(r!==void 0){this.finishExit(r,n);return}if(e?.isControlFlow&&e?.resourceFailure===void 0)return;let s=e instanceof M?{file:e.file,line:e.line,column:e.column}:n;this.failure??={site:{...s},message:e instanceof Error?e.message:String(e),untrusted:this.tainted}}captureOutput(e,n){if(!this.replay)return;this.check();let r=Buffer.byteLength(n)+Buffer.byteLength(this.lastSite.file??"")+32;this.planBytes+r>1024*1024-4096&&this.truncate("console output size exceeded"),this.planBytes+=r,this.replay.push({name:e,text:n,site:{...this.lastSite}})}record(e,n,r,s,i,o=!0){this.sealed||(this.check(),this.append({seq:this.entries.length+1,kind:s,file:r.file??"<main>",line:r.line,column:r.column,function:e,arguments:n,simulated:!0,...i?{argv:[...i],renderedArgv:Bu(i,this.platform==="win32"?"windows":"posix"),dialect:this.platform==="win32"?"windows":"posix"}:{}}),this.hasTaintedValues||=o)}snapshot(e){let n=new Map,r=new Map,s=0,i=a=>{s+=a,this.check(),s+this.planBytes>1024*1024-4096&&this.truncate("plan size exceeded")},o=(a,l,c)=>{if(i(8),c>256&&this.truncate("plan size traversal depth exceeded"),a===null||typeof a=="boolean")return a;if(typeof a=="string")return i(Buffer.byteLength(a)),a;if(typeof a=="number")return Number.isFinite(a)?a:{$type:String(a)};if(typeof a=="bigint"){let h=String(a);return i(h.length),{$type:"bigint",value:h}}if(typeof a=="symbol"){r.has(a)||r.set(a,r.size+1);let h=String(a);return i(Buffer.byteLength(h)),{$type:"symbol",id:r.get(a),value:h}}if(typeof a>"u"||typeof a=="function")return{$type:typeof a};if(Ae(a))return{$type:"resource"};if(ps.has(a)&&(a=Or(a)),ve.isProxy(a))return{$type:"proxy"};let u=Wu(a);if(u)return{$type:ve.isMap(a)?"Map":ve.isSet(a)?"Set":ve.isDate(a)?"Date":ve.isRegExp(a)?"RegExp":ve.isNativeError(a)?"Error":ve.isArrayBufferView(a)?"TypedArray":u};if(n.has(a))return{$ref:n.get(a)};n.set(a,l),Array.isArray(a)&&i(a.length);let d=Array.isArray(a)?new Array(a.length):{},m=Reflect.ownKeys(a);i(m.length*8);let p=Array.isArray(a),f=m.some(h=>typeof h=="symbol"||h==="$ref"||h==="$type"||p&&h!=="length"&&!(/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)<a.length)),g=[];for(let h of m.filter(y=>y!=="length"||!Array.isArray(a)).sort((y,v)=>String(y)<String(v)?-1:String(y)>String(v)?1:0)){let y=typeof h=="symbol"?"symbol:"+g.length:h;i(Buffer.byteLength(y));let v=Object.getOwnPropertyDescriptor(a,h),_="value"in v?o(v.value,f?l+"/properties/"+g.length+"/1":l+"/"+y.replaceAll("~","~0").replaceAll("/","~1"),c+1):{$type:"accessor"};f?g.push([typeof h=="symbol"?o(h,l+"/properties/"+g.length+"/0",c+1):h,_]):Object.defineProperty(d,y,{value:_,enumerable:!0,writable:!0,configurable:!0})}return f?{$type:p?"array":"object",...p?{length:a.length}:{},properties:g}:d};return o(e,"$",0)}append(e){let n=Buffer.byteLength(JSON.stringify(e))+1;this.planBytes+n>1024*1024-4096&&this.truncate("plan size exceeded"),this.planBytes+=n,this.entries.push(e)}capture(e){if(this.truncation)return;let n=e.diagnostics;if(!this.failure){let r=n.find(s=>s.severity==="error");r&&(this.failure={site:r,message:r.message,untrusted:this.tainted})}!this.failure&&!this.scriptExit&&e.exitCode&&e.exitCode!==0&&(this.failure={site:this.lastSite,message:"exit("+e.exitCode+")",untrusted:this.tainted})}report(e){let n=[...e.diagnostics];this.capture(e);let r=[...this.recordedDiagnostics];for(let l of e.errors??[])r.some(c=>c.message===l)||r.push({...this.lastSite,severity:"error",message:l});if(this.sealed=!0,this.truncation&&!this.failure)return hu({version:1,status:"truncated",entries:this.entries,stop:{file:this.lastSite.file??"<main>",line:this.lastSite.line,column:this.lastSite.column,reason:this.truncation},diagnostics:[...r,...n.filter(l=>l.severity!=="error"),{...this.lastSite,severity:"warning",message:this.truncation}],exitCode:0});if(!this.failure){let l=this.scriptExit?{file:this.scriptExit.site.file??"<main>",line:this.scriptExit.site.line,column:this.scriptExit.site.column,reason:"script exit with code "+this.scriptExit.code}:null;return hu({version:1,status:this.scriptExit?"complete":this.entries.some(c=>c.kind==="loop")?"loop-limited":"complete",entries:this.entries,stop:l,diagnostics:[...r,...n],exitCode:0})}let{site:s,message:i,untrusted:o}=this.failure,a=o?"needs a real result: "+i:i;return hu({version:1,status:o?"needs-real-result":"failed",entries:this.entries,stop:{file:s.file??"<main>",line:s.line,column:s.column,reason:a},diagnostics:[...r,...!o&&n.some(l=>l.severity==="error")?n:[...n.filter(l=>l.severity!=="error"),{...s,severity:o?"warning":"error",message:a}]],exitCode:o?0:2})}};Tx=new Set(["read","read_file","read_lines","read_json","read_csv"]);Mu=new WeakMap,bi=class{constructor(e){Mu.set(this,e)}},kx=5e3;Rx=1,Du=class{id;constructor(e){Rh++,Ih.add(this),Object.defineProperty(this,"id",{value:e,enumerable:!0}),Object.freeze(this)}},Rh=0;Ih=new WeakSet;ch=new WeakMap,xh=1e7;vi=class{failure;records=[];label;parent;base;constructor(e,n,r){this.label=e,this.parent=n,this.base=r}isAncestorOf(e){for(let n=e.parent;n;n=n.parent)if(n===this)return!0;return!1}},Ah=new uh;Fu=class{token=`run-${process.pid}-${Rx++}`;root=new vi("root");ordinal=0;terminating=!1;records=new WeakMap;ordered=[];rawRecords=new WeakMap;scopes=new WeakMap;onFailure;defaultDeadlineMs;failures=[];constructor(e,n={}){this.onFailure=e;let r=n.defaultDeadlineMs;this.defaultDeadlineMs=typeof r=="number"&&Number.isFinite(r)&&r>0?r:kx}scopeFor(e){for(let n=e;n;n=n.isFunctionScope?void 0:n.parent){let r=this.scopes.get(n);if(r)return r}return this.root}enterScope(e,n,r){let s=new vi(r,n);return this.scopes.set(e,s),s}temporaryScope(e,n,r){return new vi(n,e,r)}register(e,n,r,s){let i=String(e.id),o={handle:new Du(i),raw:e,kind:typeof e.kind=="string"&&e.kind?e.kind:n,id:i,site:r,ordinal:++this.ordinal,owner:s,state:"open",adoptable:!0,unresolved:!1};return ch.set(o.handle,`${o.kind} ${o.id}`),this.records.set(o.handle,o),this.rawRecords.set(e,o),this.ordered.push(o),s.records.push(o),o.handle}terminate(){if(!this.terminating){this.terminating=!0;for(let e of[...this.ordered].sort((n,r)=>r.ordinal-n.ordinal))if(!(e.state==="closed"||e.state==="close_failed"))try{typeof e.raw.finalizeSync=="function"&&(e.raw.finalizeSync(),e.state="closed")}catch(n){this.fail(e,"critical finalization failed: "+String(n))}}}authorizeRaw(e,n,r,s=!1){let i=e!==null&&typeof e=="object"?this.rawRecords.get(e):void 0;if(!i)throw Error("Resource "+String(e?.kind??"batch")+" "+String(e?.id)+" belongs to another run: "+r);if(i.owner!==n&&!i.owner.isAncestorOf(n))throw Error("Resource "+i.kind+" "+i.id+" is not authorized in this borrower scope: "+r);if(!s&&i.state!=="open")throw Error("Resource "+i.kind+" "+i.id+" is closed: "+r);return i}lookup(e){return this.records.get(e)}describe(e){let n=this.records.get(e);return n?`${n.kind} ${n.id}`:`${ch.get(e)??e.id} (from another run)`}borrow(e){if(Ae(e)){let n=this.records.get(e);n&&(n.adoptable=!1)}}bind(e,n,r){if(!Ae(e))return;let s=this.records.get(e);if(!s)return`resource ${e.id} belongs to another run`;let i=this.scopeFor(n);if(s.adoptable){s.adoptable=!1,i!==s.owner&&(s.owner.records.splice(s.owner.records.indexOf(s),1),i.records.push(s),s.owner=i);return}if(i!==s.owner&&i.isAncestorOf(s.owner))return`resource ${s.kind} ${s.id} cannot escape its owner into the longer-lived binding '${r}'`}close(e,n){if(e.closing)return e.closing;e.state="closing";let r=e.raw,s=r.closeDeadlineMs,i=typeof s=="number"&&Number.isFinite(s)&&s>0?s:this.defaultDeadlineMs,o=performance.now(),a;e.closing=new Promise(c=>{a=c});let l=`close did not finish within its ${i} ms deadline`;return(async()=>{let c,u=!1;try{let d=r.close({reason:this.terminating?"cancelled":e.owner.failure!==void 0?"error":"done",error:e.owner.failure instanceof Error?e.owner.failure.message:e.owner.failure==null?void 0:String(e.owner.failure),explicit:n});if(Ge(d)){let m=Promise.resolve(d).then(()=>!0);m.catch(()=>{});let p=i-(performance.now()-o);if(!(p>0&&await Promise.race([m,new Promise(g=>{c=setTimeout(()=>g(!1),p)})]))){this.critical(e),u=this.fail(e,l);return}}if(performance.now()-o>i){this.critical(e),u=this.fail(e,l);return}if(this.terminating&&e.state==="close_failed")return;e.state="closed",u=!0}catch(d){u=this.fail(e,d instanceof Error?d.message:String(d))}finally{c&&clearTimeout(c),a(u)}})(),e.closing}critical(e){try{typeof e.raw.finalizeSync=="function"&&e.raw.finalizeSync()}catch(n){this.report(`resource ${e.kind} ${e.id} (${e.site}): critical finalization failed: ${n instanceof Error?n.message:String(n)}`)}}fail(e,n){return e.state="close_failed",e.unresolved=!0,this.report(`resource close failed: ${e.kind} ${e.id} (${e.site}): ${n}`),!1}report(e){this.failures.push(e);try{this.onFailure(e)}catch{}}async drain(e){for(let n of[...e.records].sort((r,s)=>s.ordinal-r.ordinal))if(!(n.state==="closed"||n.state==="close_failed"))try{await this.close(n)}catch{}}snapshot(){return this.ordered.map(e=>({id:e.id,kind:e.kind,owner:e.owner.label,site:e.site,state:e.state,unresolved:e.unresolved,ordinal:e.ordinal}))}},fa=class{nativeImports;processContext;warningDiagnostics=[];dry;platform;abortSignal;resources;resourcesEnabled;temporaryScopes=new Map;globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new Au;isAsync;nextTaskId=1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recovery;initialGlobals;callDepth=0;noPreflight;asyncCallDepth=new Map;recordedErrors;promptHumanConfig;childEngineFactory;compileOptions;constructor(e,n=m=>console.log(m),r=!1,s,i,o,a=gi(void 0),l=process.platform,c,u=!1,d){this.nativeImports=d,this.dry=c,this.noPreflight=u,this.platform=l,this.recovery=a,this.recordedErrors=a.errors,this.stdout=n,this.stderr=i,this.isAsync=r,this.initialGlobals=s,this.globalEnv=new Qe,this.hostFunctions=new Map(e),this.promptHumanConfig=o??{mode:"interactive"},this.resourcesEnabled=[...this.hostFunctions.values()].some(I=>I.returnsResource===!0),this.resources=new Fu(I=>{ta(this.recovery,I);try{this.stderr?.(`error: ${I}`)}catch{}});let m=e.get("print");(!m||m.isDefault)&&this.hostFunctions.set("print",{...m,fn:(...I)=>{let A=m?.signature?.dryrunIndex===0?I.shift()===!0:!1,N=I.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return A||this.stdout(N),N},arity:m?.signature?.nativeArity??m?.arity??{min:0},description:m?.description??"Prints formatted values to output log",isDefault:!0});let p=e.get("println");(!p||p.isDefault)&&this.hostFunctions.set("println",{...p,fn:(...I)=>{let A=p?.signature?.dryrunIndex===0?I.shift()===!0:!1,N=I.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return A||this.stdout(N),N},arity:p?.signature?.nativeArity??p?.arity??{min:0},description:p?.description??"Prints line to output log",isDefault:!0});let f=e.get("printf");(!f||f.isDefault)&&this.hostFunctions.set("printf",{...f,fn:(...I)=>{let A=f?.signature?.dryrunIndex===0?I.shift()===!0:!1,[N,...O]=I,E=na(N,O,"printf");return A||this.stdout(E),E},arity:f?.signature?.nativeArity??f?.arity??{min:2},description:f?.description??"Formats and prints %s, %d, %f and %% using sprintf rules",isDefault:!0});let g=e.get("require");(!g||g.isDefault)&&this.hostFunctions.set("require",{...g,fn:(I,A)=>Uu(I,A,N=>{ta(this.recovery,N),this.stderr?.(`error: ${N}`)}),arity:2,isDefault:!0});let h=e.get("error");(!h||h.isDefault)&&this.hostFunctions.set("error",{...h,fn:(...I)=>{let A=I.map(N=>typeof N=="object"?JSON.stringify(N):String(N)).join(" ");return ta(this.recovery,A),this.stderr?this.stderr(`error: ${A}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${A}
393
+ `,pu=null;ps=new WeakMap,wi=new WeakMap,nh=["get_property","has_property","get_properties","set_property"];ua=class{sources=new Map;loaded=!1;path="the registered property source";hint="Define it in the property source";tree={};known=[];constructor(e,n){this.tree.Directory=e,this.tree.NonInteractive=n.LMCTL_NON_INTERACTIVE==="1"}addSource(e,n,r){this.sources.has(e)||(this.sources.set(e,n),this.known.push(...r))}load(e){if(this.loaded)return;let n={};for(let r of this.sources.values()){let s;try{s=r()}catch(i){throw Error(`Property '${e}': ${i instanceof Error?i.message:String(i)}`)}this.path=s.path,this.hint=s.hint??"Define it in the property source";for(let[i,o]of Object.entries(s.properties)){if(i==="Directory"||i==="NonInteractive"||Object.hasOwn(n,i))throw Error(`Property '${i}' conflicts with a read-only invocation fact or another source in ${this.path}`);bt(n,i,structuredClone(o))}}for(let[r,s]of Object.entries(n))bt(this.tree,r,s);this.loaded=!0}find(e,n=!0){let r=Su(Tu(e),this.known);n&&!["Directory","NonInteractive"].includes(r.split(".")[0])&&this.load(r);let s=this.tree;for(let i of r.split(".")){if(!s||typeof s!="object"||!Object.hasOwn(s,i))return{found:!1,value:void 0,key:r};s=s[i]}return{found:!0,value:s,key:r}}missing(e){throw Error(`Property '${e}' is not defined in ${this.path}; ${this.hint}`)}get(e,...n){let r=this.find(e);return r.found?Gn(r.value,r.key):n.length?n[0]:this.missing(r.key)}has(e){return this.find(e).found}copy(e=""){if(!e)return this.load("<all>"),Gn(this.tree,"");let n=this.find(e);if(!n.found)return this.missing(n.key);if(!n.value||typeof n.value!="object"||Array.isArray(n.value)||n.value instanceof Date)throw Error(`Property '${n.key}' is not a table; get_properties requires a table`);return Gn(n.value,n.key)}set(e,n){let r=Su(Tu(e),this.known);if(["Directory","NonInteractive"].includes(r.split(".")[0]))throw Error(`Property '${r}' is read-only`);let s=Gn(n,r),i=this.find(r),o=this.tree,a=r.split(".");for(let u of a.slice(0,-1)){if(Object.hasOwn(o,u)||bt(o,u,{}),!o[u]||typeof o[u]!="object"||Array.isArray(o[u])||o[u]instanceof Date)throw Error(`Property '${u}' is a value, not a table`);o=o[u]}let l=i.found?Gn(i.value,r):null,c=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)&&!(u instanceof Date);if(i.found&&c(i.value)!==c(s))throw Error(`Property '${r}' cannot change between a table and a value`);return bt(o,a.at(-1),s),l}view(e=""){let n=i=>{let o=e?e+"."+i:i,a=this.find(o);if(!a.found)return this.missing(a.key);if(a.value&&typeof a.value=="object"&&!Array.isArray(a.value)&&!(a.value instanceof Date))return this.view(a.key);let l=Gn(a.value,a.key),c=u=>{if(u&&typeof u=="object"){for(let d of Object.values(u))c(d);Object.freeze(u)}return u};return c(l)},r=()=>{throw Error(`PROPS${e?"."+e:""} is read-only; use set_property`)},s=new Proxy({},{get:(i,o)=>typeof o=="symbol"||o==="then"?void 0:o==="toJSON"?()=>this.copy(e):n(o),ownKeys:()=>(e||this.load("<keys>"),Object.keys(e?this.find(e).value:this.tree)),getOwnPropertyDescriptor:(i,o)=>{if(typeof o!="string")return;!e&&!["Directory","NonInteractive"].includes(o)&&this.load("<keys>");let a=e?this.find(e).value:this.tree;return Object.hasOwn(a,o)?{enumerable:!0,configurable:!0}:void 0},set:r,deleteProperty:r,defineProperty:r,setPrototypeOf:r});return ps.set(s,n),wi.set(s,()=>this.copy(e)),s}};En=new uh;px=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;wn=class{variables=new Set;shadowedGlobals=new Set;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolvingScope(e){return this.variables.has(e)?this:this.parent?.resolvingScope(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}resolveInScope(e){return this.variables.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.resolveInScope(e):!1}},Iu=class{diagnostics=[];hostFunctions=new Map;knownHostReferences=new Map;options;functions=new Map;currentScope=new wn;loopDepth=0;inFunction=!1;hasConcurrency=!1;usedGlobals=new Set;usedProperties=!1;loadedPackages=new Set;functionPackages=new WeakMap;recoverLabels=new Set;hasRecover=!1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recoverContexts=[];constructor(e,n={}){this.options=n;for(let[r,s]of e.entries())this.hostFunctions.set(r,s),this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.usedGlobals.clear(),this.usedProperties=!1,this.loadedPackages=new Set,this.functionPackages=new WeakMap,this.recoverLabels.clear(),this.hasRecover=!1,this.recoverContexts=[],this.recoverScopedReads=new WeakMap,this.recoverScopedWrites=new WeakMap,this.loopDepth=0,this.inFunction=!1,this.currentScope=new wn,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,s]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);this.checkRecoverSiblings(e.statements),this.collectKnownHostReferences(e);for(let r of e.statements)r.kind==="FunctionDeclStmt"?this.functionPackages.set(r,new Set(this.loadedPackages)):this.checkStmt(r);let n=this.loadedPackages;for(let r of e.statements)r.kind==="FunctionDeclStmt"&&(this.loadedPackages=this.functionPackages.get(r),this.checkStmt(r));return this.loadedPackages=n,this.diagnostics}collectKnownHostReferences(e){this.knownHostReferences.clear();let n=new Map,r=new Map,s=(a,l)=>{n.set(a,(n.get(a)??0)+1),l&&r.set(a,l)},i=a=>{if(!(!a||typeof a!="object")){if(a.kind==="AssignExpr")s(a.target,a.value);else if(a.kind==="VarDeclStmt")s(a.name,a.initializer);else if(a.kind==="TupleAssignExpr")for(let l of a.targets)s(l);else if(a.kind==="TupleVarDeclStmt")for(let l of a.names)s(l);else if(a.kind==="ForInStmt")s(a.name);else if(a.kind==="FunctionDeclStmt")for(let l of a.params)s(l);for(let l of Object.values(a))Array.isArray(l)?l.forEach(i):l&&typeof l=="object"&&i(l)}};i(e);let o=(a,l=new Set)=>{if(l.has(a))return;if(l.add(a),!n.has(a))return this.hostFunctions.get(a);if(n.get(a)!==1)return;let c=r.get(a);for(;c?.kind==="GroupingExpr";)c=c.expression;return c?.kind==="IdentifierExpr"?o(c.name,l):void 0};for(let a of n.keys()){let l=o(a);l&&this.knownHostReferences.set(a,l)}}addError(e,n,r,s){this.diagnostics.push({message:e,line:n,column:r,severity:"error",file:s})}isPropsBinding(e){return e==="PROPS"||e.endsWith(".PROPS")}checkReservedBinding(e,n){e.some(r=>r==="RESUMEPOINT"||r.endsWith(".RESUMEPOINT"))&&this.addError("'RESUMEPOINT' is reserved; rename this binding (RESUMEPOINT is read-only)",n.line,n.column,n.file)}checkRecoverSiblings(e){let n=!1;for(let r of e)r.kind==="RecoverStmt"&&(n&&this.addError("Only one recover statement is allowed in this statement list",r.line,r.column,r.file),n=!0)}isScopeOrAncestor(e,n){if(!n)return!1;let r=e;for(;r;){if(r===n)return!0;r=r.parent}return!1}noteRecoverWrite(e,n,r){let s=this.currentScope.resolvingScope(e),i=this.recoverContexts.find(o=>o.scope===s);if(i){if(r){let o=this.recoverScopedWrites.get(r);o||this.recoverScopedWrites.set(r,o=new Map),o.set(e,i.stmt)}if(!n){i.noInitializer.add(e);return}}if(n)for(let o of this.recoverContexts){if(!this.isScopeOrAncestor(o.scope,s))continue;let a=o.assigned.get(e);a||o.assigned.set(e,a=new Set),a.add(o.point)}}noteRecoverRead(e,n=e){let r=this.currentScope.resolvingScope(e.name),s=this.recoverContexts.find(i=>i.scope===r);s&&this.recoverScopedReads.set(n,s.stmt);for(let i of this.recoverContexts){if(!this.isScopeOrAncestor(i.scope,r))continue;let o=i.assigned.get(e.name);if(!o||o.has(i.point)||i.noInitializer.has(e.name)||i.warned.has(e.name))continue;i.warned.add(e.name);let a=[...o].sort((l,c)=>l-c).map(l=>i.points[l]).join(", ");this.diagnostics.push({severity:"warning",message:`Variable '${e.name}' read in resumepoint '${i.points[i.point]}' is assigned only in earlier resumepoint(s): ${a}; resuming here may skip initialization`,line:e.line,column:e.column,file:e.file})}}packageBindingCollision(e){return this.options.sourcePackages?.has(e.split(".").at(-1))??!1}collectFunction(e){for(let r of[e.name,...e.params])this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a function or parameter",e.line,e.column,e.file);if((this.isPropsBinding(e.name)||e.params.includes("PROPS"))&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name,...e.params],e),!e.isStdlib&&this.options.reservedFunctionPrefixes?.some(r=>e.name.startsWith(r))){this.addError(`Function name '${e.name}' uses a reserved built-in prefix`,e.line,e.column,e.file);return}if(this.functions.has(e.name)){let r=this.functions.get(e.name);if(r.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(r.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=r.file?`${r.file}:${r.line}`:`line ${r.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let n=new Set;for(let r of e.params)n.has(r)&&this.addError(`Duplicate parameter name '${r}' in function '${e.name}'`,e.line,e.column,e.file),n.add(r);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"PackageStmt":{(this.currentScope.parent||this.inFunction)&&this.addError("package must be the first file-level statement",e.line,e.column,e.file),(this.options.reservedFunctionPrefixes?.some(n=>e.name.startsWith(n))||this.options.builtinProviderNames?.includes(e.name))&&this.addError("Package name '"+e.name+"' uses a reserved built-in name/prefix",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),(e.name==="ARGV"||this.currentScope.resolve(e.name)||this.functions.has(e.name))&&this.addError("Package name collision: '"+e.name+"' is already a variable or function",e.line,e.column,e.file),this.loadedPackages.add(e.name);break}case"ImportStmt":{this.addError("Import must be at file top level; move the literal include before use",e.line,e.column,e.file);break}case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let n=this.currentScope,r=this.inFunction;this.inFunction=!0,this.currentScope=new wn(n,!0);for(let i of e.params)this.currentScope.define(i);let s=this.loopDepth;this.loopDepth=0,this.checkRecoverSiblings(e.body.statements);for(let i of e.body.statements)this.checkStmt(i);this.loopDepth=s,this.inFunction=r,this.currentScope=n;break}case"VarDeclStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a variable",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.currentScope.hasInCurrent(e.name)&&!(this.options.builtinGlobals?.includes(e.name)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(e.name))&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer,!0),this.currentScope.define(e.name),this.currentScope.shadowedGlobals.add(e.name),this.noteRecoverWrite(e.name,e.initializer!==void 0&&e.initializer!==null);break}case"TupleVarDeclStmt":{e.names.some(n=>this.isPropsBinding(n))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.names,e),this.checkExpr(e.initializer);for(let n of e.names)this.packageBindingCollision(n)&&this.addError("Package name collision: '"+n+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.hasInCurrent(n)&&!(this.options.builtinGlobals?.includes(n)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(n))&&this.addError(`Variable '${n}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(n),this.currentScope.shadowedGlobals.add(n),this.noteRecoverWrite(n,!0);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForInStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a loop binding",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.checkExpr(e.iterable);let n=this.currentScope;if(this.currentScope=new wn(n),this.currentScope.define(e.name),this.loopDepth++,e.body.kind==="BlockStmt")for(let r of e.body.statements)this.checkStmt(r);else this.checkStmt(e.body);this.loopDepth--,this.currentScope=n;break}case"ForStmt":{let n=s=>{if(!(!s||typeof s!="object")){if(s.kind==="CommandExpr"){let i=s;this.addError("command: not allowed in a loop header; assign argv before the loop",i.line,i.column,i.file);return}for(let i of Object.values(s))Array.isArray(i)?i.forEach(n):n(i)}};n(e.init);let r=this.currentScope;this.currentScope=new wn(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,e.update&&this.checkExpr(e.update),this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value,!0);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let n=this.currentScope;this.currentScope=new wn(n),this.checkRecoverSiblings(e.statements);for(let r of e.statements)this.checkStmt(r);this.currentScope=n;break}case"RecoverStmt":{this.hasRecover=!0,this.loopDepth>0&&this.addError("recover is not allowed lexically inside a loop body",e.line,e.column,e.file);let n=new Set;for(let i of e.points)n.has(i.name)&&this.addError(`Duplicate resumepoint '${i.name}'`,i.line,i.column,i.file),n.add(i.name),this.recoverLabels.add(i.name);let r=this.currentScope;this.currentScope=new wn(r);let s={stmt:e,scope:this.currentScope,points:e.points.map(i=>i.name),point:0,assigned:new Map,noInitializer:new Set,warned:new Set};this.recoverContexts.push(s),e.points.forEach((i,o)=>{s.point=o,this.checkRecoverSiblings(i.statements);for(let a of i.statements)this.checkStmt(a)}),this.recoverContexts.pop(),this.currentScope=r;break}case"SyncAssignStmt":{this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value),this.noteRecoverWrite(e.target,!0,e);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let n=e.call;n.args.length===0&&this.addError(`Synchronized call '${n.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let r=this.hostFunctions.get(n.callee);(!r||!r.isContainerMutation)&&this.addError(`Synchronized call '${n.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr,e.expr.kind==="AssignExpr"||e.expr.kind==="CommandExpr"&&e.expr.mode==="system");break}}}checkReadPath(e){let n=e.args[0];for(;n.kind==="GroupingExpr";)n=n.expression;if(n.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof n.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!W.statSync(n.value).isFile())throw new Error("path is not a regular file");W.accessSync(n.value,W.constants.R_OK)}catch(r){this.addError(`Cannot read file ${JSON.stringify(n.value)}: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,e.file)}}optionLiteral(e){if(e.kind==="GroupingExpr")return this.optionLiteral(e.expression);if(e.kind==="LiteralExpr")return{type:e.value===null?"null":typeof e.value,value:e.value};if(e.kind==="ArrayExpr"||e.kind==="TupleExpr")return{type:"list"};if(e.kind==="ObjectExpr")return{type:"map"};if(e.kind==="UnaryExpr"&&e.operator==="-"&&e.operand.kind==="LiteralExpr"&&typeof e.operand.value=="number")return{type:"number",value:-e.operand.value}}optionSuggestion(e,n){let r=a=>a.toLowerCase().replace(/[_-]/g,"");function s(a,l){let c=Array.from({length:l.length+1},(u,d)=>d);for(let u=1;u<=a.length;u++){let d=[u];for(let m=1;m<=l.length;m++)d[m]=Math.min(d[m-1]+1,c[m]+1,c[m-1]+(a[u-1]===l[m-1]?0:1));c=d}return c[l.length]}let i=n.filter(a=>a.name!=="*"),o=a=>{let l=r(e),c=r(a),u=0;for(;u<l.length&&u<c.length&&l[u]===c[u];)u++;return s(l,c)/Math.max(1,l.length,c.length)-u/Math.max(1,l.length)};return i.sort((a,l)=>o(a.name)-o(l.name)),i[0]?`; did you mean '${i[0].name}'?`:""}checkHostOptions(e,n){for(let[r,s]of n.entries()){if(!s.keys)continue;let i=e.args[r];for(;i?.kind==="GroupingExpr";)i=i.expression;if(i?.kind!=="ObjectExpr")continue;let o=new Set,a=s.open||s.keys.some(l=>l.name==="*"&&(l.type==="any"||l.type==="open"));for(let l of i.properties){let c=l.line??i.line,u=l.column??i.column,d=l.file??i.file;o.has(l.key)&&this.addError(`Duplicate option '${l.key}' in '${e.callee}' argument '${s.name}'`,c,u,d),o.add(l.key);let m=s.keys.find(h=>h.name===l.key);if(!m){a||this.addError(`Unknown option '${l.key}' in '${e.callee}' argument '${s.name}'${this.optionSuggestion(l.key,s.keys)}`,c,u,d);continue}let p=this.optionLiteral(l.value);if(!p||!m.type||m.type==="any"||m.type==="open")continue;let f=m.type.split("|").map(h=>h.trim().replace(/^array$/,"list").replace(/^object$/,"map")),g=["string","number","boolean","null","list","map"];f.every(h=>g.includes(h))&&!f.includes(p.type)&&this.addError(`Option '${l.key}' expects ${m.type}, got ${p.type}`,l.value.line,l.value.column,l.value.file),m.values&&p.type!=="list"&&p.type!=="map"&&!m.values.includes(p.value)&&this.addError(`Option '${l.key}' has a literal value outside its declared values`,l.value.line,l.value.column,l.value.file)}for(let l of s.keys)l.required&&l.name!=="*"&&!o.has(l.name)&&this.addError(`Missing required option '${l.name}' in '${e.callee}' argument '${s.name}'`,i.line,i.column,i.file)}}checkPackageMember(e,n){let r=e.split(".")[0],s=this.options.sourcePackages?.get(r);if(!this.loadedPackages.has(r)&&this.currentScope.resolve(r)){this.addError("Map member calls are not supported; use a named function",n.line,n.column,n.file);return}if(!this.loadedPackages.has(r)){this.addError("package "+r+" not loaded: import it before use; import order matters, leaf packages first",n.line,n.column,n.file);return}s?.members.includes(e)||this.addError("Unknown package member '"+e+"'"+this.optionSuggestion(e,(s?.members??[]).map(i=>({name:i}))),n.line,n.column,n.file)}checkPropertyPath(e,n){let r;try{r=Tu(e)}catch(c){this.addError(c.message,n.line,n.column,n.file);return}let s=this.options.propertyDeclarations;if(!s||(r=Su(r,s.known),s.known.includes(r)||s.closedTables?.includes(r)))return;let o=r.split(".")[0],a=this.optionSuggestion(r,s.known.map(c=>({name:c}))),l=(s.closedTables??[]).some(c=>/\d+$/.test(c)&&c.replace(/\d+$/,"")===o.replace(/\d+$/,""));(s.closedTables?.includes(o)||l)&&this.addError(`Unknown property '${e}'${a}`,n.line,n.column,n.file)}checkExpr(e,n=!1){switch(e.kind){case"CommandExpr":e.words.length||this.addError("command: a program is required",e.line,e.column,e.file),n||this.addError("command: allowed only as a simple initializer, return value, or standalone system statement",e.line,e.column,e.file);for(let r of e.words)for(let s of r.pieces)typeof s!="string"&&this.checkExpr(s.expression);e.mode==="system"&&this.checkExpr({kind:"CallExpr",callee:"system",args:[{kind:"ArrayExpr",elements:[],line:e.line,column:e.column}],line:e.line,column:e.column,file:e.file});break;case"InterpolatedStringExpr":for(let r of e.parts)typeof r!="string"&&this.checkExpr(r.expression);break;case"LiteralExpr":break;case"IdentifierExpr":{if(e.name.includes(".")){this.checkPackageMember(e.name,e),this.loadedPackages.has(e.name.split(".")[0])&&!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError("Package variable '"+e.name+"' used before declaration",e.line,e.column,e.file);break}(e.name==="PROPS"||e.name==="expand"||nh.includes(e.name))&&(this.usedProperties=!0);let r=this.currentScope.resolvingScope(e.name);r&&!r.parent&&this.options.globals?.includes(e.name)&&this.usedGlobals.add(e.name),this.noteRecoverRead(e),!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(Object.hasOwn(la,e.name)?_i(e.name,"Undeclared variable"):this.options.propertyDeclarations?.removedGlobals?.[e.name]?`'${e.name}' was replaced by ${this.options.propertyDeclarations.removedGlobals[e.name]}; declare a local variable if intended`:`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.packageBindingCollision(e.target)&&this.addError("Package name collision: '"+e.target+"' is a variable",e.line,e.column,e.file),e.target.includes(".")&&this.checkPackageMember(e.target,e),this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.checkExpr(e.value,n&&e.value.kind!=="AssignExpr"),this.currentScope.resolveInScope(e.target)||this.currentScope.define(e.target),this.currentScope.resolvingScope(e.target)?.shadowedGlobals.add(e.target),this.noteRecoverWrite(e.target,!0,e);break}case"TupleAssignExpr":{e.targets.some(r=>this.isPropsBinding(r))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.targets,e),this.checkExpr(e.value);for(let r of e.targets)this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.resolveInScope(r)||this.currentScope.define(r),this.currentScope.resolvingScope(r)?.shadowedGlobals.add(r),this.noteRecoverWrite(r,!0,e);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"ConditionalExpr":{this.checkExpr(e.condition),this.checkExpr(e.trueArm),this.checkExpr(e.falseArm);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{let r=da(e);r&&this.checkPropertyPath(r,e),this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{if(e.callee==="system"){let a=l=>l.kind==="LiteralExpr"?typeof l.value=="string":l.kind==="InterpolatedStringExpr"?!0:l.kind==="GroupingExpr"?a(l.expression):l.kind==="BinaryExpr"&&l.operator==="+"?a(l.left)||a(l.right):!1;e.args[0]&&a(e.args[0])&&this.addError("command: system(string) is not supported; write system PROGRAM ARGS or system([program, args...]); for an explicit shell invoke bash -c with a script field",e.line,e.column,e.file)}if(e.callee.includes(".")&&(Object.hasOwn(la,e.callee)&&!this.options.sourcePackages?.has(e.callee.split(".")[0])?this.addError(_i(e.callee),e.line,e.column,e.file):this.checkPackageMember(e.callee,e)),nh.includes(e.callee)&&(this.usedProperties=!0,e.args[0]?.kind==="LiteralExpr"&&typeof e.args[0].value=="string"&&e.args[0].value!==""&&this.checkPropertyPath(e.args[0].value,e.args[0])),e.callee==="expand"){let a=e.args[0];if(a?.kind==="LiteralExpr"&&typeof a.value=="string")try{let l=mi(a.value),c=e.args[1];for(;c?.kind==="GroupingExpr";)c=c.expression;let u=e.args[1]?c?.kind==="ObjectExpr"?new Set(c.properties.map(m=>m.key)):void 0:new Set,d=new Set;for(let m of l)typeof m!="string"&&(m.kind==="property"?(this.usedProperties=!0,this.checkPropertyPath(m.key,a)):m.kind==="variable"&&u&&!u.has(m.name)&&d.add(m.name));if(d.size){let m=[...d].map(p=>`${p} (not defined)`).join("; ");this.addError(`expand: missing references: ${m}; assign a temporary variable first and pass it in vars.`,a.line,a.column,a.file)}}catch(l){this.addError(l.message,a.line,a.column,a.file)}else this.usedProperties=!0}let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(_i(e.callee),e.line,e.column,e.file);let s=this.hostFunctions.get(e.callee)??this.knownHostReferences.get(e.callee),i=a=>{if(a.kind==="AssignExpr")return a.target==="dryrun"||i(a.value);if(a.kind==="TupleAssignExpr")return a.targets.includes("dryrun")||i(a.value);for(let l of Object.values(a))if(l&&typeof l=="object"&&(Array.isArray(l)?l.some(c=>c&&typeof c=="object"&&i(c)):i(l)))return!0;return!1};(s||!r||r.isHost)&&e.args.some(i)&&this.addError(`dryrun is supplied by the language; omit it from '${e.callee}' arguments`,e.line,e.column,e.file);let o=s?.signature?.publicArity??s?.arity;!r&&typeof o=="number"&&e.args.length!==o&&this.addError(`Function '${e.callee}' expects ${o} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),typeof o=="object"&&(e.args.length<o.min||e.args.length>(o.max??1/0))&&this.addError(`Function '${e.callee}' expects ${o.min}..${o.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),(this.hostFunctions.has(e.callee)||s?.signature?.dryrunIndex!==void 0)&&(s?.signature?.publicParams?this.checkHostOptions(e,s.signature.publicParams):s?.params&&this.checkHostOptions(e,s.params)),this.options.checkFiles&&s?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let a of e.args)this.checkExpr(a);r||this.noteRecoverRead({...e,kind:"IdentifierExpr",name:e.callee},e);break}}}};Jn=class{value;constructor(e){this.value=e}},Ot=class{},Lt=class{},Vn=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Qe=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,n){this.values.set(e,n)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}hasInScope(e){return this.values.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.hasInScope(e):!1}writeTarget(e){return this.values.has(e)?this:!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)?this.parent.writeTarget(e):this}set(e,n){if(this.values.has(e)){this.values.set(e,n);return}if(!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)){this.parent.set(e,n);return}this.values.set(e,n)}},ma=class{holderTaskId;depth=0;waiters=[];acquire(e=0,n=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((r,s)=>{let i;n>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${n}ms (possible deadlock)`)))},n));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,r()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,n=0,r=1e4){await this.acquire(n,r);try{return await e()}finally{this.release()}}},Au=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let n=this.bindingLocks.get(e);return n||(n=new ma,this.bindingLocks.set(e,n)),n}getObjectLock(e){let n=this.objectLocks.get(e);return n||(n=new ma,this.objectLocks.set(e,n)),n}},he=Object.freeze({readonly:!0}),bx=t=>{for(let e of Object.values(t))Object.freeze(e);return Object.freeze(t)},vx=bx({warning:{readonly:!0,control:"warning",dummyType:"string"},which:he,get_property:he,has_property:he,get_properties:he,expand:he,set_property:{dummyType:"null"},read:he,read_file:he,read_lines:{readonly:!0,dummyType:"array"},read_json:{readonly:!0,dummyType:"map"},read_csv:{readonly:!0,dummyType:"array"},file_exists:{readonly:!0,dummyType:"boolean"},glob:{readonly:!0,dummyType:"array"},list_dir:{readonly:!0,dummyType:"array"},csv_parse:{readonly:!0,dummyType:"array"},csv_stringify:{readonly:!0,dummyType:"string"},basename:{readonly:!0,dummyType:"string"},dirname:{readonly:!0,dummyType:"string"},path_join:{readonly:!0,dummyType:"string"},abs_path:{readonly:!0,dummyType:"string"},write:{dummyType:"boolean"},write_file:{dummyType:"boolean"},write_file_exclusive:{dummyType:"boolean"},write_lines:{dummyType:"boolean"},write_json:{dummyType:"boolean"},write_csv:{dummyType:"boolean"},append_file:{dummyType:"boolean"},delete_file:{dummyType:"boolean"},remove_file:{dummyType:"boolean"},mkdir:{dummyType:"boolean"},rmdir:{dummyType:"boolean"},copy_file:{dummyType:"boolean"},move_file:{dummyType:"boolean"},temp_file:{dummyType:"null"},env:{readonly:!0,frozen:"env"},getenv:{readonly:!0,frozen:"env"},set_env:{dummyType:"boolean"},list:{readonly:!0,dummyType:"array"},array:{readonly:!0,dummyType:"array"},push:he,pop:he,shift:he,unshift:he,insert:he,remove_at:he,concat:{readonly:!0,dummyType:"array"},reverse:{readonly:!0,dummyType:"array"},sort:{readonly:!0,dummyType:"array"},unique:{readonly:!0,dummyType:"array"},flatten:{readonly:!0,dummyType:"array"},first:he,last:he,sum:{readonly:!0,dummyType:"number"},avg:{readonly:!0,dummyType:"number"},map:{readonly:!0,dummyType:"map"},hash:{readonly:!0,dummyType:"map"},from_entries:{readonly:!0,dummyType:"map"},clear:he,size:{readonly:!0,dummyType:"number"},len:{readonly:!0,dummyType:"number"},keys:{readonly:!0,dummyType:"array"},values:{readonly:!0,dummyType:"array"},entries:{readonly:!0,dummyType:"array"},items:{readonly:!0,dummyType:"array"},has_key:{readonly:!0,dummyType:"boolean"},get:he,getstr:{readonly:!0,dummyType:"string"},getnum:{readonly:!0,dummyType:"number"},getbool:{readonly:!0,dummyType:"boolean"},getlist:{readonly:!0,dummyType:"array"},set:he,delete_key:he,merge:{readonly:!0,dummyType:"map"},clone:he,pluck:{readonly:!0,dummyType:"array"},filter_by:{readonly:!0,dummyType:"array"},find_by:he,json_parse:he,json_parse_safe:he,json_stringify:{readonly:!0,dummyType:"string"},regex_test:{readonly:!0,dummyType:"boolean"},regex_match:{readonly:!0,dummyType:"array"},regex_find_all:{readonly:!0,dummyType:"array"},regex_replace:{readonly:!0,dummyType:"string"},split_regex:{readonly:!0,dummyType:"array"},split:{readonly:!0,dummyType:"array"},lines:{readonly:!0,dummyType:"array"},last_line_as_status:he,words:{readonly:!0,dummyType:"array"},join:{readonly:!0,dummyType:"string"},trim:{readonly:!0,dummyType:"string"},strip:{readonly:!0,dummyType:"string"},trim_start:{readonly:!0,dummyType:"string"},lstrip:{readonly:!0,dummyType:"string"},trim_end:{readonly:!0,dummyType:"string"},rstrip:{readonly:!0,dummyType:"string"},to_upper:{readonly:!0,dummyType:"string"},upper:{readonly:!0,dummyType:"string"},to_lower:{readonly:!0,dummyType:"string"},lower:{readonly:!0,dummyType:"string"},upper_first:{readonly:!0,dummyType:"string"},title_case:{readonly:!0,dummyType:"string"},contains:{readonly:!0,dummyType:"boolean"},includes:{readonly:!0,dummyType:"boolean"},starts_with:{readonly:!0,dummyType:"boolean"},startswith:{readonly:!0,dummyType:"boolean"},ends_with:{readonly:!0,dummyType:"boolean"},endswith:{readonly:!0,dummyType:"boolean"},index_of:{readonly:!0,dummyType:"number"},last_index_of:{readonly:!0,dummyType:"number"},count_matches:{readonly:!0,dummyType:"number"},substr:{readonly:!0,dummyType:"string"},substring:{readonly:!0,dummyType:"string"},slice:he,char_at:{readonly:!0,dummyType:"string"},char_code:{readonly:!0,dummyType:"number"},from_char_code:{readonly:!0,dummyType:"string"},replace:{readonly:!0,dummyType:"string"},replace_all:{readonly:!0,dummyType:"string"},repeat:{readonly:!0,dummyType:"string"},pad_start:{readonly:!0,dummyType:"string"},pad_end:{readonly:!0,dummyType:"string"},reverse_str:{readonly:!0,dummyType:"string"},is_empty:{readonly:!0,dummyType:"boolean"},is_digit:{readonly:!0,dummyType:"boolean"},is_alpha:{readonly:!0,dummyType:"boolean"},is_alnum:{readonly:!0,dummyType:"boolean"},is_array:{readonly:!0,dummyType:"boolean"},is_string:{readonly:!0,dummyType:"boolean"},is_number:{readonly:!0,dummyType:"boolean"},is_map:{readonly:!0,dummyType:"boolean"},is_function:{readonly:!0,dummyType:"boolean"},format:{readonly:!0,dummyType:"string"},sprintf:{readonly:!0,dummyType:"string"},cmd_render:{readonly:!0,dummyType:"string"},range:{readonly:!0,dummyType:"array"},abs:{readonly:!0,dummyType:"number"},min:{readonly:!0,dummyType:"number"},max:{readonly:!0,dummyType:"number"},floor:{readonly:!0,dummyType:"number"},ceil:{readonly:!0,dummyType:"number"},round:{readonly:!0,dummyType:"number"},sqrt:{readonly:!0,dummyType:"number"},pow:{readonly:!0,dummyType:"number"},sha256:{readonly:!0,dummyType:"string"},now:{readonly:!0,dummyType:"number",frozen:"now"},timestamp:{readonly:!0,dummyType:"number",frozen:"timestamp"},date:{readonly:!0,dummyType:"string",frozen:"date"},strftime:{readonly:!0,dummyType:"string"},coalesce:he,if_null:he,if_else:he,str:{readonly:!0,dummyType:"string"},num:{readonly:!0,dummyType:"number"},type:{readonly:!0,dummyType:"string"},require:{readonly:!0,control:"require"},assert:{readonly:!0,control:"assert"},error:{readonly:!0,control:"error",dummyType:"string"},exit:{readonly:!0,control:"exit",dummyType:"null"},print:{control:"print",dummyType:"string",taints:!1},println:{control:"println",dummyType:"string",taints:!1},printf:{control:"printf",dummyType:"string",taints:!1},system:{dummyType:"SystemResult",process:!0},run_script:{dummyType:"map"},http_get:{dummyType:"string"},random:{dummyType:"number"},sleep_ms:{dummyType:"null"},prompt_human:{dummyType:"null"},prompt_human_config:{dummyType:"map"}}),Ex={stdout:"",stderr:"",code:0,signal:null,timed_out:!1,duration_ms:0,pid:null,dry:!0};De=Symbol("core dry policy"),Cu=Symbol("dry invocation"),Nu=Symbol("implicit preflight work limit"),Ou=Symbol("implicit preflight stdout");Pt=class extends Error{isControlFlow=!0;exitCode=0};pa=class{entries=[];lastSite={line:1,column:1};failure;recordedDiagnostics=[];recordError(e,n=this.lastSite){this.sealed||(this.check(),this.recordedDiagnostics.push({...n,severity:"error",message:e}))}scriptExit;sealed=!1;loopLimit;platform;timeout;deadline=1/0;wallClock;environment;planBytes=0;work=0;workLimit;replay;cleanups=new Map;own(e){this.cleanups.has(e)||this.cleanups.set(e,{started:!1})}dispose(e){this.own(e);let n=this.cleanups.get(e);return n.started||(n.started=!0,n.value=e.dispose(),Ge(n.value)&&Promise.resolve(n.value).catch(()=>{})),n.value}controller=new AbortController;truncation;onStart;start(){Number.isFinite(this.deadline)||(this.deadline=performance.now()+this.timeout,this.onStart?.())}constructor(e={}){if(this.replay=e[Ou],this.workLimit=e[Nu]??1/0,this.platform=e.hostContext?.platform??e.platform??process.platform,this.wallClock=e.dryrunClockMs??Date.now(),!Number.isFinite(this.wallClock))throw Error("Dry wall clock must be finite");this.environment=Object.freeze(Object.assign(Object.create(null),e.hostContext?.env??process.env)),this.loopLimit=e.dryLoopLimit??10,this.timeout=e.dryrunTimeoutMs??5e3;for(let n of[this.loopLimit,this.timeout])if(!Number.isSafeInteger(n)||n<=0)throw Error("Dry bounds must be positive safe integers")}hasTaintedValues=!1;get tainted(){return this.hasTaintedValues}at(e){this.lastSite={file:e.file,line:e.line,column:e.column},++this.work>this.workLimit&&this.truncate("work budget exceeded"),this.check()}check(){if(this.truncation)throw new Pt(this.truncation);if(this.sealed)throw new Pt("Dry pass finished");performance.now()>=this.deadline&&this.truncate("time budget exceeded")}truncate(e){this.truncation??="dry run truncated: "+e,this.sealed=!0,this.controller.abort();for(let n of[...this.cleanups.keys()].reverse())try{this.dispose(n)}catch{}throw new Pt(this.truncation)}async wait(e){let n=Promise.resolve(e);n.catch(()=>{}),this.check();let r;try{let s=await Promise.race([n,new Promise((i,o)=>{let a=()=>{r&&(clearTimeout(r),r=void 0);let l=this.deadline-performance.now();if(l<=0)try{this.truncate("time budget exceeded")}catch(c){o(c)}else r=setTimeout(a,Math.min(2147483647,Math.max(1,l)))};this.onStart=a,a()})]);return this.check(),s}finally{r&&clearTimeout(r),this.onStart=void 0}}loop(e,n){return this.at(n),e<this.loopLimit?!1:(this.append({seq:this.entries.length+1,kind:"loop",file:n.file??"<main>",line:n.line,column:n.column,iterations:e,limit:this.loopLimit,message:"loop truncated at "+this.loopLimit,simulated:!1}),this.hasTaintedValues=!0,!0)}propertyView;propertyLoads=[];prepareProperties(e){if(e&&["Directory","NonInteractive"].includes(e.split(".")[0]))return;let n=this.propertyLoads.map(r=>r());return n.some(Ge)?Promise.all(n):void 0}fail(e,n=this.lastSite){throw this.check(),this.failure??={site:{...n},message:e,untrusted:this.tainted},new Pt(e)}finishExit(e,n=this.lastSite){this.scriptExit??={site:{...n},code:e}}captureFailure(e,n=this.lastSite){if(this.truncation)return;if(performance.now()>=this.deadline){try{this.truncate("time budget exceeded")}catch{}return}let r=wx(e);if(r!==void 0){this.finishExit(r,n);return}if(e?.isControlFlow&&e?.resourceFailure===void 0)return;let s=e instanceof M?{file:e.file,line:e.line,column:e.column}:n;this.failure??={site:{...s},message:e instanceof Error?e.message:String(e),untrusted:this.tainted}}captureOutput(e,n){if(!this.replay)return;this.check();let r=Buffer.byteLength(n)+Buffer.byteLength(this.lastSite.file??"")+32;this.planBytes+r>1024*1024-4096&&this.truncate("console output size exceeded"),this.planBytes+=r,this.replay.push({name:e,text:n,site:{...this.lastSite}})}record(e,n,r,s,i,o=!0){this.sealed||(this.check(),this.append({seq:this.entries.length+1,kind:s,file:r.file??"<main>",line:r.line,column:r.column,function:e,arguments:n,simulated:!0,...i?{argv:[...i],renderedArgv:Bu(i,this.platform==="win32"?"windows":"posix"),dialect:this.platform==="win32"?"windows":"posix"}:{}}),this.hasTaintedValues||=o)}snapshot(e){let n=new Map,r=new Map,s=0,i=a=>{s+=a,this.check(),s+this.planBytes>1024*1024-4096&&this.truncate("plan size exceeded")},o=(a,l,c)=>{if(i(8),c>256&&this.truncate("plan size traversal depth exceeded"),a===null||typeof a=="boolean")return a;if(typeof a=="string")return i(Buffer.byteLength(a)),a;if(typeof a=="number")return Number.isFinite(a)?a:{$type:String(a)};if(typeof a=="bigint"){let h=String(a);return i(h.length),{$type:"bigint",value:h}}if(typeof a=="symbol"){r.has(a)||r.set(a,r.size+1);let h=String(a);return i(Buffer.byteLength(h)),{$type:"symbol",id:r.get(a),value:h}}if(typeof a>"u"||typeof a=="function")return{$type:typeof a};if(Ae(a))return{$type:"resource"};if(ps.has(a)&&(a=Or(a)),ve.isProxy(a))return{$type:"proxy"};let u=Wu(a);if(u)return{$type:ve.isMap(a)?"Map":ve.isSet(a)?"Set":ve.isDate(a)?"Date":ve.isRegExp(a)?"RegExp":ve.isNativeError(a)?"Error":ve.isArrayBufferView(a)?"TypedArray":u};if(n.has(a))return{$ref:n.get(a)};n.set(a,l),Array.isArray(a)&&i(a.length);let d=Array.isArray(a)?new Array(a.length):{},m=Reflect.ownKeys(a);i(m.length*8);let p=Array.isArray(a),f=m.some(h=>typeof h=="symbol"||h==="$ref"||h==="$type"||p&&h!=="length"&&!(/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)<a.length)),g=[];for(let h of m.filter(y=>y!=="length"||!Array.isArray(a)).sort((y,v)=>String(y)<String(v)?-1:String(y)>String(v)?1:0)){let y=typeof h=="symbol"?"symbol:"+g.length:h;i(Buffer.byteLength(y));let v=Object.getOwnPropertyDescriptor(a,h),_="value"in v?o(v.value,f?l+"/properties/"+g.length+"/1":l+"/"+y.replaceAll("~","~0").replaceAll("/","~1"),c+1):{$type:"accessor"};f?g.push([typeof h=="symbol"?o(h,l+"/properties/"+g.length+"/0",c+1):h,_]):Object.defineProperty(d,y,{value:_,enumerable:!0,writable:!0,configurable:!0})}return f?{$type:p?"array":"object",...p?{length:a.length}:{},properties:g}:d};return o(e,"$",0)}append(e){let n=Buffer.byteLength(JSON.stringify(e))+1;this.planBytes+n>1024*1024-4096&&this.truncate("plan size exceeded"),this.planBytes+=n,this.entries.push(e)}capture(e){if(this.truncation)return;let n=e.diagnostics;if(!this.failure){let r=n.find(s=>s.severity==="error");r&&(this.failure={site:r,message:r.message,untrusted:this.tainted})}!this.failure&&!this.scriptExit&&e.exitCode&&e.exitCode!==0&&(this.failure={site:this.lastSite,message:"exit("+e.exitCode+")",untrusted:this.tainted})}report(e){let n=[...e.diagnostics];this.capture(e);let r=[...this.recordedDiagnostics];for(let l of e.errors??[])r.some(c=>c.message===l)||r.push({...this.lastSite,severity:"error",message:l});if(this.sealed=!0,this.truncation&&!this.failure)return hu({version:1,status:"truncated",entries:this.entries,stop:{file:this.lastSite.file??"<main>",line:this.lastSite.line,column:this.lastSite.column,reason:this.truncation},diagnostics:[...r,...n.filter(l=>l.severity!=="error"),{...this.lastSite,severity:"warning",message:this.truncation}],exitCode:0});if(!this.failure){let l=this.scriptExit?{file:this.scriptExit.site.file??"<main>",line:this.scriptExit.site.line,column:this.scriptExit.site.column,reason:"script exit with code "+this.scriptExit.code}:null;return hu({version:1,status:this.scriptExit?"complete":this.entries.some(c=>c.kind==="loop")?"loop-limited":"complete",entries:this.entries,stop:l,diagnostics:[...r,...n],exitCode:0})}let{site:s,message:i,untrusted:o}=this.failure,a=o?"needs a real result: "+i:i;return hu({version:1,status:o?"needs-real-result":"failed",entries:this.entries,stop:{file:s.file??"<main>",line:s.line,column:s.column,reason:a},diagnostics:[...r,...!o&&n.some(l=>l.severity==="error")?n:[...n.filter(l=>l.severity!=="error"),{...s,severity:o?"warning":"error",message:a}]],exitCode:o?0:2})}};Tx=new Set(["read","read_file","read_lines","read_json","read_csv"]);Mu=new WeakMap,bi=class{constructor(e){Mu.set(this,e)}},kx=5e3;Rx=1,Du=class{id;constructor(e){Rh++,Ih.add(this),Object.defineProperty(this,"id",{value:e,enumerable:!0}),Object.freeze(this)}},Rh=0;Ih=new WeakSet;ch=new WeakMap,xh=1e7;vi=class{failure;records=[];label;parent;base;constructor(e,n,r){this.label=e,this.parent=n,this.base=r}isAncestorOf(e){for(let n=e.parent;n;n=n.parent)if(n===this)return!0;return!1}},Ah=new uh;Fu=class{token=`run-${process.pid}-${Rx++}`;root=new vi("root");ordinal=0;terminating=!1;records=new WeakMap;ordered=[];rawRecords=new WeakMap;scopes=new WeakMap;onFailure;defaultDeadlineMs;failures=[];constructor(e,n={}){this.onFailure=e;let r=n.defaultDeadlineMs;this.defaultDeadlineMs=typeof r=="number"&&Number.isFinite(r)&&r>0?r:kx}scopeFor(e){for(let n=e;n;n=n.isFunctionScope?void 0:n.parent){let r=this.scopes.get(n);if(r)return r}return this.root}enterScope(e,n,r){let s=new vi(r,n);return this.scopes.set(e,s),s}temporaryScope(e,n,r){return new vi(n,e,r)}register(e,n,r,s){let i=String(e.id),o={handle:new Du(i),raw:e,kind:typeof e.kind=="string"&&e.kind?e.kind:n,id:i,site:r,ordinal:++this.ordinal,owner:s,state:"open",adoptable:!0,unresolved:!1};return ch.set(o.handle,`${o.kind} ${o.id}`),this.records.set(o.handle,o),this.rawRecords.set(e,o),this.ordered.push(o),s.records.push(o),o.handle}terminate(){if(!this.terminating){this.terminating=!0;for(let e of[...this.ordered].sort((n,r)=>r.ordinal-n.ordinal))if(!(e.state==="closed"||e.state==="close_failed"))try{typeof e.raw.finalizeSync=="function"&&(e.raw.finalizeSync(),e.state="closed")}catch(n){this.fail(e,"critical finalization failed: "+String(n))}}}authorizeRaw(e,n,r,s=!1){let i=e!==null&&typeof e=="object"?this.rawRecords.get(e):void 0;if(!i)throw Error("Resource "+String(e?.kind??"batch")+" "+String(e?.id)+" belongs to another run: "+r);if(i.owner!==n&&!i.owner.isAncestorOf(n))throw Error("Resource "+i.kind+" "+i.id+" is not authorized in this borrower scope: "+r);if(!s&&i.state!=="open")throw Error("Resource "+i.kind+" "+i.id+" is closed: "+r);return i}lookup(e){return this.records.get(e)}describe(e){let n=this.records.get(e);return n?`${n.kind} ${n.id}`:`${ch.get(e)??e.id} (from another run)`}borrow(e){if(Ae(e)){let n=this.records.get(e);n&&(n.adoptable=!1)}}bind(e,n,r){if(!Ae(e))return;let s=this.records.get(e);if(!s)return`resource ${e.id} belongs to another run`;let i=this.scopeFor(n);if(s.adoptable){s.adoptable=!1,i!==s.owner&&(s.owner.records.splice(s.owner.records.indexOf(s),1),i.records.push(s),s.owner=i);return}if(i!==s.owner&&i.isAncestorOf(s.owner))return`resource ${s.kind} ${s.id} cannot escape its owner into the longer-lived binding '${r}'`}close(e,n){if(e.closing)return e.closing;e.state="closing";let r=e.raw,s=r.closeDeadlineMs,i=typeof s=="number"&&Number.isFinite(s)&&s>0?s:this.defaultDeadlineMs,o=performance.now(),a;e.closing=new Promise(c=>{a=c});let l=`close did not finish within its ${i} ms deadline`;return(async()=>{let c,u=!1;try{let d=r.close({reason:this.terminating?"cancelled":e.owner.failure!==void 0?"error":"done",error:e.owner.failure instanceof Error?e.owner.failure.message:e.owner.failure==null?void 0:String(e.owner.failure),explicit:n});if(Ge(d)){let m=Promise.resolve(d).then(()=>!0);m.catch(()=>{});let p=i-(performance.now()-o);if(!(p>0&&await Promise.race([m,new Promise(g=>{c=setTimeout(()=>g(!1),p)})]))){this.critical(e),u=this.fail(e,l);return}}if(performance.now()-o>i){this.critical(e),u=this.fail(e,l);return}if(this.terminating&&e.state==="close_failed")return;e.state="closed",u=!0}catch(d){u=this.fail(e,d instanceof Error?d.message:String(d))}finally{c&&clearTimeout(c),a(u)}})(),e.closing}critical(e){try{typeof e.raw.finalizeSync=="function"&&e.raw.finalizeSync()}catch(n){this.report(`resource ${e.kind} ${e.id} (${e.site}): critical finalization failed: ${n instanceof Error?n.message:String(n)}`)}}fail(e,n){return e.state="close_failed",e.unresolved=!0,this.report(`resource close failed: ${e.kind} ${e.id} (${e.site}): ${n}`),!1}report(e){this.failures.push(e);try{this.onFailure(e)}catch{}}async drain(e){for(let n of[...e.records].sort((r,s)=>s.ordinal-r.ordinal))if(!(n.state==="closed"||n.state==="close_failed"))try{await this.close(n)}catch{}}snapshot(){return this.ordered.map(e=>({id:e.id,kind:e.kind,owner:e.owner.label,site:e.site,state:e.state,unresolved:e.unresolved,ordinal:e.ordinal}))}},fa=class{nativeImports;processContext;warningDiagnostics=[];dry;platform;abortSignal;resources;resourcesEnabled;temporaryScopes=new Map;globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new Au;isAsync;nextTaskId=1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recovery;initialGlobals;callDepth=0;noPreflight;asyncCallDepth=new Map;recordedErrors;promptHumanConfig;childEngineFactory;compileOptions;constructor(e,n=m=>console.log(m),r=!1,s,i,o,a=gi(void 0),l=process.platform,c,u=!1,d){this.nativeImports=d,this.dry=c,this.noPreflight=u,this.platform=l,this.recovery=a,this.recordedErrors=a.errors,this.stdout=n,this.stderr=i,this.isAsync=r,this.initialGlobals=s,this.globalEnv=new Qe,this.hostFunctions=new Map(e),this.promptHumanConfig=o??{mode:"interactive"},this.resourcesEnabled=[...this.hostFunctions.values()].some(I=>I.returnsResource===!0),this.resources=new Fu(I=>{ta(this.recovery,I);try{this.stderr?.(`error: ${I}`)}catch{}});let m=e.get("print");(!m||m.isDefault)&&this.hostFunctions.set("print",{...m,fn:(...I)=>{let A=m?.signature?.dryrunIndex===0?I.shift()===!0:!1,N=I.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return A||this.stdout(N),N},arity:m?.signature?.nativeArity??m?.arity??{min:0},description:m?.description??"Prints formatted values to output log",isDefault:!0});let p=e.get("println");(!p||p.isDefault)&&this.hostFunctions.set("println",{...p,fn:(...I)=>{let A=p?.signature?.dryrunIndex===0?I.shift()===!0:!1,N=I.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return A||this.stdout(N),N},arity:p?.signature?.nativeArity??p?.arity??{min:0},description:p?.description??"Prints line to output log",isDefault:!0});let f=e.get("printf");(!f||f.isDefault)&&this.hostFunctions.set("printf",{...f,fn:(...I)=>{let A=f?.signature?.dryrunIndex===0?I.shift()===!0:!1,[N,...O]=I,E=na(N,O,"printf");return A||this.stdout(E),E},arity:f?.signature?.nativeArity??f?.arity??{min:2},description:f?.description??"Formats and prints %s, %d, %f and %% using sprintf rules",isDefault:!0});let g=e.get("require");(!g||g.isDefault)&&this.hostFunctions.set("require",{...g,fn:(I,A)=>Uu(I,A,N=>{ta(this.recovery,N),this.stderr?.(`error: ${N}`)}),arity:2,isDefault:!0});let h=e.get("error");(!h||h.isDefault)&&this.hostFunctions.set("error",{...h,fn:(...I)=>{let A=I.map(N=>typeof N=="object"?JSON.stringify(N):String(N)).join(" ");return ta(this.recovery,A),this.stderr?this.stderr(`error: ${A}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${A}
394
394
  `):console.error(`error: ${A}`),A},arity:{min:1},description:h?.description??"Prints error message to stderr and records it for execution error summary",isDefault:!0});let y=e.get("system");(!y||y.isDefault)&&this.hostFunctions.set("system",{...y,fn:(I,A=6e4)=>this.isAsync?Eu(I,A,this.platform,this.abortSignal,this.processContext):vu(I,A,this.platform,this.processContext),arity:y?.arity??{min:1,max:2},description:"Executes argv directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",isDefault:!0});let v=e.get("prompt_human_config");(!v||v.isDefault)&&this.hostFunctions.set("prompt_human_config",{...v,fn:(I,A)=>{if(I===void 0)return{mode:this.promptHumanConfig.mode??"interactive",dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200};if(typeof I=="string")I==="interactive"?this.promptHumanConfig.mode="interactive":I==="file"?(this.promptHumanConfig.mode="file",A&&(this.promptHumanConfig.dir=String(A))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=I);else if(I&&typeof I=="object"){let N=I.mode?String(I.mode):I.dir?"file":this.promptHumanConfig.mode??"interactive",O=I.dir!==void 0?String(I.dir):this.promptHumanConfig.dir,E=I.timeout_ms!==void 0?Number(I.timeout_ms):I.timeoutMs!==void 0?Number(I.timeoutMs):this.promptHumanConfig.timeoutMs,T=I.poll_ms!==void 0?Number(I.poll_ms):I.pollIntervalMs!==void 0?Number(I.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=N==="file"?"file":"interactive",this.promptHumanConfig.dir=O,this.promptHumanConfig.timeoutMs=typeof E=="number"&&Number.isFinite(E)?E:void 0,this.promptHumanConfig.pollIntervalMs=typeof T=="number"&&Number.isFinite(T)&&T>0?T:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},arity:v?.arity??{min:0,max:2},description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",isDefault:!0});let _=e.get("prompt_human");(!_||_.isDefault)&&this.hostFunctions.set("prompt_human",{..._,fn:(I,A)=>{if((A?.mode??(A?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let O=A?.dir??this.promptHumanConfig.dir;if(!O)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsync)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return _h(I,{dir:O,sessionId:A?.sessionId??A?.sessionid??A?.id,timeoutMs:A?.timeout_ms??A?.timeoutMs??this.promptHumanConfig.timeoutMs,pollIntervalMs:A?.poll_ms??A?.pollIntervalMs??this.promptHumanConfig.pollIntervalMs,onWaiting:E=>this.stderr?this.stderr(E):typeof process<"u"&&process.stderr?process.stderr.write(E):void 0})}return this.isAsync?ga(I,void 0,void 0,this.abortSignal):yh(I)},arity:_?.arity??{min:0,max:2},description:"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",isDefault:!0});let b=e.get("cmd_render");(!b||b.isDefault)&&this.hostFunctions.set("cmd_render",{...b,fn:(I,A)=>Bu(I,A,this.platform),arity:{min:1,max:2},isDefault:!0});let w=e.get("run_script");(!w||w.isDefault)&&this.hostFunctions.set("run_script",{...w,fn:(I,A=[])=>{let N=ge.resolve(String(I));if(!W.existsSync(N))throw new Error(`run_script: file not found: '${N}'`);let O=W.readFileSync(N,"utf-8"),E=Array.isArray(A)?A.map(String):[],T=this.childEngineFactory?this.childEngineFactory({args:E}):new Kn;if(!this.childEngineFactory){for(let[S,R]of this.hostFunctions)T.hasFunction(S)?R.isDefault||T.registerFunction(S,R.fn,R.signature?.nativeArity??R.arity,{description:R.description,params:R.signature?.nativeParams??R.params,returnType:R.returnType,readonly:R.readonly,dryControl:R.dryControl,[De]:R[De],doc:R.doc,allowOverwrite:!0,isContainerMutation:R.isContainerMutation,...Lr(R)},!1,R.isContainerMutation):T.registerFunction(S,R.fn,R.signature?.nativeArity??R.arity,{description:R.description,params:R.signature?.nativeParams??R.params,returnType:R.returnType,readonly:R.readonly,dryControl:R.dryControl,[De]:R[De],doc:R.doc,isDefault:R.isDefault,isContainerMutation:R.isContainerMutation,...Lr(R)});T.setGlobal("args",[...E]),T.setGlobal("ARGV",[...E])}if(this.isAsync)return(async()=>{let S=await T.runAsync(O,{file:N,signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight}),R=Pr(S.value);if(R)throw new Error(`run_script: ${Ae(R)?`the child result contains resource ${R.id}, which cannot leave the child run`:yu(R,"child run")}`);let C=S.output.join(`
395
395
  `)+(S.output.length>0?`
396
396
  `:""),P=S.exitCode!==void 0?S.exitCode:S.success&&!S.errors?.length?0:1,D={success:S.success&&P===0,stdout:C,output:[...S.output],value:S.value,exit_code:P,code:P,errors:S.errors??[]};for(let U of[...S.errors??[],...S.diagnostics.filter(j=>j.severity==="error").map(j=>j.message)])this.recordedErrors.push(U);return D})();{let S=T.run(O,{file:N,signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight}),R=S.output.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmctl-ai/lmctl",
3
- "version": "0.2.183",
3
+ "version": "0.2.185",
4
4
  "description": "A provider-agnostic control plane for teams of AI coding agents — across providers, with independent review and durable memory.",
5
5
  "type": "module",
6
6
  "homepage": "https://lmctl.com",