@lmctl-ai/lmctl 0.2.102 → 0.2.104

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
@@ -4,6 +4,8 @@ All notable public-preview changes for `@lmctl-ai/lmctl` are recorded here.
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ - **is_empty now tests literal emptiness.** Whitespace-only strings return false; use is_blank for whitespace checks. Empty strings, null, empty arrays and empty maps still return true.
8
+
7
9
  - **Compatible database upgrades are quiet.** Older lmctl builds open declared-compatible additive schema changes without a warning. Incompatible databases still require an update; the refusal names the exact npm command and explains that no manual data migration is needed. --allow-schema-skew remains a last resort and warns about hidden newer data.
8
10
  - **Retired no-op surfaces removed.** Database utilities expose backfill-events; the downgrade stub and dead infra environment interception are gone. Tail refuses --json with --max-bytes (exit 2); JSON still supports --lines. The standalone runner no longer recognizes --module, and imports named lmctl resolve ordinary source files. The lmctl prompt_human binding accepts at most one argument. Removed pass-through builtins sorted, length, date_format, default_to and to_string now suggest sort, len, strftime, if_null and str before effects.
9
11
 
package/build-info.json CHANGED
@@ -1 +1 @@
1
- {"sha": "f0a533a17fa108459398bc48a6169b72eb957242", "dirty": false, "builtAt": "2026-10-06T04:12:41.000Z"}
1
+ {"sha": "d49c99a01e9036083364a5d1c8d954073a6cd138", "dirty": false, "builtAt": "2026-10-06T04:47:26.000Z"}
@@ -407,7 +407,7 @@ fn clamp(val, low, high) {
407
407
  `)+(O.output.length>0?`
408
408
  `:""),S=O.exitCode!==void 0?O.exitCode:O.success?0:1,R={success:O.success&&S===0,stdout:w,output:[...O.output],value:O.value,exit_code:S,code:S,errors:O.errors??[]};return R.toString=()=>w,R})();{let O=L.run(I,{file:T}),k=O.output.join(`
409
409
  `)+(O.output.length>0?`
410
- `:""),w=O.exitCode!==void 0?O.exitCode:O.success?0:1,S={success:O.success&&w===0,stdout:k,output:[...O.output],value:O.value,exit_code:w,code:w,errors:O.errors??[]};return S.toString=()=>k,S}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let h=e.get("http_get");(!h||h.isDefault)&&this.hostFunctions.set("http_get",{fn:g=>this.isAsync?Zw(g):bm(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let v=e.get("sleep_ms");(!v||v.isDefault)&&this.hostFunctions.set("sleep_ms",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(T=>setTimeout(T,g));let E=Date.now()+g;for(;Date.now()<E;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new De,this.initialGlobals)for(let[r,s]of this.initialGlobals.entries())this.globalEnv.define(r,s);this.userFunctions.clear(),this.callDepth=0,this.recovery=Ra(this.resumepoint);for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.userFunctions.set(r.name,r);let n;for(let r of e.statements)r.kind!=="FunctionDeclStmt"&&(n=this.execStmt(r,this.globalEnv));return this.checkRootRemainder(e),n}enterRecover(e,n){if(n)throw new M("recover cannot be entered inside a parallel task",e.line,e.column,"RUNTIME",e.file);let r=this.recovery;if(r.entered.has(e))throw new M("recover statement already entered during this run",e.line,e.column,"RUNTIME",e.file);if(r.entered.add(e),r.active=!0,r.pending.length===0)return{start:0,consumed:!1};let s=r.pending.shift(),i=e.points.findIndex(o=>o.name===s);if(i<0)throw new M(`Unknown resumepoint '${s}' in entered recover; available: ${e.points.map(o=>o.name).join(", ")}`,e.line,e.column,"RUNTIME",e.file);return{start:i,consumed:!0}}enterPoint(e,n){this.recovery.stack.length=e,this.recovery.stack.push(n),this.publishResumepoint()}leaveRecover(e){this.recovery.stack.length=e,this.publishResumepoint()}publishResumepoint(){this.globalEnv.define("RESUMEPOINT",this.recovery.stack.length>0?this.recovery.stack.join("."):null)}checkRemainder(e){if(Oe(this.abortSignal),this.recovery.pending.length>0)throw new M(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(Oe(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new M(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRecoverRead(e,n,r,s){let i=this.recoverScopedReads.get(r);if(!i)return;let o=this.recovery.envs.get(i);if(o&&n.resolveBinding(e)?.env!==o)throw new M(`Variable '${e}' was read before its binding was initialized`,s.line,s.column,"RUNTIME",s.file)}recoverWriteScope(e,n){let r=this.recoverScopedWrites.get(n)?.get(e);return r?this.recovery.envs.get(r):void 0}execStmt(e,n){switch(Oe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let r=new De(n);for(let s of e.statements)this.execStmt(s,r);return}case"VarDeclStmt":{let r=null;return e.initializer&&(r=this.evalExpr(e.initializer,n)),n.define(e.name,r),r}case"TupleVarDeclStmt":{let r=this.evalExpr(e.initializer,n);if(!Array.isArray(r))throw new M(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.execStmt(e.thenBranch,n):e.elseBranch?this.execStmt(e.elseBranch,n):void 0}case"WhileStmt":{let r=0;for(;this.isTruthy(this.evalExpr(e.condition,n));){if(++r>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(s){if(s instanceof ft)break;if(s instanceof gt)continue;throw s}}return}case"ForInStmt":{let r=fm(this.evalExpr(e.iterable,n),e),s=0;for(let i of r){if(++s>1e6)throw new M("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let o=new De(n);o.define(e.name,i);try{if(e.body.kind==="BlockStmt")for(let a of e.body.statements)this.execStmt(a,o);else this.execStmt(e.body,o)}catch(a){if(a instanceof ft)break;if(a instanceof gt)continue;throw a}}return}case"ForStmt":{let r=new De(n);e.init&&this.execStmt(e.init,r);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,r);if(!this.isTruthy(i))break}if(++s>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(i){if(i instanceof ft)break;if(!(i instanceof gt))throw i}e.update&&this.evalExpr(e.update,r)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new Gn(r)}case"BreakStmt":throw new ft;case"ContinueStmt":throw new gt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,n);case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new De(n);this.recovery.envs.set(e,s);let i=this.recovery.stack.length;try{for(let o=r.start;o<e.points.length;o++){let a=e.points[o];this.enterPoint(i,a.name);for(let l of a.statements)this.execStmt(l,s);r.consumed&&o===r.start&&this.checkRemainder(a)}}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(Oe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let r="";for(let s of e.parts)r+=typeof s=="string"?s:Ua(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new M("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let r=this.evalExpr(e.value,n),s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return s?s.define(e.target,r):n.set(e.target,r),r}case"TupleAssignExpr":{let r=this.evalExpr(e.value,n);if(!Array.isArray(r))throw new M(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<r.length?r[s]:null,o=this.recovery.active?this.recoverWriteScope(e.targets[s],e):void 0;o?o.define(e.targets[s],i):n.set(e.targets[s],i)}return r}case"IndexAssignExpr":{let r=this.evalExpr(e.target,n),s=this.evalExpr(e.index,n),i=this.evalExpr(e.value,n);if(Array.isArray(r)||typeof r=="object"&&r!==null)return Array.isArray(r)&&typeof s=="number"&&s<0&&(s=r.length+s),Je(r,s,i),i;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,n);case"TupleExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ArrayExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ObjectExpr":{let r={};for(let s of e.properties)Je(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=ei(e);if(r)return We(this.resolveIdentifier("PROPS",n,e),r);let s=this.evalExpr(e.target,n),i=this.evalExpr(e.index,n);if(s==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:We(s,i)}case"UnaryExpr":{let r=this.evalExpr(e.operand,n),s=e.operator;if(s==="!")return!this.isTruthy(r);if(s==="-")return-r;throw new M(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.evalExpr(e.trueArm,n):this.evalExpr(e.falseArm,n)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?this.evalExpr(e.right,n):o}if(e.operator==="||"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?o:this.evalExpr(e.right,n)}let r=this.evalExpr(e.left,n),s=this.evalExpr(e.right,n),i=e.operator;switch(i){case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":if(s===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:throw new M(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let r=e.args.map(s=>this.evalExpr(s,n));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),this.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}resolveIdentifier(e,n,r){if(this.recovery.active&&this.checkRecoverRead(e,n,r,r),n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&Ba.has(s))try{let i=Ba.get(s)();return Jn(i)?i.catch(o=>{throw new M(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new M(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new En(e);throw new M(`Variable '${e}' was read before its binding was initialized`,r.line,r.column,"RUNTIME",r.file)}resolveCallTarget(e,n){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;let r=n.get(e);return r instanceof En?r.name:e}invokeNamed(e,n,r,s,i,o){if(Oe(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Xs)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xs})`,s,i,"RUNTIME",o);let l=new De(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],n[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Gn)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);if(a.returnsResource)throw new M(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);try{Oe(this.abortSignal);let l=a.fn(...n);if(a.returnsResource&&Jn(l))throw l.then(c=>{try{c&&typeof c.finalizeSync=="function"?c.finalizeSync():c&&typeof c.close=="function"&&c.close()}catch{}},()=>{}),new Error("returns a resource asynchronously; use engine.runAsync()");return l}catch(l){throw l instanceof ht||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(Nr(e,"Undefined function"),s,i,"RUNTIME",o)}ownerFor(e,n){let r=this.resources.scopeFor(e),s=this.temporaryScopes.get(n),i=s&&s[s.length-1];return i&&i.base===r?i:r}pushTemporaryScope(e,n){let r=this.temporaryScopes.get(e);r?r.push(n):this.temporaryScopes.set(e,[n])}popTemporaryScope(e){let n=this.temporaryScopes.get(e);n?.pop(),n&&n.length===0&&this.temporaryScopes.delete(e)}async execLoopBodyAsync(e,n,r){if(!this.resourcesEnabled||e.kind==="BlockStmt"){await this.execStmtAsync(e,n,r);return}let s=this.resources.temporaryScope(this.ownerFor(n,r),"iteration",this.resources.scopeFor(n));this.pushTemporaryScope(r,s);try{await this.execStmtAsync(e,n,r)}finally{this.popTemporaryScope(r),s.records.length>0&&await this.resources.drain(s)}}resourceError(e,n,r){return new M(`Resource ${this.resources.describe(e)} ${n}`,r.line,r.column,"RUNTIME",r.file)}refuseResource(e,n,r){if(ve(e))throw this.resourceError(e,n,r)}bindResource(e,n,r,s){let i=this.resources.bind(e,n,r);if(i)throw new M(i.charAt(0).toUpperCase()+i.slice(1),s.line,s.column,"RUNTIME",s.file)}async resourceCallArgs(e,n,r,s,i,o){if(!r.some(ve))return r;let a={line:s,column:i,file:o};if(!e.usesResource&&!e.closesResource)throw this.resourceError(r.find(ve),`cannot be passed to '${n}'`,a);let l=[];for(let c of r){if(!ve(c)){l.push(c);continue}let d=this.resources.lookup(c);if(!d)throw this.resourceError(c,`cannot be used by '${n}': it belongs to another run`,a);if(e.closesResource)this.resources.borrow(c),await this.resources.close(d);else if(d.state!=="open")throw this.resourceError(c,`is ${d.state==="closing"?"closing":"closed"}: '${n}' cannot use it`,a);this.resources.borrow(c),l.push(d.raw)}return l}registerHostResource(e,n,r,s,i,o){if(e==null)return e;if(typeof e!="object"||typeof e.close!="function"||typeof e.id!="string"&&typeof e.id!="number"||String(e.id)==="")throw new Error("a returnsResource host must return null or an object with a close method and a stable id");return this.resources.register(e,n,`${o??"<main>"}:${s}:${i}`,r)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new De,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear(),this.recovery=Ra(this.resumepoint);for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let n=this.nextTaskId++;this.recovery.rootTaskId=n;let r;try{for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(r=await this.execStmtAsync(s,this.globalEnv,n))}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),ve(r))r=null;else if(ym()){let s=xa(r);if(s)throw new M(ve(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:Aa(s,"run"),1,1,"RUNTIME")}return r}async execStmtAsync(e,n,r){switch(Oe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let s=new De(n);if(!this.resourcesEnabled){for(let o of e.statements)await this.execStmtAsync(o,s,r);return}let i=this.resources.enterScope(s,this.ownerFor(n,r),"block");try{for(let o of e.statements)await this.execStmtAsync(o,s,r)}finally{i.records.length>0&&await this.resources.drain(i)}return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,n,r)),ve(s)&&this.bindResource(s,n,e.name,e),n.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(Array.isArray(s))for(let i=0;i<e.names.length&&i<s.length;i++)this.bindResource(s[i],n,e.names[i],e);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,n,r):e.elseBranch?await this.execStmtAsync(e.elseBranch,n,r):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,n,r));){if(++s>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,n,r):await this.execStmtAsync(e.body,n,r)}catch(i){if(i instanceof ft)break;if(i instanceof gt)continue;throw i}}return}case"ForInStmt":{let s=fm(await this.evalExprAsync(e.iterable,n,r),e),i=0;for(let o of s){if(++i>1e6)throw new M("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new De(n);a.define(e.name,o);let l=this.resourcesEnabled?this.resources.enterScope(a,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let c of e.body.statements)await this.execStmtAsync(c,a,r);else await this.execStmtAsync(e.body,a,r)}finally{l&&l.records.length>0&&await this.resources.drain(l)}}catch(c){if(c instanceof ft)break;if(c instanceof gt)continue;throw c}}return}case"ForStmt":{let s=new De(n),i=this.resourcesEnabled?this.resources.enterScope(s,this.ownerFor(n,r),"for"):void 0;try{e.init&&await this.execStmtAsync(e.init,s,r);let o=0;for(;;){if(e.condition){let a=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(a))break}if(++o>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,s,r):await this.execStmtAsync(e.body,s,r)}catch(a){if(a instanceof ft)break;if(!(a instanceof gt))throw a}e.update&&await this.evalExprAsync(e.update,s,r)}}finally{i&&i.records.length>0&&await this.resources.drain(i)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,n,r):null;throw ve(s)&&this.refuseResource(s,"cannot be returned: a resource stays with its owner (return copied data instead)",e),new Gn(s)}case"BreakStmt":throw new ft;case"ContinueStmt":throw new gt;case"SyncAssignStmt":{let s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0,i=s?{env:s,name:e.target}:n.resolveBinding(e.target);if(!i)throw new M(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let o=`bind:${i.env.id}:${i.name}`;await this.lockManager.getBindingLock(o).withLock(async()=>{let l=await this.evalExprAsync(e.value,n,r);this.bindResource(l,i.env,i.name,e),i.env.define(i.name,l)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new M("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,n,r),a=await this.evalExprAsync(e.value,n,r);this.refuseResource(s,"cannot be modified",e),this.refuseResource(o,"cannot be used as a map key",e),this.refuseResource(a,"cannot be stored in a container",e),Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Je(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new M(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],n,r);if(o==null||typeof o!="object"&&typeof o!="function")throw new M("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":return await this.evalExprAsync(e.expr,n,r);case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new De(n);this.recovery.envs.set(e,i);let o=this.resourcesEnabled?this.resources.enterScope(i,this.ownerFor(n,r),"block"):void 0,a=this.recovery.stack.length;try{for(let l=s.start;l<e.points.length;l++){let c=e.points[l];this.enterPoint(a,c.name);for(let d of c.statements)await this.execStmtAsync(d,i,r);s.consumed&&l===s.start&&this.checkRemainder(c)}}finally{this.leaveRecover(a),o&&o.records.length>0&&await this.resources.drain(o)}return}default:return}}async evalExprAsync(e,n,r){switch(Oe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let s="";for(let i of e.parts){if(typeof i=="string"){s+=i;continue}let o=await this.evalExprAsync(i.expression,n,r);this.refuseResource(o,"cannot be converted to text",i.expression),s+=Ua(o,i)}return s}case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let s=await this.evalExprAsync(e.value,n,r),i=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return ve(s)&&this.bindResource(s,i??n.writeTarget(e.target),e.target,e),i?i.define(e.target,s):n.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,n,r);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null,a=this.recovery.active?this.recoverWriteScope(e.targets[i],e):void 0;ve(o)&&this.bindResource(o,a??n.writeTarget(e.targets[i]),e.targets[i],e),a?a.define(e.targets[i],o):n.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,n,r),i=await this.evalExprAsync(e.index,n,r),o=await this.evalExprAsync(e.value,n,r);if(this.refuseResource(s,"cannot be modified",e),this.refuseResource(i,"cannot be used as a map key",e),this.refuseResource(o,"cannot be stored in a container",e),Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Je(s,i,o),o;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,n,r);case"TupleExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ArrayExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ObjectExpr":{let s={};for(let i of e.properties){let o=await this.evalExprAsync(i.value,n,r);this.refuseResource(o,"cannot be stored in a container",i.value),Je(s,i.key,o)}return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(r)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;this.asyncCallDepth.set(d,s);let u=this.resourcesEnabled?this.resources.temporaryScope(this.ownerFor(n,r),"task",this.resources.scopeFor(n)):void 0;u&&this.pushTemporaryScope(d,u);try{let m=await this.evalExprAsync(c,n,d),p=ym()?xa(m):void 0;if(p)throw new M(ve(p)?`Resource ${this.resources.describe(p)} cannot be a parallel task result: it stays with the task that opened it`:Aa(p,"parallel task"),c.line,c.column,"RUNTIME",c.file);return m}finally{u&&(this.popTemporaryScope(d),u.records.length>0&&await this.resources.drain(u))}}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=ei(e);if(s)return We(await this.resolveIdentifier("PROPS",n,e),s);let i=await this.evalExprAsync(e.target,n,r),o=await this.evalExprAsync(e.index,n,r);if(this.refuseResource(o,"cannot be used as a map key",e),ve(i)){if(o==="id")return i.id;throw this.resourceError(i,`has no readable field '${String(o)}' (only id)`,e)}if(i==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(i)&&typeof o=="number"&&o<0?i[i.length+o]:We(i,o)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,n,r),i=e.operator;if(i==="!")return!this.isTruthy(s);if(this.refuseResource(s,"cannot be used in arithmetic",e),i==="-")return-s;throw new M(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,n,r):await this.evalExprAsync(e.falseArm,n,r)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?await this.evalExprAsync(e.right,n,r):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,n,r)}let s=await this.evalExprAsync(e.left,n,r),i=await this.evalExprAsync(e.right,n,r),o=e.operator;switch((ve(s)||ve(i))&&o!=="=="&&o!=="!="&&(this.refuseResource(s,`cannot be used with '${o}' (only ==, != and truth tests)`,e),this.refuseResource(i,`cannot be used with '${o}' (only ==, != and truth tests)`,e)),o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,n,r));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),await this.invokeCallAsync(e.callee,s,n,e.line,e.column,r,e.file)}}}async invokeCallAsync(e,n,r,s,i,o,a){let l=this.resolveCallTarget(e,r);if(Oe(this.abortSignal),this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Xs)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xs})`,s,i,"RUNTIME",a);let u=new De(this.globalEnv,!0),m=this.resourcesEnabled?this.resources.enterScope(u,this.ownerFor(r,o),`function ${l}`):void 0;for(let p=0;p<c.params.length;p++)m&&this.resources.borrow(n[p]),u.define(c.params[p],n[p]);try{for(let p of c.body.statements)await this.execStmtAsync(p,u,o)}catch(p){if(p instanceof Gn)return p.value;throw p}finally{m&&m.records.length>0&&await this.resources.drain(m),this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l),d=fT(n)?await this.resourceCallArgs(c,l,n,s,i,a):n;try{let u=c.fn(...d),m=u instanceof Promise?await u:u;return c.returnsResource?this.registerHostResource(m,l,this.ownerFor(r,o),s,i,a):m}catch(u){throw u instanceof ht||u?.name==="LMScriptExit"||u?.isControlFlow?u:new M(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(Nr(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},gT=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. Function bodies establish an isolated local variable scope for assignments, preventing accidental mutation of caller variables.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],hT=[{name:"sha256",category:"Math & Utilities",signature:"sha256(text: string): string",description:"Lowercase SHA-256 hex of UTF-8 bytes; rejects non-string inputs.",example:'sha256("abc");'},{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("teams/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), reports through injected diagnostics/captured errors and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests a JavaScript regex against text.",example:'regex_test("abc", "a");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns first [full_match, group1, ...], including with g; missing optional groups become null. Rejects sticky y.",example:'regex_match("a1 b2", "([a-z])([0-9])", "g");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns capture arrays for matches; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_find_all("a1 b2", "([a-z])([0-9])");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:"JavaScript regex replacement with $1 captures; use g for repeated replacement.",example:'regex_replace("a1", "([a-z])([0-9])", "$2$1");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits using JavaScript regex semantics.",example:'split_regex("a b", " +");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width/other precision limit: 10000. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:"join(arr: array, [separator: string]): string",description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"upper_first",category:"Strings",signature:"upper_first(s: string): string",description:"Capitalizes the first character of a string.",example:'c = upper_first("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the UTF-16 code unit at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, ...items: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, ...items: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(first: array, ...more: array): array",description:"Concatenates two or more arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:'Safely parses JSON with markdown fence and preamble tolerance, returning fallback on failure without throwing. Use a custom sentinel (e.g. "PARSE_FAILED") to distinguish parse failure from valid JSON null.',example:'data = json_parse_safe(llm_output, "PARSE_FAILED"); if (data == "PARSE_FAILED") { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 0]): string",description:"Serializes a value to compact JSON by default; optional indent formats the output.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string], [options: map]): string|null; prompt_human(session: map, [options: map]): map",description:"Pauses execution to prompt an operator on terminal stdin or dedicated directory, returning the entered input line or decision map, or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"prompt_human_config",category:"System & Process",signature:"prompt_human_config([config: map|string], [dir: string]): map",description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms). Returns current configuration map.",example:'prompt_human_config({ dir: "/tmp/handoffs", timeout_ms: 60000 });'},{name:"error",category:"System & Process",signature:"error(value: any, ...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats values into an output-log entry rendered as a line by the CLI. Returns the formatted text without adding a newline.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules.",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline.",example:'println("Done.");'},{name:"sleep_ms",category:"System & Process",signature:"sleep_ms(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep_ms(1000);"},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in milliseconds.",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now or a supplied epoch-millisecond value.",example:"created = date(0);"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null (including no arguments).",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"http_get",category:"System & Process",signature:"http_get(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = http_get("https://example.com");'}],_T=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];Kt=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;promptHumanConfig={mode:"interactive"};hostCatalog=new Map;builtinProviders=new Map;hostResolver;constructor(e={}){this.hostResolver=e.resolveHostModule,this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions();for(let[n,r]of[["get_property",{min:1,max:2}],["has_property",1],["get_properties",{min:0,max:1}],["set_property",2]])this.registerFunction(n,()=>{throw Error("Property store is not running")},r,"Read or overlay hierarchical run-local properties; no persistence");this.registerFunction("expand",()=>{throw Error("Template resolver is not running")},{min:1,max:2},"Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque"),this.registerDefaultDocs();for(let[n,r,s]of[["get_property","get_property(key, [default])","Returns a copied property value; absent keys are errors unless a default is supplied."],["has_property","has_property(key)","Tests property presence; missing/invalid profile errors remain loud."],["get_properties","get_properties([prefix])","Returns a detached nested property table copy."],["set_property","set_property(key, value)","Returns the previous value and changes only the run-local overlay; invocation facts are read-only."]])this.functionDocs.set(n,{name:n,signature:r,description:s,module:"core",category:"Properties"});this.functionDocs.set("expand",{name:"expand",signature:"expand(text, [vars])",description:"Resolve ${name} from an explicit vars map, ${PROPS.path}, and ${ARGV[n]}; $${ escapes, no caller-local capture or recursive expansion.",module:"core",category:"Strings"})}registerDefaultDocs(){for(let e of gT)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of hT)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of _T)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){return this.functionDocs.set(e.name,{...e,module:e.module??this.currentRegisteringModule}),this}registerModule(e,n){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let r=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,n)}finally{this.currentRegisteringModule=r}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return Array.from(this.functionDocs.values()).filter(n=>(n.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return Array.from(this.functionDocs.values())}getFunctionDoc(e){return this.functionDocs.get(e)}getFunctionCategories(){let e=new Set;for(let n of this.functionDocs.values())e.add(n.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(n=>n.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>F.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>F.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=F.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
410
+ `:""),w=O.exitCode!==void 0?O.exitCode:O.success?0:1,S={success:O.success&&w===0,stdout:k,output:[...O.output],value:O.value,exit_code:w,code:w,errors:O.errors??[]};return S.toString=()=>k,S}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let h=e.get("http_get");(!h||h.isDefault)&&this.hostFunctions.set("http_get",{fn:g=>this.isAsync?Zw(g):bm(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let v=e.get("sleep_ms");(!v||v.isDefault)&&this.hostFunctions.set("sleep_ms",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(T=>setTimeout(T,g));let E=Date.now()+g;for(;Date.now()<E;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new De,this.initialGlobals)for(let[r,s]of this.initialGlobals.entries())this.globalEnv.define(r,s);this.userFunctions.clear(),this.callDepth=0,this.recovery=Ra(this.resumepoint);for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.userFunctions.set(r.name,r);let n;for(let r of e.statements)r.kind!=="FunctionDeclStmt"&&(n=this.execStmt(r,this.globalEnv));return this.checkRootRemainder(e),n}enterRecover(e,n){if(n)throw new M("recover cannot be entered inside a parallel task",e.line,e.column,"RUNTIME",e.file);let r=this.recovery;if(r.entered.has(e))throw new M("recover statement already entered during this run",e.line,e.column,"RUNTIME",e.file);if(r.entered.add(e),r.active=!0,r.pending.length===0)return{start:0,consumed:!1};let s=r.pending.shift(),i=e.points.findIndex(o=>o.name===s);if(i<0)throw new M(`Unknown resumepoint '${s}' in entered recover; available: ${e.points.map(o=>o.name).join(", ")}`,e.line,e.column,"RUNTIME",e.file);return{start:i,consumed:!0}}enterPoint(e,n){this.recovery.stack.length=e,this.recovery.stack.push(n),this.publishResumepoint()}leaveRecover(e){this.recovery.stack.length=e,this.publishResumepoint()}publishResumepoint(){this.globalEnv.define("RESUMEPOINT",this.recovery.stack.length>0?this.recovery.stack.join("."):null)}checkRemainder(e){if(Oe(this.abortSignal),this.recovery.pending.length>0)throw new M(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(Oe(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new M(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRecoverRead(e,n,r,s){let i=this.recoverScopedReads.get(r);if(!i)return;let o=this.recovery.envs.get(i);if(o&&n.resolveBinding(e)?.env!==o)throw new M(`Variable '${e}' was read before its binding was initialized`,s.line,s.column,"RUNTIME",s.file)}recoverWriteScope(e,n){let r=this.recoverScopedWrites.get(n)?.get(e);return r?this.recovery.envs.get(r):void 0}execStmt(e,n){switch(Oe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let r=new De(n);for(let s of e.statements)this.execStmt(s,r);return}case"VarDeclStmt":{let r=null;return e.initializer&&(r=this.evalExpr(e.initializer,n)),n.define(e.name,r),r}case"TupleVarDeclStmt":{let r=this.evalExpr(e.initializer,n);if(!Array.isArray(r))throw new M(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.execStmt(e.thenBranch,n):e.elseBranch?this.execStmt(e.elseBranch,n):void 0}case"WhileStmt":{let r=0;for(;this.isTruthy(this.evalExpr(e.condition,n));){if(++r>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(s){if(s instanceof ft)break;if(s instanceof gt)continue;throw s}}return}case"ForInStmt":{let r=fm(this.evalExpr(e.iterable,n),e),s=0;for(let i of r){if(++s>1e6)throw new M("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let o=new De(n);o.define(e.name,i);try{if(e.body.kind==="BlockStmt")for(let a of e.body.statements)this.execStmt(a,o);else this.execStmt(e.body,o)}catch(a){if(a instanceof ft)break;if(a instanceof gt)continue;throw a}}return}case"ForStmt":{let r=new De(n);e.init&&this.execStmt(e.init,r);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,r);if(!this.isTruthy(i))break}if(++s>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(i){if(i instanceof ft)break;if(!(i instanceof gt))throw i}e.update&&this.evalExpr(e.update,r)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new Gn(r)}case"BreakStmt":throw new ft;case"ContinueStmt":throw new gt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,n);case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new De(n);this.recovery.envs.set(e,s);let i=this.recovery.stack.length;try{for(let o=r.start;o<e.points.length;o++){let a=e.points[o];this.enterPoint(i,a.name);for(let l of a.statements)this.execStmt(l,s);r.consumed&&o===r.start&&this.checkRemainder(a)}}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(Oe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let r="";for(let s of e.parts)r+=typeof s=="string"?s:Ua(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new M("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let r=this.evalExpr(e.value,n),s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return s?s.define(e.target,r):n.set(e.target,r),r}case"TupleAssignExpr":{let r=this.evalExpr(e.value,n);if(!Array.isArray(r))throw new M(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<r.length?r[s]:null,o=this.recovery.active?this.recoverWriteScope(e.targets[s],e):void 0;o?o.define(e.targets[s],i):n.set(e.targets[s],i)}return r}case"IndexAssignExpr":{let r=this.evalExpr(e.target,n),s=this.evalExpr(e.index,n),i=this.evalExpr(e.value,n);if(Array.isArray(r)||typeof r=="object"&&r!==null)return Array.isArray(r)&&typeof s=="number"&&s<0&&(s=r.length+s),Je(r,s,i),i;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,n);case"TupleExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ArrayExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ObjectExpr":{let r={};for(let s of e.properties)Je(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=ei(e);if(r)return We(this.resolveIdentifier("PROPS",n,e),r);let s=this.evalExpr(e.target,n),i=this.evalExpr(e.index,n);if(s==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:We(s,i)}case"UnaryExpr":{let r=this.evalExpr(e.operand,n),s=e.operator;if(s==="!")return!this.isTruthy(r);if(s==="-")return-r;throw new M(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.evalExpr(e.trueArm,n):this.evalExpr(e.falseArm,n)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?this.evalExpr(e.right,n):o}if(e.operator==="||"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?o:this.evalExpr(e.right,n)}let r=this.evalExpr(e.left,n),s=this.evalExpr(e.right,n),i=e.operator;switch(i){case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":if(s===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:throw new M(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let r=e.args.map(s=>this.evalExpr(s,n));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),this.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}resolveIdentifier(e,n,r){if(this.recovery.active&&this.checkRecoverRead(e,n,r,r),n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&Ba.has(s))try{let i=Ba.get(s)();return Jn(i)?i.catch(o=>{throw new M(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new M(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new En(e);throw new M(`Variable '${e}' was read before its binding was initialized`,r.line,r.column,"RUNTIME",r.file)}resolveCallTarget(e,n){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;let r=n.get(e);return r instanceof En?r.name:e}invokeNamed(e,n,r,s,i,o){if(Oe(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Xs)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xs})`,s,i,"RUNTIME",o);let l=new De(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],n[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Gn)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);if(a.returnsResource)throw new M(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);try{Oe(this.abortSignal);let l=a.fn(...n);if(a.returnsResource&&Jn(l))throw l.then(c=>{try{c&&typeof c.finalizeSync=="function"?c.finalizeSync():c&&typeof c.close=="function"&&c.close()}catch{}},()=>{}),new Error("returns a resource asynchronously; use engine.runAsync()");return l}catch(l){throw l instanceof ht||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(Nr(e,"Undefined function"),s,i,"RUNTIME",o)}ownerFor(e,n){let r=this.resources.scopeFor(e),s=this.temporaryScopes.get(n),i=s&&s[s.length-1];return i&&i.base===r?i:r}pushTemporaryScope(e,n){let r=this.temporaryScopes.get(e);r?r.push(n):this.temporaryScopes.set(e,[n])}popTemporaryScope(e){let n=this.temporaryScopes.get(e);n?.pop(),n&&n.length===0&&this.temporaryScopes.delete(e)}async execLoopBodyAsync(e,n,r){if(!this.resourcesEnabled||e.kind==="BlockStmt"){await this.execStmtAsync(e,n,r);return}let s=this.resources.temporaryScope(this.ownerFor(n,r),"iteration",this.resources.scopeFor(n));this.pushTemporaryScope(r,s);try{await this.execStmtAsync(e,n,r)}finally{this.popTemporaryScope(r),s.records.length>0&&await this.resources.drain(s)}}resourceError(e,n,r){return new M(`Resource ${this.resources.describe(e)} ${n}`,r.line,r.column,"RUNTIME",r.file)}refuseResource(e,n,r){if(ve(e))throw this.resourceError(e,n,r)}bindResource(e,n,r,s){let i=this.resources.bind(e,n,r);if(i)throw new M(i.charAt(0).toUpperCase()+i.slice(1),s.line,s.column,"RUNTIME",s.file)}async resourceCallArgs(e,n,r,s,i,o){if(!r.some(ve))return r;let a={line:s,column:i,file:o};if(!e.usesResource&&!e.closesResource)throw this.resourceError(r.find(ve),`cannot be passed to '${n}'`,a);let l=[];for(let c of r){if(!ve(c)){l.push(c);continue}let d=this.resources.lookup(c);if(!d)throw this.resourceError(c,`cannot be used by '${n}': it belongs to another run`,a);if(e.closesResource)this.resources.borrow(c),await this.resources.close(d);else if(d.state!=="open")throw this.resourceError(c,`is ${d.state==="closing"?"closing":"closed"}: '${n}' cannot use it`,a);this.resources.borrow(c),l.push(d.raw)}return l}registerHostResource(e,n,r,s,i,o){if(e==null)return e;if(typeof e!="object"||typeof e.close!="function"||typeof e.id!="string"&&typeof e.id!="number"||String(e.id)==="")throw new Error("a returnsResource host must return null or an object with a close method and a stable id");return this.resources.register(e,n,`${o??"<main>"}:${s}:${i}`,r)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new De,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear(),this.recovery=Ra(this.resumepoint);for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let n=this.nextTaskId++;this.recovery.rootTaskId=n;let r;try{for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(r=await this.execStmtAsync(s,this.globalEnv,n))}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),ve(r))r=null;else if(ym()){let s=xa(r);if(s)throw new M(ve(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:Aa(s,"run"),1,1,"RUNTIME")}return r}async execStmtAsync(e,n,r){switch(Oe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let s=new De(n);if(!this.resourcesEnabled){for(let o of e.statements)await this.execStmtAsync(o,s,r);return}let i=this.resources.enterScope(s,this.ownerFor(n,r),"block");try{for(let o of e.statements)await this.execStmtAsync(o,s,r)}finally{i.records.length>0&&await this.resources.drain(i)}return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,n,r)),ve(s)&&this.bindResource(s,n,e.name,e),n.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(Array.isArray(s))for(let i=0;i<e.names.length&&i<s.length;i++)this.bindResource(s[i],n,e.names[i],e);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,n,r):e.elseBranch?await this.execStmtAsync(e.elseBranch,n,r):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,n,r));){if(++s>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,n,r):await this.execStmtAsync(e.body,n,r)}catch(i){if(i instanceof ft)break;if(i instanceof gt)continue;throw i}}return}case"ForInStmt":{let s=fm(await this.evalExprAsync(e.iterable,n,r),e),i=0;for(let o of s){if(++i>1e6)throw new M("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new De(n);a.define(e.name,o);let l=this.resourcesEnabled?this.resources.enterScope(a,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let c of e.body.statements)await this.execStmtAsync(c,a,r);else await this.execStmtAsync(e.body,a,r)}finally{l&&l.records.length>0&&await this.resources.drain(l)}}catch(c){if(c instanceof ft)break;if(c instanceof gt)continue;throw c}}return}case"ForStmt":{let s=new De(n),i=this.resourcesEnabled?this.resources.enterScope(s,this.ownerFor(n,r),"for"):void 0;try{e.init&&await this.execStmtAsync(e.init,s,r);let o=0;for(;;){if(e.condition){let a=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(a))break}if(++o>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,s,r):await this.execStmtAsync(e.body,s,r)}catch(a){if(a instanceof ft)break;if(!(a instanceof gt))throw a}e.update&&await this.evalExprAsync(e.update,s,r)}}finally{i&&i.records.length>0&&await this.resources.drain(i)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,n,r):null;throw ve(s)&&this.refuseResource(s,"cannot be returned: a resource stays with its owner (return copied data instead)",e),new Gn(s)}case"BreakStmt":throw new ft;case"ContinueStmt":throw new gt;case"SyncAssignStmt":{let s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0,i=s?{env:s,name:e.target}:n.resolveBinding(e.target);if(!i)throw new M(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let o=`bind:${i.env.id}:${i.name}`;await this.lockManager.getBindingLock(o).withLock(async()=>{let l=await this.evalExprAsync(e.value,n,r);this.bindResource(l,i.env,i.name,e),i.env.define(i.name,l)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new M("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,n,r),a=await this.evalExprAsync(e.value,n,r);this.refuseResource(s,"cannot be modified",e),this.refuseResource(o,"cannot be used as a map key",e),this.refuseResource(a,"cannot be stored in a container",e),Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Je(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new M(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],n,r);if(o==null||typeof o!="object"&&typeof o!="function")throw new M("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":return await this.evalExprAsync(e.expr,n,r);case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new De(n);this.recovery.envs.set(e,i);let o=this.resourcesEnabled?this.resources.enterScope(i,this.ownerFor(n,r),"block"):void 0,a=this.recovery.stack.length;try{for(let l=s.start;l<e.points.length;l++){let c=e.points[l];this.enterPoint(a,c.name);for(let d of c.statements)await this.execStmtAsync(d,i,r);s.consumed&&l===s.start&&this.checkRemainder(c)}}finally{this.leaveRecover(a),o&&o.records.length>0&&await this.resources.drain(o)}return}default:return}}async evalExprAsync(e,n,r){switch(Oe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let s="";for(let i of e.parts){if(typeof i=="string"){s+=i;continue}let o=await this.evalExprAsync(i.expression,n,r);this.refuseResource(o,"cannot be converted to text",i.expression),s+=Ua(o,i)}return s}case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let s=await this.evalExprAsync(e.value,n,r),i=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return ve(s)&&this.bindResource(s,i??n.writeTarget(e.target),e.target,e),i?i.define(e.target,s):n.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,n,r);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null,a=this.recovery.active?this.recoverWriteScope(e.targets[i],e):void 0;ve(o)&&this.bindResource(o,a??n.writeTarget(e.targets[i]),e.targets[i],e),a?a.define(e.targets[i],o):n.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,n,r),i=await this.evalExprAsync(e.index,n,r),o=await this.evalExprAsync(e.value,n,r);if(this.refuseResource(s,"cannot be modified",e),this.refuseResource(i,"cannot be used as a map key",e),this.refuseResource(o,"cannot be stored in a container",e),Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Je(s,i,o),o;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,n,r);case"TupleExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ArrayExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ObjectExpr":{let s={};for(let i of e.properties){let o=await this.evalExprAsync(i.value,n,r);this.refuseResource(o,"cannot be stored in a container",i.value),Je(s,i.key,o)}return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(r)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;this.asyncCallDepth.set(d,s);let u=this.resourcesEnabled?this.resources.temporaryScope(this.ownerFor(n,r),"task",this.resources.scopeFor(n)):void 0;u&&this.pushTemporaryScope(d,u);try{let m=await this.evalExprAsync(c,n,d),p=ym()?xa(m):void 0;if(p)throw new M(ve(p)?`Resource ${this.resources.describe(p)} cannot be a parallel task result: it stays with the task that opened it`:Aa(p,"parallel task"),c.line,c.column,"RUNTIME",c.file);return m}finally{u&&(this.popTemporaryScope(d),u.records.length>0&&await this.resources.drain(u))}}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=ei(e);if(s)return We(await this.resolveIdentifier("PROPS",n,e),s);let i=await this.evalExprAsync(e.target,n,r),o=await this.evalExprAsync(e.index,n,r);if(this.refuseResource(o,"cannot be used as a map key",e),ve(i)){if(o==="id")return i.id;throw this.resourceError(i,`has no readable field '${String(o)}' (only id)`,e)}if(i==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(i)&&typeof o=="number"&&o<0?i[i.length+o]:We(i,o)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,n,r),i=e.operator;if(i==="!")return!this.isTruthy(s);if(this.refuseResource(s,"cannot be used in arithmetic",e),i==="-")return-s;throw new M(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,n,r):await this.evalExprAsync(e.falseArm,n,r)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?await this.evalExprAsync(e.right,n,r):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,n,r)}let s=await this.evalExprAsync(e.left,n,r),i=await this.evalExprAsync(e.right,n,r),o=e.operator;switch((ve(s)||ve(i))&&o!=="=="&&o!=="!="&&(this.refuseResource(s,`cannot be used with '${o}' (only ==, != and truth tests)`,e),this.refuseResource(i,`cannot be used with '${o}' (only ==, != and truth tests)`,e)),o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,n,r));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),await this.invokeCallAsync(e.callee,s,n,e.line,e.column,r,e.file)}}}async invokeCallAsync(e,n,r,s,i,o,a){let l=this.resolveCallTarget(e,r);if(Oe(this.abortSignal),this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Xs)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xs})`,s,i,"RUNTIME",a);let u=new De(this.globalEnv,!0),m=this.resourcesEnabled?this.resources.enterScope(u,this.ownerFor(r,o),`function ${l}`):void 0;for(let p=0;p<c.params.length;p++)m&&this.resources.borrow(n[p]),u.define(c.params[p],n[p]);try{for(let p of c.body.statements)await this.execStmtAsync(p,u,o)}catch(p){if(p instanceof Gn)return p.value;throw p}finally{m&&m.records.length>0&&await this.resources.drain(m),this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l),d=fT(n)?await this.resourceCallArgs(c,l,n,s,i,a):n;try{let u=c.fn(...d),m=u instanceof Promise?await u:u;return c.returnsResource?this.registerHostResource(m,l,this.ownerFor(r,o),s,i,a):m}catch(u){throw u instanceof ht||u?.name==="LMScriptExit"||u?.isControlFlow?u:new M(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(Nr(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},gT=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. Function bodies establish an isolated local variable scope for assignments, preventing accidental mutation of caller variables.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],hT=[{name:"sha256",category:"Math & Utilities",signature:"sha256(text: string): string",description:"Lowercase SHA-256 hex of UTF-8 bytes; rejects non-string inputs.",example:'sha256("abc");'},{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("teams/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), reports through injected diagnostics/captured errors and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests a JavaScript regex against text.",example:'regex_test("abc", "a");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns first [full_match, group1, ...], including with g; missing optional groups become null. Rejects sticky y.",example:'regex_match("a1 b2", "([a-z])([0-9])", "g");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns capture arrays for matches; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_find_all("a1 b2", "([a-z])([0-9])");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:"JavaScript regex replacement with $1 captures; use g for repeated replacement.",example:'regex_replace("a1", "([a-z])([0-9])", "$2$1");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits using JavaScript regex semantics.",example:'split_regex("a b", " +");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width/other precision limit: 10000. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:"join(arr: array, [separator: string]): string",description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"upper_first",category:"Strings",signature:"upper_first(s: string): string",description:"Capitalizes the first character of a string.",example:'c = upper_first("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the UTF-16 code unit at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, ...items: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, ...items: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(first: array, ...more: array): array",description:"Concatenates two or more arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:'Safely parses JSON with markdown fence and preamble tolerance, returning fallback on failure without throwing. Use a custom sentinel (e.g. "PARSE_FAILED") to distinguish parse failure from valid JSON null.',example:'data = json_parse_safe(llm_output, "PARSE_FAILED"); if (data == "PARSE_FAILED") { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 0]): string",description:"Serializes a value to compact JSON by default; optional indent formats the output.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string], [options: map]): string|null; prompt_human(session: map, [options: map]): map",description:"Pauses execution to prompt an operator on terminal stdin or dedicated directory, returning the entered input line or decision map, or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"prompt_human_config",category:"System & Process",signature:"prompt_human_config([config: map|string], [dir: string]): map",description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms). Returns current configuration map.",example:'prompt_human_config({ dir: "/tmp/handoffs", timeout_ms: 60000 });'},{name:"error",category:"System & Process",signature:"error(value: any, ...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats values into an output-log entry rendered as a line by the CLI. Returns the formatted text without adding a newline.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules.",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline.",example:'println("Done.");'},{name:"sleep_ms",category:"System & Process",signature:"sleep_ms(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep_ms(1000);"},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in milliseconds.",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now or a supplied epoch-millisecond value.",example:"created = date(0);"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null (including no arguments).",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"http_get",category:"System & Process",signature:"http_get(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = http_get("https://example.com");'}],_T=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];Kt=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;promptHumanConfig={mode:"interactive"};hostCatalog=new Map;builtinProviders=new Map;hostResolver;constructor(e={}){this.hostResolver=e.resolveHostModule,this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions();for(let[n,r]of[["get_property",{min:1,max:2}],["has_property",1],["get_properties",{min:0,max:1}],["set_property",2]])this.registerFunction(n,()=>{throw Error("Property store is not running")},r,"Read or overlay hierarchical run-local properties; no persistence");this.registerFunction("expand",()=>{throw Error("Template resolver is not running")},{min:1,max:2},"Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque"),this.registerDefaultDocs();for(let[n,r,s]of[["get_property","get_property(key, [default])","Returns a copied property value; absent keys are errors unless a default is supplied."],["has_property","has_property(key)","Tests property presence; missing/invalid profile errors remain loud."],["get_properties","get_properties([prefix])","Returns a detached nested property table copy."],["set_property","set_property(key, value)","Returns the previous value and changes only the run-local overlay; invocation facts are read-only."]])this.functionDocs.set(n,{name:n,signature:r,description:s,module:"core",category:"Properties"});this.functionDocs.set("expand",{name:"expand",signature:"expand(text, [vars])",description:"Resolve ${name} from an explicit vars map, ${PROPS.path}, and ${ARGV[n]}; $${ escapes, no caller-local capture or recursive expansion.",module:"core",category:"Strings"})}registerDefaultDocs(){for(let e of gT)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of hT)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of _T)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){return this.functionDocs.set(e.name,{...e,module:e.module??this.currentRegisteringModule}),this}registerModule(e,n){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let r=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,n)}finally{this.currentRegisteringModule=r}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return Array.from(this.functionDocs.values()).filter(n=>(n.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return Array.from(this.functionDocs.values())}getFunctionDoc(e){return this.functionDocs.get(e)}getFunctionCategories(){let e=new Set;for(let n of this.functionDocs.values())e.add(n.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(n=>n.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>F.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>F.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=F.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
411
411
  `)?n=n.slice(0,-2):n.endsWith(`
412
412
  `)&&(n=n.slice(0,-1)),r?n.length===0?[""]:n.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,n)=>{if(!Array.isArray(n))throw new Error("write_lines: second argument must be an array of lines");let r=n.length===0?"":n.map(String).join(`
413
413
  `)+`
@@ -416,7 +416,7 @@ fn clamp(val, low, high) {
416
416
  `:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d})();{let a=o.run(s,{file:r}),l=a.output.join(`
417
417
  `)+(a.output.length>0?`
418
418
  `:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${n}
419
- `):console.error(`error: ${n}`),n},{min:1},"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("http_get",e=>bm(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep_ms",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");let n=Date.now()+e;for(;Date.now()<n;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human_config",(e,n)=>{if(e===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 e=="string")e==="interactive"?this.promptHumanConfig.mode="interactive":e==="file"?(this.promptHumanConfig.mode="file",n&&(this.promptHumanConfig.dir=String(n))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=e);else if(e&&typeof e=="object"){let r=e.mode?String(e.mode):e.dir?"file":this.promptHumanConfig.mode??"interactive",s=e.dir!==void 0?String(e.dir):this.promptHumanConfig.dir,i=e.timeout_ms!==void 0?Number(e.timeout_ms):e.timeoutMs!==void 0?Number(e.timeoutMs):this.promptHumanConfig.timeoutMs,o=e.poll_ms!==void 0?Number(e.poll_ms):e.pollIntervalMs!==void 0?Number(e.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=r==="file"?"file":"interactive",this.promptHumanConfig.dir=s,this.promptHumanConfig.timeoutMs=typeof i=="number"&&Number.isFinite(i)?i:void 0,this.promptHumanConfig.pollIntervalMs=typeof o=="number"&&Number.isFinite(o)&&o>0?o:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},{min:0,max:2},"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",!0),this.registerFunction("prompt_human",(e,n)=>{if((n?.mode??(n?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let s=n?.dir??this.promptHumanConfig.dir;if(!s)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsyncMode)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return xm(e,{dir:s,sessionId:n?.sessionId??n?.sessionid??n?.id,timeoutMs:n?.timeout_ms??n?.timeoutMs??this.promptHumanConfig.timeoutMs,pollIntervalMs:n?.poll_ms??n?.pollIntervalMs??this.promptHumanConfig.pollIntervalMs})}return this.isAsyncMode?ri(e):Im(e)},{min:0,max:2},"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",!0),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(n){throw new Error(`JSON parse error: ${n.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,n=null)=>eT(e,n),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,n)=>JSON.stringify(e,null,n),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(Ar(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(Ar(e)):[],1,"Returns array of [key, value] pairs"),this.registerFunction("has_key",(e,n)=>e&&typeof e=="object"?Object.hasOwn(e,n):!1,2,"Checks if object has key"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(Ar(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=xr(e,n);return s!==void 0?s:r},{min:2,max:3},"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,n,r="")=>{let s=xr(e,n);return s==null?r:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,n,r=0)=>{let s=xr(e,n);return s==null?r:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,n,r=!1)=>{let s=xr(e,n);if(s==null)return r;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,n,r=[])=>{let s=xr(e,n);return Array.isArray(s)?s:r},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",Tm,2,"Requires a present value; injected diagnostic/captured error and exit 2 on missing",!0),this.registerFunction("set",(e,n,r)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(n)?n:String(n).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(We(i,a)==null||typeof We(i,a)!="object")&&Je(i,a,{}),i=We(i,a)}return s.length>0&&Je(i,s[s.length-1],r),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,n)=>Array.isArray(e)?e.map(r=>We(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&We(s,n)===r):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,n,r)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&We(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...Ar(e),...Ar(n)}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,n)=>(e&&typeof e=="object"&&delete e[n],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints line to output log",!0),this.registerFunction("split",(e,n)=>String(e).split(n),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let n=e.split(/\r?\n/);for(let r=n.length-1;r>=0;r--){let s=n[r].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,n=", ")=>Array.isArray(e)?e.join(n):String(e),{min:1,max:2},"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("upper_first",e=>{let n=String(e);return n.length===0?"":n.charAt(0).toUpperCase()+n.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,n=>n.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,n)=>Array.isArray(e)?e.includes(n):String(e).includes(String(n)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,n)=>Array.isArray(e)?e.includes(n):String(e).includes(String(n)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,n)=>String(e).startsWith(n),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,n)=>String(e).startsWith(n),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,n)=>String(e).endsWith(n),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,n)=>String(e).endsWith(n),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,n,r)=>Array.isArray(e)?e.indexOf(n,r):String(e).indexOf(n,r),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent"),this.registerFunction("last_index_of",(e,n)=>Array.isArray(e)?e.lastIndexOf(n):String(e).lastIndexOf(n),2,"Finds last substring or strictly equal array element index; -1 if absent"),this.registerFunction("count_matches",(e,n)=>n?String(e).split(n).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,n,r)=>{let s=String(e),i=Math.trunc(Number(n))||0,o=i<0?Math.max(0,s.length+i):Math.min(s.length,i);if(r===void 0)return s.slice(o);let a=Math.max(0,Math.trunc(Number(r))||0);return s.slice(o,o+a)},{min:2,max:3},"Returns substring by end-relative start and optional length"),this.registerFunction("substring",(e,n,r)=>String(e).substring(n,r),{min:2,max:3},"Returns substring between indices"),this.registerFunction("slice",(e,n,r)=>e!=null?e.slice(n,r):"",{min:2,max:3},"Slices string or array"),this.registerFunction("char_at",(e,n)=>String(e).charAt(n),2,"Returns character at index"),this.registerFunction("char_code",(e,n=0)=>String(e).charCodeAt(n),{min:1,max:2},"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),{min:0},"Returns string from character codes"),this.registerFunction("replace",(e,n,r)=>String(e).replace(n,r),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,n,r)=>String(e).replaceAll(n,r),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,n)=>String(e).repeat(n),2,"Repeats string count times"),this.registerFunction("pad_start",(e,n,r=" ")=>String(e).padStart(n,r),{min:2,max:3},"Left-pads string"),this.registerFunction("pad_end",(e,n,r=" ")=>String(e).padEnd(n,r),{min:2,max:3},"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof En,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>Sm(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("sprintf",(e,...n)=>Ga(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>Ga(e,n,"printf"),{min:1},"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules",!0),this.registerFunction("format",(e,...n)=>{let r=String(e),s=n.length===1&&typeof n[0]=="object"&&n[0]!==null&&!Array.isArray(n[0])?n[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<r.length;){let c=r[l];if(c==="{"&&r[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&r[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=r.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=r.slice(l+1,d);if(u==="")o+=i<n.length?a(n[i++]):"{}";else if(/^\d+$/.test(u)){let m=Number(u);o+=m<n.length?a(n[m]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("regex_test",(e,n,r="")=>Cr(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",tT,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",nT,{min:2,max:3},"Returns capture arrays with Unicode-aware zero-width progress; y is rejected"),this.registerFunction("regex_replace",(e,n,r,s="")=>String(e).replace(Cr(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(Cr(n,r)),{min:2,max:3},"Splits text at regular expression matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("range",(e,n,r=1)=>{let s=n===void 0?0:e,i=n===void 0?e:n,o=[];if(r>0)for(let a=s;a<i;a+=r)o.push(a);else if(r<0)for(let a=s;a>i;a+=r)o.push(a);return o},{min:1,max:3},"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...n)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...n)},{min:0},"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,n)=>Math.pow(e,n),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("sha256",e=>{if(typeof e!="string")throw new Error("sha256: expected a string");return zw("sha256").update(e,"utf8").digest("hex")},1,"Returns lowercase SHA-256 of UTF-8 text; strings only"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,n)=>yT(e,n),2,"Formats local time: epoch milliseconds first, format string second"),this.registerFunction("coalesce",(...e)=>{for(let n of e)if(n!=null)return n;return null},{min:0},"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,n)=>e??n,2,"Returns fallback if value is null/undefined, else value"),this.registerFunction("if_else",(e,n,r)=>e?n:r,3,"Eager compatibility helper: arguments evaluate eagerly; use condition ? thenValue : elseValue for lazy selection"),this.registerFunction("str",e=>Ia(e),1,"Converts lists and maps to compact JSON; scalars to normal text"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof En?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,n="Assertion failed")=>{if(!e)throw new Error(n);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,n,r,s,i=!1,o=!1){if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is reserved; rename this function");let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==m&&!u)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${p}'`);this.functionOriginModule.set(e,m);let f=typeof s=="object"?{returnsResource:s.returnsResource===!0||void 0,usesResource:s.usesResource===!0||void 0,closesResource:s.closesResource===!0||void 0}:{};if(this.hostFunctions.set(e,{fn:n,arity:r,description:a,isDefault:l,isContainerMutation:c,doc:d,params:typeof s=="object"?s.params:void 0,...f}),d)this.functionDocs.set(e,{...d,module:d.module??m});else if(!this.functionDocs.has(e)){let _=typeof r=="number"?r:r?.min??0,y=typeof r=="number"?r:r?.max,h=Array.from({length:y??_},(v,g)=>(g>=_?"[":"")+"arg"+(g+1)+(g>=_?"]":""));y===void 0&&h.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+h.join(", ")+")",description:a??"Host function "+e})}return this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,n){if(e==="PROPS")throw Error("PROPS is a reserved read-only map binding");if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is a reserved read-only binding: the running resumepoint path or null");return this.initialGlobals.set(e,n),this}getGlobal(e){return this.initialGlobals.get(e)}registerHostModule(e){return this.hostCatalog.set(e.name,e),this}getHostModule(e){return this.hostCatalog.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}async scanAndCheckAsync(e,n={}){try{let r=n.compiledSource??await uT(e,{...n,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??[]]});return{...this.scanAndCheck(e,{...n,compiledSource:r}),compiledSource:r}}catch(r){let s=r;return{ast:null,hasConcurrency:!1,diagnostics:[{severity:"error",message:s.message,line:s.line??1,column:s.column??1,file:s.file??n.file}]}}}scanAndCheck(e,n={}){try{let{program:r,diagnostics:s,hostImports:i,packages:o}=n.compiledSource??cT(e,{...n,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??[]]}),a=new Map(this.hostFunctions),l=[],c=new Map,d=new Map,u=new Set,m=[],p={known:[],closedTables:[],removedGlobals:{}};for(let v of[...[...this.builtinProviders.keys(),...this.hostCatalog.keys()].map(g=>({name:g,line:1,column:1,file:n.file})),...i]){if(l.some(T=>T.name===v.name))continue;let g;try{g=this.builtinProviders.get(v.name)??this.hostCatalog.get(v.name)??(n.resolveHostModule??this.hostResolver)?.(v.name)}catch(T){let I=aT(T);throw new M(`Cannot load module '${v.name}': ${I}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!g)throw new M(`Missing host module '${v.name}'. Install with npm install ${v.name} or set LMSCRIPT_MODULES; for a file use './${v.name}.lms'.`,v.line,v.column,"CHECKER",v.file);let E;try{let T=g.declarations,I=T?.functions,x=T?.globals;Array.isArray(I)&&Array.isArray(x)&&(E={functions:I.map(L=>({...L})),globals:x.map(L=>({...L})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(g.name!==v.name||!E||typeof g.activate!="function")throw new M(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let T of E.functions){let I=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Vs,T.name)||T.name==="RESUMEPOINT"||!I||!Number.isSafeInteger(I.min)||I.min<0||I.max!==void 0&&(!Number.isSafeInteger(I.max)||I.max<I.min))throw new M(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let x=d.get(T.name);if(T.override===!0&&a.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new M(`Module '${v.name}' cannot override ${x===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${x}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(a.has(T.name)&&!(T.override===!0&&a.get(T.name)?.isDefault))throw new M(`Module function collision: '${T.name}' in module '${v.name}'${x===void 0?"":` is already declared by module '${x}'`}`,v.line,v.column,"CHECKER",v.file);a.set(T.name,{arity:T.arity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:T.params,returnsResource:T.returnsResource===!0||void 0}),d.set(T.name,v.name)}for(let T of E.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Vs,T.name)||u.has(T.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(T.name)||this.initialGlobals.has(T.name)||n.globals?.includes(T.name))throw new M(`Module global collision or invalid name: '${T.name}'`,v.line,v.column,"CHECKER",v.file);u.add(T.name),this.builtinProviders.has(v.name)&&m.push(T.name)}E.properties&&(p.known=[...p.known,...E.properties.known],p.closedTables=[...p.closedTables??[],...E.properties.closedTables??[]],p.removedGlobals={...p.removedGlobals,...E.properties.removedGlobals}),l.push(g),c.set(g,E)}let f=[...this.initialGlobals.keys(),...n.globals||[],...u,"PROPS","Directory","NonInteractive","RESUMEPOINT"],_=new $a(a,{...n,globals:f,builtinGlobals:m,propertyDeclarations:p,sourcePackages:o}),y=[...s,..._.check(r)];for(let v of y)if(v.message.startsWith("Call to undefined function"))for(let g of this.hostCatalog.values())for(let E of g.declarations.functions)v.message.includes(`'${E.name}'`)&&(v.message+=`; provided by module '${g.name}': add import "${g.name}";`);let h={ast:r,diagnostics:y,hasConcurrency:_.hasConcurrency,hostModules:l,hostDeclarations:c,usedGlobals:[..._.usedGlobals],usedProperties:_.usedProperties,recoverLabels:[..._.recoverLabels],hasRecover:_.hasRecover,recoverScopedReads:_.recoverScopedReads,recoverScopedWrites:_.recoverScopedWrites};return hm(h,n)}catch(r){return r instanceof M?{ast:null,diagnostics:[{message:r.message,line:r.line,column:r.column,severity:"error",file:r.file||n.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:r instanceof Error?r.message:String(r),line:1,column:1,severity:"error",file:n.file}],hasConcurrency:!1}}}installBuiltinStubs(e,n,r,s,i){let o=n.hostDeclarations.get(e);for(let a of o.globals)r.globals.set(a.name,new Wa(()=>i(a.name)));for(let a of o.functions)r.functions.set(a.name,{fn:s(a.name),arity:a.arity,doc:a.doc,params:a.params,..._m(a)})}activationContext(e,n,r){return{cwd:n.hostContext?.cwd??process.cwd(),env:Object.freeze({...n.hostContext?.env??process.env}),signal:n.signal,propertyStore:n.propertyStore,usedGlobals:(e.usedGlobals??[]).filter(s=>(e.hostDeclarations?.get(r)??r.declarations).globals.some(i=>i.name===s))}}bindModule(e,n,r,s){if(!n||typeof n.dispose!="function")throw new Error(`Module '${e.name}' did not return a disposable`);let i=r.hostDeclarations?.get(e)??e.declarations;if(i.properties){if(!n.loadProperties)throw Error(`Provider '${e.name}' did not supply properties`);s.properties?.addSource(e.name,()=>n.loadProperties(),i.properties.known)}for(let o of i.functions){if(typeof n.functions?.[o.name]!="function")throw new Error(`Module '${e.name}' did not bind '${o.name}'`);s.functions.set(o.name,{fn:n.functions[o.name],arity:o.arity,doc:o.doc,params:o.params,..._m(o)})}for(let o of i.globals)if(Object.hasOwn(n.globals??{},o.name))s.globals.set(o.name,n.globals[o.name]);else if(r.usedGlobals?.includes(o.name))throw new Error(`Module '${e.name}' did not provide global '${o.name}'`)}moduleFailure(e,n,r){return{success:!1,output:[],diagnostics:[...n.diagnostics,{severity:"error",message:e instanceof Error?e.message:String(e),line:1,column:1,file:r.file}]}}collectModuleErrors(e,n){for(let r of e)if(r.getRecordedErrors!==void 0)try{let s=r.getRecordedErrors();if(!Array.isArray(s))throw new Error("getRecordedErrors must return an array");n.errors=[...n.errors??[],...s.map(i=>typeof i=="string"?i:JSON.stringify(i)??String(i))]}catch(s){n.diagnostics.push({severity:"warning",message:`Host module error collection failed: ${s instanceof Error?s.message:String(s)}`,line:1,column:1})}}cleanupWarning(e,n){n.diagnostics.push({severity:"warning",message:`Host module cleanup failed: ${e instanceof Error?e.message:String(e)}`,line:1,column:1})}run(e,n={}){this.outputLogs=[],this.lastRecordedErrors=[];let r=this.scanAndCheck(e,n);n={...n,propertyStore:n.propertyStore??new Zs(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let s=n.propertyStore,i={functions:new Map(this.hostFunctions),globals:new Map(this.initialGlobals),properties:s};i.globals.set("PROPS",s.view()),i.globals.set("Directory",s.get("Directory")),i.globals.set("NonInteractive",s.get("NonInteractive")),i.globals.set("RESUMEPOINT",null);let a={expand:(d,u={})=>{if(!u||typeof u!="object"||Array.isArray(u)||![Object.prototype,null].includes(Object.getPrototypeOf(u)))throw Error("expand: vars must be a map");let m=i.globals.get("ARGV")??[];return Ws(d,p=>p.kind==="property"?s.get(p.key):p.kind==="argument"?Array.isArray(m)&&Object.hasOwn(m,p.index)?m[p.index]:void 0:Object.hasOwn(u,p.name)?We(u,p.name):void 0,Ia)},get_property:(d,...u)=>s.get(d,...u),has_property:d=>s.has(d),get_properties:d=>s.copy(d),set_property:(d,u)=>s.set(d,u)};for(let[d,u]of Object.entries(a))i.functions.set(d,{...i.functions.get(d),fn:u});if(!r.ast||r.diagnostics.some(d=>d.severity==="error")||r.hasConcurrency)return this.executeSync(e,n,r,i);let l=[],c;try{Oe(n.signal);for(let d of r.hostModules??[]){if(this.builtinProviders.has(d.name)){let m,p=()=>{if(m)return m;Oe(n.signal);let f=d.activate(this.activationContext(r,n,d));if(Jn(f))throw f.then(_=>_.dispose()).catch(()=>{}),new Error(`Module '${d.name}' requires runAsync for activation`);if(!f||typeof f.dispose!="function")throw new Error(`Module '${d.name}' did not return a disposable`);return m=f,l.push(m),this.bindModule(d,m,r,i),m};this.installBuiltinStubs(d,r,i,f=>(..._)=>p().functions[f](..._),f=>(p(),i.globals.get(f))),r.usedProperties&&r.hostDeclarations?.get(d)?.properties&&p();continue}let u=d.activate(this.activationContext(r,n,d));if(Jn(u))throw u.then(m=>m.dispose()).catch(()=>{}),new Error(`Module '${d.name}' requires runAsync for activation`);l.push(u),this.bindModule(d,u,r,i),Oe(n.signal)}c=this.executeSync(e,n,r,i),n.signal?.aborted&&(c={...c,success:!1,diagnostics:c.diagnostics.some(d=>d.severity==="error"&&d.message==="Execution aborted")?c.diagnostics:[...c.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(d){c=this.moduleFailure(d,r,n)}this.collectModuleErrors(l,c);for(let d of l.reverse())try{let u=d.dispose();if(Jn(u))throw u.catch(()=>{}),new Error("Async disposal requires runAsync")}catch(u){this.cleanupWarning(u,c)}return c}async runAsync(e,n={}){n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?hm(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;n={...n,propertyStore:n.propertyStore??new Zs(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let i=n.propertyStore,o={functions:new Map(this.hostFunctions),globals:new Map(this.initialGlobals),properties:i};o.globals.set("PROPS",i.view()),o.globals.set("Directory",i.get("Directory")),o.globals.set("NonInteractive",i.get("NonInteractive")),o.globals.set("RESUMEPOINT",null);let l={expand:(u,m={})=>{if(!m||typeof m!="object"||Array.isArray(m)||![Object.prototype,null].includes(Object.getPrototypeOf(m)))throw Error("expand: vars must be a map");let p=o.globals.get("ARGV")??[];return Ws(u,f=>f.kind==="property"?i.get(f.key):f.kind==="argument"?Array.isArray(p)&&Object.hasOwn(p,f.index)?p[f.index]:void 0:Object.hasOwn(m,f.name)?We(m,f.name):void 0,Ia)},get_property:(u,...m)=>i.get(u,...m),has_property:u=>i.has(u),get_properties:u=>i.copy(u),set_property:(u,m)=>i.set(u,m)};for(let[u,m]of Object.entries(l))o.functions.set(u,{...o.functions.get(u),fn:m});if(!s.ast||s.diagnostics.some(u=>u.severity==="error"))return this.executeAsync(e,n,s,o);let c=[],d;try{Oe(n.signal);for(let u of s.hostModules??[]){if(this.builtinProviders.has(u.name)){let p,f=()=>p??=Promise.resolve().then(async()=>{Oe(n.signal);let _=await u.activate(this.activationContext(s,n,u));if(!_||typeof _.dispose!="function")throw new Error(`Module '${u.name}' did not return a disposable`);return c.push(_),this.bindModule(u,_,s,o),Oe(n.signal),_});this.installBuiltinStubs(u,s,o,_=>async(...y)=>(await f()).functions[_](...y),async _=>(await f(),o.globals.get(_))),s.usedProperties&&s.hostDeclarations?.get(u)?.properties&&await f();continue}let m=await u.activate(this.activationContext(s,n,u));c.push(m),this.bindModule(u,m,s,o),Oe(n.signal)}d=await this.executeAsync(e,n,s,o),n.signal?.aborted&&(d={...d,success:!1,diagnostics:d.diagnostics.some(u=>u.severity==="error"&&u.message==="Execution aborted")?d.diagnostics:[...d.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(u){d=this.moduleFailure(u,s,n)}this.collectModuleErrors(c,d);for(let u of c.reverse())try{await u.dispose()}catch(m){this.cleanupWarning(m,d)}return d}executeSync(e,n,r,s){let i=[],{ast:o,diagnostics:a,hasConcurrency:l}=r;if(a.filter(m=>m.severity==="error").length>0||!o)return this.outputLogs=i,{success:!1,diagnostics:a,output:i};if(l)return this.outputLogs=i,{success:!1,diagnostics:[...a,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:n.file}],output:i};let d,u;try{d=new ni(s.functions,f=>{i.push(f),n.stdout?.(f)},!1,s.globals,n.stderr,this.promptHumanConfig),d.abortSignal=n.signal,d.resumepoint=n.resumepoint,d.recoverScopedReads=r.recoverScopedReads??new WeakMap,d.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,u=this.trackResourceRun(d.resources);let m=d.evaluateProgram(o);this.outputLogs=[...i];let p=d.getRecordedErrors();return this.lastRecordedErrors=p,{success:!0,value:m,diagnostics:a,output:i,errors:p,resourceRun:u}}catch(m){let p=d?d.getRecordedErrors():[];if(this.lastRecordedErrors=p,m instanceof ht||m?.name==="LMScriptExit"||m?.isControlFlow){this.outputLogs=[...i];let h=typeof m.exitCode=="number"?m.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:a,output:i,errors:p,resourceRun:u}}let f=m instanceof M?m.line:1,_=m instanceof M?m.column:1,y=m instanceof M&&m.file||n.file;return this.outputLogs=[...i],{success:!1,diagnostics:[...a,{message:m?.message||String(m),line:f,column:_,severity:"error",file:y}],output:i,errors:p,resourceRun:u}}}async executeAsync(e,n,r,s){let i=[],{ast:o,diagnostics:a}=r;if(a.filter(u=>u.severity==="error").length>0||!o)return this.outputLogs=i,this.lastRecordedErrors=[],{success:!1,diagnostics:a,output:i,errors:[]};let c,d;try{c=new ni(s.functions,p=>{i.push(p),n.stdout?.(p)},!0,s.globals,n.stderr,this.promptHumanConfig),c.abortSignal=n.signal,c.resumepoint=n.resumepoint,c.recoverScopedReads=r.recoverScopedReads??new WeakMap,c.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,d=this.trackResourceRun(c.resources);let u=await c.evaluateProgramAsync(o);this.outputLogs=[...i];let m=c.getRecordedErrors();return this.lastRecordedErrors=m,{success:!0,value:u,diagnostics:a,output:i,errors:m,resourceRun:d}}catch(u){let m=c?c.getRecordedErrors():[];if(this.lastRecordedErrors=m,u instanceof ht||u?.name==="LMScriptExit"||u?.isControlFlow){this.outputLogs=[...i];let y=typeof u.exitCode=="number"?u.exitCode:0;return{success:y===0,value:y,exitCode:y,diagnostics:a,output:i,errors:m,resourceRun:d}}let p=u instanceof M?u.line:1,f=u instanceof M?u.column:1,_=u instanceof M&&u.file||n.file;return this.outputLogs=[...i],{success:!1,diagnostics:[...a,{message:u?.message||String(u),line:p,column:f,severity:"error",file:_}],output:i,errors:m,resourceRun:d}}}lastRecordedErrors=[];resourceRuns=new Map;trackResourceRun(e){for(this.resourceRuns.set(e.token,e);this.resourceRuns.size>64;)this.resourceRuns.delete(this.resourceRuns.keys().next().value);return e.token}inspectResources(e){return this.resourceRuns.get(e)?.snapshot()??[]}getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getFunctionMetadata(e){let n=this.hostFunctions.get(e);return n?{arity:n.arity,description:n.description}:void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};Ca=le.basename(Ja(import.meta.url));(Ca==="lmscript.ts"||Ca==="lmscript.js"||Ca==="lmscript")&&process.argv[1]&&F.existsSync(process.argv[1])&&F.realpathSync(Ja(import.meta.url))===F.realpathSync(le.resolve(process.argv[1]))&&vT()});var $M,Vt,wT,TT,bT,Qa,Za,el,fe,za,_t,si,Mr,ii,oi,Ya,$m,Um,Hm,Pr,Bm,Ke,zt=N(()=>{"use strict";$M=1,Vt=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Vt(e);Object.freeze(t)}return t},wT=Vt(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal"]),TT=Vt({status:"string",error:"string|null",code:"ErrorCode?"}),bT=Vt(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),Qa=Vt(["Provider1.Provider","Provider1.Model1","Provider1.Model2","Provider1.Model3","Provider2.Provider","Provider2.Model1","Provider2.Model2","Provider2.Model3","Provider3.Provider","Provider3.Model1","Provider3.Model2","Provider3.Model3"]),Za=Vt(["Provider1","Provider2","Provider3"]),el=Vt({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),fe={name:"ctx",type:"context"},za={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},_t={name:"teamfile",type:"string"},si={name:"alias",type:"string"},Mr={name:"prompt",type:"string"},ii={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"alias",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"},{name:"sessiondir",type:"string"},{name:"sessionid",type:"string"}]},oi=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],Ya={name:"options",type:"map",optional:!0,keys:oi},$m={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},Um={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},Hm={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Pr={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},Bm={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},Ke=Vt([{name:"resolveProfilePath",implemented:!0,params:[fe,za],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[fe,za],statuses:["ok","error"],results:{error:"string|null",profile:"{path,raw,config}",values:"{Provider1..3,Model1..3,Directory,NonInteractive}",path:"string?",line:"number?",column:"number?"},effects:["file-read"],summary:"Read and validate the complete init profile without discovery or writes."},{name:"profileValues",implemented:!0,params:[{name:"config",type:"map"}],statuses:["ok","error"],results:{error:"string|null",Provider1:"string",Provider2:"string",Provider3:"string",Model1:"string",Model2:"string",Model3:"string"},effects:[],summary:"Validate and map slots to first-model environment values."},{name:"readPrompts",implemented:!0,params:[fe,{name:"path",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"single",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",prompts:"string[]"},effects:["file-read"],summary:"Read prompt records without exiting the caller.",scriptBinding:{name:"lm_read_prompts",params:[{name:"batchfile",type:"string"},{name:"single",type:"boolean",optional:!0}]}},{name:"listMembers",implemented:!0,params:[fe,_t],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[_t]}},{name:"resolveMember",implemented:!0,params:[fe,_t,si],statuses:["ok","not_found","error"],results:{error:"string|null",member:"Member",isLead:"boolean",teamfile:"string"},effects:["file-read","db"],summary:"Resolve a team member with an explicit missing outcome.",scriptBinding:{name:"lm_member",params:[_t,si]}},{name:"lintTeam",implemented:!0,params:[fe,_t],statuses:["ok","error"],results:{error:"string|null",errors:"list",warnings:"list",counts:"map"},effects:["file-read","db"],summary:"Return structured lint findings.",scriptBinding:{name:"lm_lint",params:[_t]}},{name:"seedTeam",implemented:!0,params:[fe,_t,$m],statuses:["ok","error"],results:{error:"string|null",seeded:"SeededMember[]"},effects:["provider","db","file-write"],summary:"Seed a team with explicit optional preambles.",scriptBinding:{name:"lm_seed",params:[_t,$m]}},{name:"promptAgent",implemented:!0,params:[fe,ii,Mr,Ya],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...Bm,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[ii,Mr,Ya]}},{name:"promptMember",implemented:!0,params:[fe,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"prompt",type:"string",required:!0},{name:"messageType",type:"string"},...oi]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[_t,si,Mr,{name:"options",type:"map",optional:!0,keys:[...oi,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[fe,{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"workspace",type:"string"},{name:"all",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",sessions:"Session[]"},effects:["file-read"],summary:"List native sessions in an explicit workspace.",scriptBinding:{name:"lm_session_list",params:[{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"sessiondir",type:"string"},{name:"all",type:"boolean"}]}]}},{name:"deleteSession",implemented:!0,params:[fe,Pr,Hm],statuses:["deleted","not_found","busy","error"],results:{error:"string|null"},effects:["provider","file-write"],summary:"Delete a session only with explicit force admission.",scriptBinding:{name:"lm_session_delete",params:[ii,{...Hm,optional:!0}]}},{name:"getSession",implemented:!0,params:[fe,Pr],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages."},{name:"reserveSession",implemented:!0,params:[fe,Pr],statuses:["ok","busy","error"],results:{error:"string|null",reservation:"SessionReservation"},effects:[],summary:"Reserve context-local handoff admission and return a capability."},{name:"releaseSession",implemented:!0,params:[fe,Pr],statuses:["ok","error"],results:{error:"string|null"},effects:[],summary:"Release context-local handoff admission."},{name:"openTeamBatch",implemented:!0,params:[fe,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"promptCount",type:"number",required:!0},{name:"legacy",type:"boolean"},...oi]}],statuses:["ok","busy","error"],results:{error:"string|null",batch:"opaque context-bound BatchRef"},effects:["provider","db"],summary:"Open a managed team batch; member-map composition remains language-owned."},{name:"batchTurn",implemented:!0,params:[fe,{name:"batch",type:"BatchRef"},Mr,{name:"index",type:"number"},{name:"total",type:"number"}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn an owned live batch reference."},{name:"closeBatch",implemented:!0,params:[fe,{name:"batch",type:"BatchRef"},{name:"options",type:"map",keys:[{name:"status",type:"string",required:!0,values:["done","error","cancelled"]},{name:"error",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close an owned batch."},{name:"readRatelimits",implemented:!0,params:[fe,Um],statuses:["ok","error"],results:{error:"string|null",readings:"list"},effects:["file-read","network"],summary:"Read provider rate-limit data.",scriptBinding:{name:"lm_ratelimit_readings",params:[Um]}},{name:"openTerminal",implemented:!0,params:[fe,{name:"target",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0}]},{name:"streams",type:"map",keys:[{name:"stdin",type:"stream",required:!0},{name:"stdout",type:"stream",required:!0},{name:"stderr",type:"stream",required:!0}]}],statuses:["ok","error"],results:{error:"string|null",code:"number|null",signal:"string|null"},effects:["provider","db","tty"],summary:"Open a native terminal with caller-supplied streams.",scriptBinding:{name:"lm_terminal",params:[_t,si]}},{name:"sessionAdmission",implemented:!0,params:[fe,Pr],statuses:["ok","busy","error"],results:{error:"string|null",busyReason:"turn|handoff?"},effects:[],summary:"Query context-local session admission without exposing mutable sets."},{name:"promptReservedAgent",implemented:!0,params:[fe,{name:"reservation",type:"SessionReservation"},ii,Mr,Ya],statuses:["ok","busy","stalled","empty","error"],results:{...Bm,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"inspectBatch",implemented:!0,params:[fe,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null",id:"string",closed:"boolean",member:"Member",rootId:"number|null"},effects:[],summary:"Read batch metadata without exposing native transports or lease capabilities."},{name:"loadProperties",implemented:!0,params:[fe,za],statuses:["ok","error"],results:{error:"string|null",path:"string",properties:"map",flat:"map",line:"number?",column:"number?"},effects:["file-read"],summary:"Read the complete hierarchical init.toml properties document through the canonical reader."}])});var Wm,Xm=N(()=>{"use strict";Wm=[{name:"prompt_human",category:"lmctl Automation",signature:"prompt_human([question|session])",description:"Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. Core prompt options apply only without this binding."},{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"map",description:"Batch handle object or null on error"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index, total)",description:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns the reply.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:"{ status, code } after the TUI exits"},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}]});function G(t){try{if(t instanceof Error){let e=t.message;if(typeof e=="string")return e}return String(t)}catch{return"Unprintable error"}}function ce(t){return{...t,status:"ok",error:null}}function j(t,e,n){return{...n,status:"error",code:t,error:e}}var Ve=N(()=>{"use strict"});function vn(t){return t.some(e=>e!=null&&(typeof e!="number"||!Number.isSafeInteger(e)||e<0))}var ai=N(()=>{"use strict"});var li,qm,tl=N(()=>{"use strict";li={attempt_key:"TEXT",provider:"TEXT",native_session_id:"TEXT",cwd:"TEXT",ended_at:"TEXT",turn_outcome:"TEXT",model_requested:"TEXT",model_reported:"TEXT",tok_input_uncached:"INTEGER",tok_cache_read:"INTEGER",tok_cache_write:"INTEGER",tok_output:"INTEGER",tok_reasoning:"INTEGER",usage_source:"TEXT CHECK(usage_source IN ('wire','native','cumulative_delta'))",usage_reason:"TEXT",price_record_id:"TEXT",price_snapshot_sha256:"TEXT",rate_input_1m:"REAL",rate_output_1m:"REAL",rate_cache_read_1m:"REAL",rate_cache_write_1m:"REAL",cost_reason:"TEXT",provider_cost_usd:"REAL"},qm=`CREATE UNIQUE INDEX IF NOT EXISTS idx_team_chat_attempt_unique ON team_chat_log(attempt_key) WHERE attempt_key IS NOT NULL;
419
+ `):console.error(`error: ${n}`),n},{min:1},"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("http_get",e=>bm(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep_ms",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");let n=Date.now()+e;for(;Date.now()<n;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human_config",(e,n)=>{if(e===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 e=="string")e==="interactive"?this.promptHumanConfig.mode="interactive":e==="file"?(this.promptHumanConfig.mode="file",n&&(this.promptHumanConfig.dir=String(n))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=e);else if(e&&typeof e=="object"){let r=e.mode?String(e.mode):e.dir?"file":this.promptHumanConfig.mode??"interactive",s=e.dir!==void 0?String(e.dir):this.promptHumanConfig.dir,i=e.timeout_ms!==void 0?Number(e.timeout_ms):e.timeoutMs!==void 0?Number(e.timeoutMs):this.promptHumanConfig.timeoutMs,o=e.poll_ms!==void 0?Number(e.poll_ms):e.pollIntervalMs!==void 0?Number(e.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=r==="file"?"file":"interactive",this.promptHumanConfig.dir=s,this.promptHumanConfig.timeoutMs=typeof i=="number"&&Number.isFinite(i)?i:void 0,this.promptHumanConfig.pollIntervalMs=typeof o=="number"&&Number.isFinite(o)&&o>0?o:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},{min:0,max:2},"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",!0),this.registerFunction("prompt_human",(e,n)=>{if((n?.mode??(n?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let s=n?.dir??this.promptHumanConfig.dir;if(!s)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsyncMode)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return xm(e,{dir:s,sessionId:n?.sessionId??n?.sessionid??n?.id,timeoutMs:n?.timeout_ms??n?.timeoutMs??this.promptHumanConfig.timeoutMs,pollIntervalMs:n?.poll_ms??n?.pollIntervalMs??this.promptHumanConfig.pollIntervalMs})}return this.isAsyncMode?ri(e):Im(e)},{min:0,max:2},"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",!0),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(n){throw new Error(`JSON parse error: ${n.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,n=null)=>eT(e,n),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,n)=>JSON.stringify(e,null,n),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(Ar(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(Ar(e)):[],1,"Returns array of [key, value] pairs"),this.registerFunction("has_key",(e,n)=>e&&typeof e=="object"?Object.hasOwn(e,n):!1,2,"Checks if object has key"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(Ar(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=xr(e,n);return s!==void 0?s:r},{min:2,max:3},"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,n,r="")=>{let s=xr(e,n);return s==null?r:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,n,r=0)=>{let s=xr(e,n);return s==null?r:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,n,r=!1)=>{let s=xr(e,n);if(s==null)return r;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,n,r=[])=>{let s=xr(e,n);return Array.isArray(s)?s:r},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",Tm,2,"Requires a present value; injected diagnostic/captured error and exit 2 on missing",!0),this.registerFunction("set",(e,n,r)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(n)?n:String(n).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(We(i,a)==null||typeof We(i,a)!="object")&&Je(i,a,{}),i=We(i,a)}return s.length>0&&Je(i,s[s.length-1],r),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,n)=>Array.isArray(e)?e.map(r=>We(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&We(s,n)===r):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,n,r)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&We(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...Ar(e),...Ar(n)}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,n)=>(e&&typeof e=="object"&&delete e[n],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints line to output log",!0),this.registerFunction("split",(e,n)=>String(e).split(n),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let n=e.split(/\r?\n/);for(let r=n.length-1;r>=0;r--){let s=n[r].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,n=", ")=>Array.isArray(e)?e.join(n):String(e),{min:1,max:2},"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("upper_first",e=>{let n=String(e);return n.length===0?"":n.charAt(0).toUpperCase()+n.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,n=>n.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,n)=>Array.isArray(e)?e.includes(n):String(e).includes(String(n)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,n)=>Array.isArray(e)?e.includes(n):String(e).includes(String(n)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,n)=>String(e).startsWith(n),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,n)=>String(e).startsWith(n),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,n)=>String(e).endsWith(n),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,n)=>String(e).endsWith(n),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,n,r)=>Array.isArray(e)?e.indexOf(n,r):String(e).indexOf(n,r),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent"),this.registerFunction("last_index_of",(e,n)=>Array.isArray(e)?e.lastIndexOf(n):String(e).lastIndexOf(n),2,"Finds last substring or strictly equal array element index; -1 if absent"),this.registerFunction("count_matches",(e,n)=>n?String(e).split(n).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,n,r)=>{let s=String(e),i=Math.trunc(Number(n))||0,o=i<0?Math.max(0,s.length+i):Math.min(s.length,i);if(r===void 0)return s.slice(o);let a=Math.max(0,Math.trunc(Number(r))||0);return s.slice(o,o+a)},{min:2,max:3},"Returns substring by end-relative start and optional length"),this.registerFunction("substring",(e,n,r)=>String(e).substring(n,r),{min:2,max:3},"Returns substring between indices"),this.registerFunction("slice",(e,n,r)=>e!=null?e.slice(n,r):"",{min:2,max:3},"Slices string or array"),this.registerFunction("char_at",(e,n)=>String(e).charAt(n),2,"Returns character at index"),this.registerFunction("char_code",(e,n=0)=>String(e).charCodeAt(n),{min:1,max:2},"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),{min:0},"Returns string from character codes"),this.registerFunction("replace",(e,n,r)=>String(e).replace(n,r),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,n,r)=>String(e).replaceAll(n,r),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,n)=>String(e).repeat(n),2,"Repeats string count times"),this.registerFunction("pad_start",(e,n,r=" ")=>String(e).padStart(n,r),{min:2,max:3},"Left-pads string"),this.registerFunction("pad_end",(e,n,r=" ")=>String(e).padEnd(n,r),{min:2,max:3},"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace."),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof En,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>Sm(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("sprintf",(e,...n)=>Ga(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>Ga(e,n,"printf"),{min:1},"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules",!0),this.registerFunction("format",(e,...n)=>{let r=String(e),s=n.length===1&&typeof n[0]=="object"&&n[0]!==null&&!Array.isArray(n[0])?n[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<r.length;){let c=r[l];if(c==="{"&&r[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&r[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=r.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=r.slice(l+1,d);if(u==="")o+=i<n.length?a(n[i++]):"{}";else if(/^\d+$/.test(u)){let m=Number(u);o+=m<n.length?a(n[m]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("regex_test",(e,n,r="")=>Cr(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",tT,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",nT,{min:2,max:3},"Returns capture arrays with Unicode-aware zero-width progress; y is rejected"),this.registerFunction("regex_replace",(e,n,r,s="")=>String(e).replace(Cr(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(Cr(n,r)),{min:2,max:3},"Splits text at regular expression matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("range",(e,n,r=1)=>{let s=n===void 0?0:e,i=n===void 0?e:n,o=[];if(r>0)for(let a=s;a<i;a+=r)o.push(a);else if(r<0)for(let a=s;a>i;a+=r)o.push(a);return o},{min:1,max:3},"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...n)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...n)},{min:0},"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,n)=>Math.pow(e,n),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("sha256",e=>{if(typeof e!="string")throw new Error("sha256: expected a string");return zw("sha256").update(e,"utf8").digest("hex")},1,"Returns lowercase SHA-256 of UTF-8 text; strings only"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,n)=>yT(e,n),2,"Formats local time: epoch milliseconds first, format string second"),this.registerFunction("coalesce",(...e)=>{for(let n of e)if(n!=null)return n;return null},{min:0},"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,n)=>e??n,2,"Returns fallback if value is null/undefined, else value"),this.registerFunction("if_else",(e,n,r)=>e?n:r,3,"Eager compatibility helper: arguments evaluate eagerly; use condition ? thenValue : elseValue for lazy selection"),this.registerFunction("str",e=>Ia(e),1,"Converts lists and maps to compact JSON; scalars to normal text"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof En?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,n="Assertion failed")=>{if(!e)throw new Error(n);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,n,r,s,i=!1,o=!1){if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is reserved; rename this function");let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==m&&!u)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${p}'`);this.functionOriginModule.set(e,m);let f=typeof s=="object"?{returnsResource:s.returnsResource===!0||void 0,usesResource:s.usesResource===!0||void 0,closesResource:s.closesResource===!0||void 0}:{};if(this.hostFunctions.set(e,{fn:n,arity:r,description:a,isDefault:l,isContainerMutation:c,doc:d,params:typeof s=="object"?s.params:void 0,...f}),d)this.functionDocs.set(e,{...d,module:d.module??m});else if(!this.functionDocs.has(e)){let _=typeof r=="number"?r:r?.min??0,y=typeof r=="number"?r:r?.max,h=Array.from({length:y??_},(v,g)=>(g>=_?"[":"")+"arg"+(g+1)+(g>=_?"]":""));y===void 0&&h.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+h.join(", ")+")",description:a??"Host function "+e})}return this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,n){if(e==="PROPS")throw Error("PROPS is a reserved read-only map binding");if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is a reserved read-only binding: the running resumepoint path or null");return this.initialGlobals.set(e,n),this}getGlobal(e){return this.initialGlobals.get(e)}registerHostModule(e){return this.hostCatalog.set(e.name,e),this}getHostModule(e){return this.hostCatalog.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}async scanAndCheckAsync(e,n={}){try{let r=n.compiledSource??await uT(e,{...n,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??[]]});return{...this.scanAndCheck(e,{...n,compiledSource:r}),compiledSource:r}}catch(r){let s=r;return{ast:null,hasConcurrency:!1,diagnostics:[{severity:"error",message:s.message,line:s.line??1,column:s.column??1,file:s.file??n.file}]}}}scanAndCheck(e,n={}){try{let{program:r,diagnostics:s,hostImports:i,packages:o}=n.compiledSource??cT(e,{...n,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??[]]}),a=new Map(this.hostFunctions),l=[],c=new Map,d=new Map,u=new Set,m=[],p={known:[],closedTables:[],removedGlobals:{}};for(let v of[...[...this.builtinProviders.keys(),...this.hostCatalog.keys()].map(g=>({name:g,line:1,column:1,file:n.file})),...i]){if(l.some(T=>T.name===v.name))continue;let g;try{g=this.builtinProviders.get(v.name)??this.hostCatalog.get(v.name)??(n.resolveHostModule??this.hostResolver)?.(v.name)}catch(T){let I=aT(T);throw new M(`Cannot load module '${v.name}': ${I}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!g)throw new M(`Missing host module '${v.name}'. Install with npm install ${v.name} or set LMSCRIPT_MODULES; for a file use './${v.name}.lms'.`,v.line,v.column,"CHECKER",v.file);let E;try{let T=g.declarations,I=T?.functions,x=T?.globals;Array.isArray(I)&&Array.isArray(x)&&(E={functions:I.map(L=>({...L})),globals:x.map(L=>({...L})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(g.name!==v.name||!E||typeof g.activate!="function")throw new M(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let T of E.functions){let I=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Vs,T.name)||T.name==="RESUMEPOINT"||!I||!Number.isSafeInteger(I.min)||I.min<0||I.max!==void 0&&(!Number.isSafeInteger(I.max)||I.max<I.min))throw new M(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let x=d.get(T.name);if(T.override===!0&&a.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new M(`Module '${v.name}' cannot override ${x===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${x}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(a.has(T.name)&&!(T.override===!0&&a.get(T.name)?.isDefault))throw new M(`Module function collision: '${T.name}' in module '${v.name}'${x===void 0?"":` is already declared by module '${x}'`}`,v.line,v.column,"CHECKER",v.file);a.set(T.name,{arity:T.arity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:T.params,returnsResource:T.returnsResource===!0||void 0}),d.set(T.name,v.name)}for(let T of E.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Vs,T.name)||u.has(T.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(T.name)||this.initialGlobals.has(T.name)||n.globals?.includes(T.name))throw new M(`Module global collision or invalid name: '${T.name}'`,v.line,v.column,"CHECKER",v.file);u.add(T.name),this.builtinProviders.has(v.name)&&m.push(T.name)}E.properties&&(p.known=[...p.known,...E.properties.known],p.closedTables=[...p.closedTables??[],...E.properties.closedTables??[]],p.removedGlobals={...p.removedGlobals,...E.properties.removedGlobals}),l.push(g),c.set(g,E)}let f=[...this.initialGlobals.keys(),...n.globals||[],...u,"PROPS","Directory","NonInteractive","RESUMEPOINT"],_=new $a(a,{...n,globals:f,builtinGlobals:m,propertyDeclarations:p,sourcePackages:o}),y=[...s,..._.check(r)];for(let v of y)if(v.message.startsWith("Call to undefined function"))for(let g of this.hostCatalog.values())for(let E of g.declarations.functions)v.message.includes(`'${E.name}'`)&&(v.message+=`; provided by module '${g.name}': add import "${g.name}";`);let h={ast:r,diagnostics:y,hasConcurrency:_.hasConcurrency,hostModules:l,hostDeclarations:c,usedGlobals:[..._.usedGlobals],usedProperties:_.usedProperties,recoverLabels:[..._.recoverLabels],hasRecover:_.hasRecover,recoverScopedReads:_.recoverScopedReads,recoverScopedWrites:_.recoverScopedWrites};return hm(h,n)}catch(r){return r instanceof M?{ast:null,diagnostics:[{message:r.message,line:r.line,column:r.column,severity:"error",file:r.file||n.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:r instanceof Error?r.message:String(r),line:1,column:1,severity:"error",file:n.file}],hasConcurrency:!1}}}installBuiltinStubs(e,n,r,s,i){let o=n.hostDeclarations.get(e);for(let a of o.globals)r.globals.set(a.name,new Wa(()=>i(a.name)));for(let a of o.functions)r.functions.set(a.name,{fn:s(a.name),arity:a.arity,doc:a.doc,params:a.params,..._m(a)})}activationContext(e,n,r){return{cwd:n.hostContext?.cwd??process.cwd(),env:Object.freeze({...n.hostContext?.env??process.env}),signal:n.signal,propertyStore:n.propertyStore,usedGlobals:(e.usedGlobals??[]).filter(s=>(e.hostDeclarations?.get(r)??r.declarations).globals.some(i=>i.name===s))}}bindModule(e,n,r,s){if(!n||typeof n.dispose!="function")throw new Error(`Module '${e.name}' did not return a disposable`);let i=r.hostDeclarations?.get(e)??e.declarations;if(i.properties){if(!n.loadProperties)throw Error(`Provider '${e.name}' did not supply properties`);s.properties?.addSource(e.name,()=>n.loadProperties(),i.properties.known)}for(let o of i.functions){if(typeof n.functions?.[o.name]!="function")throw new Error(`Module '${e.name}' did not bind '${o.name}'`);s.functions.set(o.name,{fn:n.functions[o.name],arity:o.arity,doc:o.doc,params:o.params,..._m(o)})}for(let o of i.globals)if(Object.hasOwn(n.globals??{},o.name))s.globals.set(o.name,n.globals[o.name]);else if(r.usedGlobals?.includes(o.name))throw new Error(`Module '${e.name}' did not provide global '${o.name}'`)}moduleFailure(e,n,r){return{success:!1,output:[],diagnostics:[...n.diagnostics,{severity:"error",message:e instanceof Error?e.message:String(e),line:1,column:1,file:r.file}]}}collectModuleErrors(e,n){for(let r of e)if(r.getRecordedErrors!==void 0)try{let s=r.getRecordedErrors();if(!Array.isArray(s))throw new Error("getRecordedErrors must return an array");n.errors=[...n.errors??[],...s.map(i=>typeof i=="string"?i:JSON.stringify(i)??String(i))]}catch(s){n.diagnostics.push({severity:"warning",message:`Host module error collection failed: ${s instanceof Error?s.message:String(s)}`,line:1,column:1})}}cleanupWarning(e,n){n.diagnostics.push({severity:"warning",message:`Host module cleanup failed: ${e instanceof Error?e.message:String(e)}`,line:1,column:1})}run(e,n={}){this.outputLogs=[],this.lastRecordedErrors=[];let r=this.scanAndCheck(e,n);n={...n,propertyStore:n.propertyStore??new Zs(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let s=n.propertyStore,i={functions:new Map(this.hostFunctions),globals:new Map(this.initialGlobals),properties:s};i.globals.set("PROPS",s.view()),i.globals.set("Directory",s.get("Directory")),i.globals.set("NonInteractive",s.get("NonInteractive")),i.globals.set("RESUMEPOINT",null);let a={expand:(d,u={})=>{if(!u||typeof u!="object"||Array.isArray(u)||![Object.prototype,null].includes(Object.getPrototypeOf(u)))throw Error("expand: vars must be a map");let m=i.globals.get("ARGV")??[];return Ws(d,p=>p.kind==="property"?s.get(p.key):p.kind==="argument"?Array.isArray(m)&&Object.hasOwn(m,p.index)?m[p.index]:void 0:Object.hasOwn(u,p.name)?We(u,p.name):void 0,Ia)},get_property:(d,...u)=>s.get(d,...u),has_property:d=>s.has(d),get_properties:d=>s.copy(d),set_property:(d,u)=>s.set(d,u)};for(let[d,u]of Object.entries(a))i.functions.set(d,{...i.functions.get(d),fn:u});if(!r.ast||r.diagnostics.some(d=>d.severity==="error")||r.hasConcurrency)return this.executeSync(e,n,r,i);let l=[],c;try{Oe(n.signal);for(let d of r.hostModules??[]){if(this.builtinProviders.has(d.name)){let m,p=()=>{if(m)return m;Oe(n.signal);let f=d.activate(this.activationContext(r,n,d));if(Jn(f))throw f.then(_=>_.dispose()).catch(()=>{}),new Error(`Module '${d.name}' requires runAsync for activation`);if(!f||typeof f.dispose!="function")throw new Error(`Module '${d.name}' did not return a disposable`);return m=f,l.push(m),this.bindModule(d,m,r,i),m};this.installBuiltinStubs(d,r,i,f=>(..._)=>p().functions[f](..._),f=>(p(),i.globals.get(f))),r.usedProperties&&r.hostDeclarations?.get(d)?.properties&&p();continue}let u=d.activate(this.activationContext(r,n,d));if(Jn(u))throw u.then(m=>m.dispose()).catch(()=>{}),new Error(`Module '${d.name}' requires runAsync for activation`);l.push(u),this.bindModule(d,u,r,i),Oe(n.signal)}c=this.executeSync(e,n,r,i),n.signal?.aborted&&(c={...c,success:!1,diagnostics:c.diagnostics.some(d=>d.severity==="error"&&d.message==="Execution aborted")?c.diagnostics:[...c.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(d){c=this.moduleFailure(d,r,n)}this.collectModuleErrors(l,c);for(let d of l.reverse())try{let u=d.dispose();if(Jn(u))throw u.catch(()=>{}),new Error("Async disposal requires runAsync")}catch(u){this.cleanupWarning(u,c)}return c}async runAsync(e,n={}){n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?hm(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;n={...n,propertyStore:n.propertyStore??new Zs(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let i=n.propertyStore,o={functions:new Map(this.hostFunctions),globals:new Map(this.initialGlobals),properties:i};o.globals.set("PROPS",i.view()),o.globals.set("Directory",i.get("Directory")),o.globals.set("NonInteractive",i.get("NonInteractive")),o.globals.set("RESUMEPOINT",null);let l={expand:(u,m={})=>{if(!m||typeof m!="object"||Array.isArray(m)||![Object.prototype,null].includes(Object.getPrototypeOf(m)))throw Error("expand: vars must be a map");let p=o.globals.get("ARGV")??[];return Ws(u,f=>f.kind==="property"?i.get(f.key):f.kind==="argument"?Array.isArray(p)&&Object.hasOwn(p,f.index)?p[f.index]:void 0:Object.hasOwn(m,f.name)?We(m,f.name):void 0,Ia)},get_property:(u,...m)=>i.get(u,...m),has_property:u=>i.has(u),get_properties:u=>i.copy(u),set_property:(u,m)=>i.set(u,m)};for(let[u,m]of Object.entries(l))o.functions.set(u,{...o.functions.get(u),fn:m});if(!s.ast||s.diagnostics.some(u=>u.severity==="error"))return this.executeAsync(e,n,s,o);let c=[],d;try{Oe(n.signal);for(let u of s.hostModules??[]){if(this.builtinProviders.has(u.name)){let p,f=()=>p??=Promise.resolve().then(async()=>{Oe(n.signal);let _=await u.activate(this.activationContext(s,n,u));if(!_||typeof _.dispose!="function")throw new Error(`Module '${u.name}' did not return a disposable`);return c.push(_),this.bindModule(u,_,s,o),Oe(n.signal),_});this.installBuiltinStubs(u,s,o,_=>async(...y)=>(await f()).functions[_](...y),async _=>(await f(),o.globals.get(_))),s.usedProperties&&s.hostDeclarations?.get(u)?.properties&&await f();continue}let m=await u.activate(this.activationContext(s,n,u));c.push(m),this.bindModule(u,m,s,o),Oe(n.signal)}d=await this.executeAsync(e,n,s,o),n.signal?.aborted&&(d={...d,success:!1,diagnostics:d.diagnostics.some(u=>u.severity==="error"&&u.message==="Execution aborted")?d.diagnostics:[...d.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(u){d=this.moduleFailure(u,s,n)}this.collectModuleErrors(c,d);for(let u of c.reverse())try{await u.dispose()}catch(m){this.cleanupWarning(m,d)}return d}executeSync(e,n,r,s){let i=[],{ast:o,diagnostics:a,hasConcurrency:l}=r;if(a.filter(m=>m.severity==="error").length>0||!o)return this.outputLogs=i,{success:!1,diagnostics:a,output:i};if(l)return this.outputLogs=i,{success:!1,diagnostics:[...a,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:n.file}],output:i};let d,u;try{d=new ni(s.functions,f=>{i.push(f),n.stdout?.(f)},!1,s.globals,n.stderr,this.promptHumanConfig),d.abortSignal=n.signal,d.resumepoint=n.resumepoint,d.recoverScopedReads=r.recoverScopedReads??new WeakMap,d.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,u=this.trackResourceRun(d.resources);let m=d.evaluateProgram(o);this.outputLogs=[...i];let p=d.getRecordedErrors();return this.lastRecordedErrors=p,{success:!0,value:m,diagnostics:a,output:i,errors:p,resourceRun:u}}catch(m){let p=d?d.getRecordedErrors():[];if(this.lastRecordedErrors=p,m instanceof ht||m?.name==="LMScriptExit"||m?.isControlFlow){this.outputLogs=[...i];let h=typeof m.exitCode=="number"?m.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:a,output:i,errors:p,resourceRun:u}}let f=m instanceof M?m.line:1,_=m instanceof M?m.column:1,y=m instanceof M&&m.file||n.file;return this.outputLogs=[...i],{success:!1,diagnostics:[...a,{message:m?.message||String(m),line:f,column:_,severity:"error",file:y}],output:i,errors:p,resourceRun:u}}}async executeAsync(e,n,r,s){let i=[],{ast:o,diagnostics:a}=r;if(a.filter(u=>u.severity==="error").length>0||!o)return this.outputLogs=i,this.lastRecordedErrors=[],{success:!1,diagnostics:a,output:i,errors:[]};let c,d;try{c=new ni(s.functions,p=>{i.push(p),n.stdout?.(p)},!0,s.globals,n.stderr,this.promptHumanConfig),c.abortSignal=n.signal,c.resumepoint=n.resumepoint,c.recoverScopedReads=r.recoverScopedReads??new WeakMap,c.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,d=this.trackResourceRun(c.resources);let u=await c.evaluateProgramAsync(o);this.outputLogs=[...i];let m=c.getRecordedErrors();return this.lastRecordedErrors=m,{success:!0,value:u,diagnostics:a,output:i,errors:m,resourceRun:d}}catch(u){let m=c?c.getRecordedErrors():[];if(this.lastRecordedErrors=m,u instanceof ht||u?.name==="LMScriptExit"||u?.isControlFlow){this.outputLogs=[...i];let y=typeof u.exitCode=="number"?u.exitCode:0;return{success:y===0,value:y,exitCode:y,diagnostics:a,output:i,errors:m,resourceRun:d}}let p=u instanceof M?u.line:1,f=u instanceof M?u.column:1,_=u instanceof M&&u.file||n.file;return this.outputLogs=[...i],{success:!1,diagnostics:[...a,{message:u?.message||String(u),line:p,column:f,severity:"error",file:_}],output:i,errors:m,resourceRun:d}}}lastRecordedErrors=[];resourceRuns=new Map;trackResourceRun(e){for(this.resourceRuns.set(e.token,e);this.resourceRuns.size>64;)this.resourceRuns.delete(this.resourceRuns.keys().next().value);return e.token}inspectResources(e){return this.resourceRuns.get(e)?.snapshot()??[]}getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getFunctionMetadata(e){let n=this.hostFunctions.get(e);return n?{arity:n.arity,description:n.description}:void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};Ca=le.basename(Ja(import.meta.url));(Ca==="lmscript.ts"||Ca==="lmscript.js"||Ca==="lmscript")&&process.argv[1]&&F.existsSync(process.argv[1])&&F.realpathSync(Ja(import.meta.url))===F.realpathSync(le.resolve(process.argv[1]))&&vT()});var $M,Vt,wT,TT,bT,Qa,Za,el,fe,za,_t,si,Mr,ii,oi,Ya,$m,Um,Hm,Pr,Bm,Ke,zt=N(()=>{"use strict";$M=1,Vt=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Vt(e);Object.freeze(t)}return t},wT=Vt(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal"]),TT=Vt({status:"string",error:"string|null",code:"ErrorCode?"}),bT=Vt(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),Qa=Vt(["Provider1.Provider","Provider1.Model1","Provider1.Model2","Provider1.Model3","Provider2.Provider","Provider2.Model1","Provider2.Model2","Provider2.Model3","Provider3.Provider","Provider3.Model1","Provider3.Model2","Provider3.Model3"]),Za=Vt(["Provider1","Provider2","Provider3"]),el=Vt({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),fe={name:"ctx",type:"context"},za={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},_t={name:"teamfile",type:"string"},si={name:"alias",type:"string"},Mr={name:"prompt",type:"string"},ii={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"alias",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"},{name:"sessiondir",type:"string"},{name:"sessionid",type:"string"}]},oi=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],Ya={name:"options",type:"map",optional:!0,keys:oi},$m={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},Um={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},Hm={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Pr={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},Bm={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},Ke=Vt([{name:"resolveProfilePath",implemented:!0,params:[fe,za],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[fe,za],statuses:["ok","error"],results:{error:"string|null",profile:"{path,raw,config}",values:"{Provider1..3,Model1..3,Directory,NonInteractive}",path:"string?",line:"number?",column:"number?"},effects:["file-read"],summary:"Read and validate the complete init profile without discovery or writes."},{name:"profileValues",implemented:!0,params:[{name:"config",type:"map"}],statuses:["ok","error"],results:{error:"string|null",Provider1:"string",Provider2:"string",Provider3:"string",Model1:"string",Model2:"string",Model3:"string"},effects:[],summary:"Validate and map slots to first-model environment values."},{name:"readPrompts",implemented:!0,params:[fe,{name:"path",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"single",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",prompts:"string[]"},effects:["file-read"],summary:"Read prompt records without exiting the caller.",scriptBinding:{name:"lm_read_prompts",params:[{name:"batchfile",type:"string"},{name:"single",type:"boolean",optional:!0}]}},{name:"listMembers",implemented:!0,params:[fe,_t],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[_t]}},{name:"resolveMember",implemented:!0,params:[fe,_t,si],statuses:["ok","not_found","error"],results:{error:"string|null",member:"Member",isLead:"boolean",teamfile:"string"},effects:["file-read","db"],summary:"Resolve a team member with an explicit missing outcome.",scriptBinding:{name:"lm_member",params:[_t,si]}},{name:"lintTeam",implemented:!0,params:[fe,_t],statuses:["ok","error"],results:{error:"string|null",errors:"list",warnings:"list",counts:"map"},effects:["file-read","db"],summary:"Return structured lint findings.",scriptBinding:{name:"lm_lint",params:[_t]}},{name:"seedTeam",implemented:!0,params:[fe,_t,$m],statuses:["ok","error"],results:{error:"string|null",seeded:"SeededMember[]"},effects:["provider","db","file-write"],summary:"Seed a team with explicit optional preambles.",scriptBinding:{name:"lm_seed",params:[_t,$m]}},{name:"promptAgent",implemented:!0,params:[fe,ii,Mr,Ya],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...Bm,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[ii,Mr,Ya]}},{name:"promptMember",implemented:!0,params:[fe,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"prompt",type:"string",required:!0},{name:"messageType",type:"string"},...oi]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[_t,si,Mr,{name:"options",type:"map",optional:!0,keys:[...oi,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[fe,{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"workspace",type:"string"},{name:"all",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",sessions:"Session[]"},effects:["file-read"],summary:"List native sessions in an explicit workspace.",scriptBinding:{name:"lm_session_list",params:[{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"sessiondir",type:"string"},{name:"all",type:"boolean"}]}]}},{name:"deleteSession",implemented:!0,params:[fe,Pr,Hm],statuses:["deleted","not_found","busy","error"],results:{error:"string|null"},effects:["provider","file-write"],summary:"Delete a session only with explicit force admission.",scriptBinding:{name:"lm_session_delete",params:[ii,{...Hm,optional:!0}]}},{name:"getSession",implemented:!0,params:[fe,Pr],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages."},{name:"reserveSession",implemented:!0,params:[fe,Pr],statuses:["ok","busy","error"],results:{error:"string|null",reservation:"SessionReservation"},effects:[],summary:"Reserve context-local handoff admission and return a capability."},{name:"releaseSession",implemented:!0,params:[fe,Pr],statuses:["ok","error"],results:{error:"string|null"},effects:[],summary:"Release context-local handoff admission."},{name:"openTeamBatch",implemented:!0,params:[fe,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"promptCount",type:"number",required:!0},{name:"legacy",type:"boolean"},...oi]}],statuses:["ok","busy","error"],results:{error:"string|null",batch:"opaque context-bound BatchRef"},effects:["provider","db"],summary:"Open a managed team batch; member-map composition remains language-owned."},{name:"batchTurn",implemented:!0,params:[fe,{name:"batch",type:"BatchRef"},Mr,{name:"index",type:"number"},{name:"total",type:"number"}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn an owned live batch reference."},{name:"closeBatch",implemented:!0,params:[fe,{name:"batch",type:"BatchRef"},{name:"options",type:"map",keys:[{name:"status",type:"string",required:!0,values:["done","error","cancelled"]},{name:"error",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close an owned batch."},{name:"readRatelimits",implemented:!0,params:[fe,Um],statuses:["ok","error"],results:{error:"string|null",readings:"list"},effects:["file-read","network"],summary:"Read provider rate-limit data.",scriptBinding:{name:"lm_ratelimit_readings",params:[Um]}},{name:"openTerminal",implemented:!0,params:[fe,{name:"target",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0}]},{name:"streams",type:"map",keys:[{name:"stdin",type:"stream",required:!0},{name:"stdout",type:"stream",required:!0},{name:"stderr",type:"stream",required:!0}]}],statuses:["ok","error"],results:{error:"string|null",code:"number|null",signal:"string|null"},effects:["provider","db","tty"],summary:"Open a native terminal with caller-supplied streams.",scriptBinding:{name:"lm_terminal",params:[_t,si]}},{name:"sessionAdmission",implemented:!0,params:[fe,Pr],statuses:["ok","busy","error"],results:{error:"string|null",busyReason:"turn|handoff?"},effects:[],summary:"Query context-local session admission without exposing mutable sets."},{name:"promptReservedAgent",implemented:!0,params:[fe,{name:"reservation",type:"SessionReservation"},ii,Mr,Ya],statuses:["ok","busy","stalled","empty","error"],results:{...Bm,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"inspectBatch",implemented:!0,params:[fe,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null",id:"string",closed:"boolean",member:"Member",rootId:"number|null"},effects:[],summary:"Read batch metadata without exposing native transports or lease capabilities."},{name:"loadProperties",implemented:!0,params:[fe,za],statuses:["ok","error"],results:{error:"string|null",path:"string",properties:"map",flat:"map",line:"number?",column:"number?"},effects:["file-read"],summary:"Read the complete hierarchical init.toml properties document through the canonical reader."}])});var Wm,Xm=N(()=>{"use strict";Wm=[{name:"prompt_human",category:"lmctl Automation",signature:"prompt_human([question|session])",description:"Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. Core prompt options apply only without this binding."},{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"map",description:"Batch handle object or null on error"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index, total)",description:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns the reply.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:"{ status, code } after the TUI exits"},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}]});function G(t){try{if(t instanceof Error){let e=t.message;if(typeof e=="string")return e}return String(t)}catch{return"Unprintable error"}}function ce(t){return{...t,status:"ok",error:null}}function j(t,e,n){return{...n,status:"error",code:t,error:e}}var Ve=N(()=>{"use strict"});function vn(t){return t.some(e=>e!=null&&(typeof e!="number"||!Number.isSafeInteger(e)||e<0))}var ai=N(()=>{"use strict"});var li,qm,tl=N(()=>{"use strict";li={attempt_key:"TEXT",provider:"TEXT",native_session_id:"TEXT",cwd:"TEXT",ended_at:"TEXT",turn_outcome:"TEXT",model_requested:"TEXT",model_reported:"TEXT",tok_input_uncached:"INTEGER",tok_cache_read:"INTEGER",tok_cache_write:"INTEGER",tok_output:"INTEGER",tok_reasoning:"INTEGER",usage_source:"TEXT CHECK(usage_source IN ('wire','native','cumulative_delta'))",usage_reason:"TEXT",price_record_id:"TEXT",price_snapshot_sha256:"TEXT",rate_input_1m:"REAL",rate_output_1m:"REAL",rate_cache_read_1m:"REAL",rate_cache_write_1m:"REAL",cost_reason:"TEXT",provider_cost_usd:"REAL"},qm=`CREATE UNIQUE INDEX IF NOT EXISTS idx_team_chat_attempt_unique ON team_chat_log(attempt_key) WHERE attempt_key IS NOT NULL;
420
420
  CREATE INDEX IF NOT EXISTS idx_team_chat_started ON team_chat_log(created_at);
421
421
  CREATE INDEX IF NOT EXISTS idx_team_chat_provider_model ON team_chat_log(provider, model_reported);
422
422
  CREATE INDEX IF NOT EXISTS idx_team_chat_provider_session ON team_chat_log(provider, native_session_id);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmctl-ai/lmctl",
3
- "version": "0.2.102",
3
+ "version": "0.2.104",
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",