@lmctl-ai/lmctl 0.2.73 → 0.2.75
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/build-info.json +1 -1
- package/dist/cli/lmscript.js +2 -2
- package/modules/git.lms +1 -1
- package/package.json +1 -1
package/build-info.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"sha": "
|
|
1
|
+
{"sha": "257aba7a053f1390008b8e8d1638e303cae4117e", "dirty": true, "builtAt": "2026-10-05T17:04:22.000Z"}
|
package/dist/cli/lmscript.js
CHANGED
|
@@ -407,11 +407,11 @@ fn clamp(val, low, high) {
|
|
|
407
407
|
`)+(A.output.length>0?`
|
|
408
408
|
`:""),v=A.exitCode!==void 0?A.exitCode:A.success?0:1,T={success:A.success&&v===0,stdout:b,output:[...A.output],value:A.value,exit_code:v,code:v,errors:A.errors??[]};return T.toString=()=>b,T})();{let A=C.run(L,{file:S}),b=A.output.join(`
|
|
409
409
|
`)+(A.output.length>0?`
|
|
410
|
-
`:""),v=A.exitCode!==void 0?A.exitCode:A.success?0:1,T={success:A.success&&v===0,stdout:b,output:[...A.output],value:A.value,exit_code:v,code:v,errors:A.errors??[]};return T.toString=()=>b,T}},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 f=e.get("http_get");(!f||f.isDefault)&&this.hostFunctions.set("http_get",{fn:g=>this.isAsync?Uv(g):xu(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let w=e.get("sleep_ms");(!w||w.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(S=>setTimeout(S,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 He,this.initialGlobals)for(let[r,s]of this.initialGlobals.entries())this.globalEnv.define(r,s);this.userFunctions.clear(),this.callDepth=0;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 n}execStmt(e,n){switch(Fe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let r=new He(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 P(`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 P("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 ut)break;if(s instanceof mt)continue;throw s}}return}case"ForInStmt":{let r=wu(this.evalExpr(e.iterable,n),e),s=0;for(let i of r){if(++s>1e6)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let o=new He(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 ut)break;if(a instanceof mt)continue;throw a}}return}case"ForStmt":{let r=new He(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 P("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 ut)break;if(!(i instanceof mt))throw i}e.update&&this.evalExpr(e.update,r)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new Dn(r)}case"BreakStmt":throw new ut;case"ContinueStmt":throw new mt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new P("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,n);default:return}}evalExpr(e,n){switch(Fe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let r="";for(let s of e.parts)r+=typeof s=="string"?s:Ea(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new P("'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);return n.set(e.target,r),r}case"TupleAssignExpr":{let r=this.evalExpr(e.value,n);if(!Array.isArray(r))throw new P(`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;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),Be(r,s,i),i;throw new P("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)Be(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Bs(e);if(r)return De(this.resolveIdentifier("PROPS",n,e),r);let s=this.evalExpr(e.target,n),i=this.evalExpr(e.index,n);if(s==null)throw new P("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]:De(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 P(`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 P("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 P(`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.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}resolveIdentifier(e,n,r){if(n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&Ta.has(s))try{let i=Ta.get(s)();return Ps(i)?i.catch(o=>{throw new P(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new P(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new Fn(e);throw new P(`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 Fn?r.name:e}invokeNamed(e,n,r,s,i,o){if(Fe(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Ns)throw this.callDepth--,new P(`Execution fuel exhausted: maximum function call depth exceeded (${Ns})`,s,i,"RUNTIME",o);let l=new He(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 Dn)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return Fe(this.abortSignal),a.fn(...n)}catch(l){throw l instanceof pt||l?.name==="LMScriptExit"||l?.isControlFlow?l:new P(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new P(`'${e}' is not a function`,s,i,"RUNTIME",o):new P(vr(e,"Undefined function"),s,i,"RUNTIME",o)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new He,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear();for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let n=this.nextTaskId++,r;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(r=await this.execStmtAsync(s,this.globalEnv,n));return r}async execStmtAsync(e,n,r){switch(Fe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let s=new He(n);for(let i of e.statements)await this.execStmtAsync(i,s,r);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,n,r)),n.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(!Array.isArray(s))throw new P(`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 P("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,n,r)}catch(i){if(i instanceof ut)break;if(i instanceof mt)continue;throw i}}return}case"ForInStmt":{let s=wu(await this.evalExprAsync(e.iterable,n,r),e),i=0;for(let o of s){if(++i>1e6)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new He(n);a.define(e.name,o);try{if(e.body.kind==="BlockStmt")for(let l of e.body.statements)await this.execStmtAsync(l,a,r);else await this.execStmtAsync(e.body,a,r)}catch(l){if(l instanceof ut)break;if(l instanceof mt)continue;throw l}}return}case"ForStmt":{let s=new He(n);e.init&&await this.execStmtAsync(e.init,s,r);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(o))break}if(++i>1e6)throw new P("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,r)}catch(o){if(o instanceof ut)break;if(!(o instanceof mt))throw o}e.update&&await this.evalExprAsync(e.update,s,r)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,n,r):null;throw new Dn(s)}case"BreakStmt":throw new ut;case"ContinueStmt":throw new mt;case"SyncAssignStmt":{let s=n.resolveBinding(e.target);if(!s)throw new P(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let i=`bind:${s.env.id}:${s.name}`;await this.lockManager.getBindingLock(i).withLock(async()=>{let a=await this.evalExprAsync(e.value,n,r);s.env.set(s.name,a)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new P("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);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Be(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new P("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 P(`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 P("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);default:return}}async evalExprAsync(e,n,r){switch(Fe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let s="";for(let i of e.parts)s+=typeof i=="string"?i:Ea(await this.evalExprAsync(i.expression,n,r),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);return n.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,n,r);if(!Array.isArray(s))throw new P(`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;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(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Be(s,i,o),o;throw new P("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)s.push(await this.evalExprAsync(i,n,r));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,n,r));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Be(s,i.key,await this.evalExprAsync(i.value,n,r));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++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,n,d)}),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=Bs(e);if(s)return De(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(i==null)throw new P("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]:De(i,o)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,n,r),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new P(`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(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 P("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 P(`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 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(Fe(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>Ns)throw this.asyncCallDepth.set(o,d-1),new P(`Execution fuel exhausted: maximum function call depth exceeded (${Ns})`,s,i,"RUNTIME",a);let u=new He(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)u.define(c.params[m],n[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,u,o)}catch(m){if(m instanceof Dn)return m.value;throw m}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...n);return d instanceof Promise?await d:d}catch(d){throw d instanceof pt||d?.name==="LMScriptExit"||d?.isControlFlow?d:new P(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new P(`'${l}' is not a function`,s,i,"RUNTIME",a):new P(vr(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},zv=[{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;"}],Yv=[{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:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or object (alias for len).",example:"n = length([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:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(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 = 2]): string",description:"Serializes a value to formatted JSON string.",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(clock(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Alias for strftime: epoch milliseconds first, format second, using local time and the same supported tokens and validation.",example:'s = date_format(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:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(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:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Alias for str; lists and plain maps become compact JSON, while scalar text and + coercion stay unchanged.",example:"s = to_string(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");'}],Qv=[{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);"}];Wt=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 zv)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Yv)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Qv)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=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=$.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
|
|
410
|
+
`:""),v=A.exitCode!==void 0?A.exitCode:A.success?0:1,T={success:A.success&&v===0,stdout:b,output:[...A.output],value:A.value,exit_code:v,code:v,errors:A.errors??[]};return T.toString=()=>b,T}},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 f=e.get("http_get");(!f||f.isDefault)&&this.hostFunctions.set("http_get",{fn:g=>this.isAsync?Uv(g):xu(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let w=e.get("sleep_ms");(!w||w.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(S=>setTimeout(S,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 He,this.initialGlobals)for(let[r,s]of this.initialGlobals.entries())this.globalEnv.define(r,s);this.userFunctions.clear(),this.callDepth=0;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 n}execStmt(e,n){switch(Fe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let r=new He(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 P(`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 P("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 ut)break;if(s instanceof mt)continue;throw s}}return}case"ForInStmt":{let r=wu(this.evalExpr(e.iterable,n),e),s=0;for(let i of r){if(++s>1e6)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let o=new He(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 ut)break;if(a instanceof mt)continue;throw a}}return}case"ForStmt":{let r=new He(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 P("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 ut)break;if(!(i instanceof mt))throw i}e.update&&this.evalExpr(e.update,r)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new Dn(r)}case"BreakStmt":throw new ut;case"ContinueStmt":throw new mt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new P("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,n);default:return}}evalExpr(e,n){switch(Fe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let r="";for(let s of e.parts)r+=typeof s=="string"?s:Ea(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new P("'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);return n.set(e.target,r),r}case"TupleAssignExpr":{let r=this.evalExpr(e.value,n);if(!Array.isArray(r))throw new P(`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;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),Be(r,s,i),i;throw new P("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)Be(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Bs(e);if(r)return De(this.resolveIdentifier("PROPS",n,e),r);let s=this.evalExpr(e.target,n),i=this.evalExpr(e.index,n);if(s==null)throw new P("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]:De(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 P(`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 P("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 P(`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.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}resolveIdentifier(e,n,r){if(n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&Ta.has(s))try{let i=Ta.get(s)();return Ps(i)?i.catch(o=>{throw new P(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new P(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new Fn(e);throw new P(`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 Fn?r.name:e}invokeNamed(e,n,r,s,i,o){if(Fe(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Ns)throw this.callDepth--,new P(`Execution fuel exhausted: maximum function call depth exceeded (${Ns})`,s,i,"RUNTIME",o);let l=new He(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 Dn)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return Fe(this.abortSignal),a.fn(...n)}catch(l){throw l instanceof pt||l?.name==="LMScriptExit"||l?.isControlFlow?l:new P(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new P(`'${e}' is not a function`,s,i,"RUNTIME",o):new P(vr(e,"Undefined function"),s,i,"RUNTIME",o)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new He,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear();for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let n=this.nextTaskId++,r;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(r=await this.execStmtAsync(s,this.globalEnv,n));return r}async execStmtAsync(e,n,r){switch(Fe(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let s=new He(n);for(let i of e.statements)await this.execStmtAsync(i,s,r);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,n,r)),n.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(!Array.isArray(s))throw new P(`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 P("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,n,r)}catch(i){if(i instanceof ut)break;if(i instanceof mt)continue;throw i}}return}case"ForInStmt":{let s=wu(await this.evalExprAsync(e.iterable,n,r),e),i=0;for(let o of s){if(++i>1e6)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new He(n);a.define(e.name,o);try{if(e.body.kind==="BlockStmt")for(let l of e.body.statements)await this.execStmtAsync(l,a,r);else await this.execStmtAsync(e.body,a,r)}catch(l){if(l instanceof ut)break;if(l instanceof mt)continue;throw l}}return}case"ForStmt":{let s=new He(n);e.init&&await this.execStmtAsync(e.init,s,r);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(o))break}if(++i>1e6)throw new P("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,r)}catch(o){if(o instanceof ut)break;if(!(o instanceof mt))throw o}e.update&&await this.evalExprAsync(e.update,s,r)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,n,r):null;throw new Dn(s)}case"BreakStmt":throw new ut;case"ContinueStmt":throw new mt;case"SyncAssignStmt":{let s=n.resolveBinding(e.target);if(!s)throw new P(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let i=`bind:${s.env.id}:${s.name}`;await this.lockManager.getBindingLock(i).withLock(async()=>{let a=await this.evalExprAsync(e.value,n,r);s.env.set(s.name,a)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new P("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);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Be(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new P("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 P(`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 P("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);default:return}}async evalExprAsync(e,n,r){switch(Fe(this.abortSignal),e.kind){case"InterpolatedStringExpr":{let s="";for(let i of e.parts)s+=typeof i=="string"?i:Ea(await this.evalExprAsync(i.expression,n,r),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);return n.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,n,r);if(!Array.isArray(s))throw new P(`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;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(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Be(s,i,o),o;throw new P("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)s.push(await this.evalExprAsync(i,n,r));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,n,r));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Be(s,i.key,await this.evalExprAsync(i.value,n,r));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++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,n,d)}),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=Bs(e);if(s)return De(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(i==null)throw new P("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]:De(i,o)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,n,r),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new P(`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(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 P("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 P(`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 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(Fe(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>Ns)throw this.asyncCallDepth.set(o,d-1),new P(`Execution fuel exhausted: maximum function call depth exceeded (${Ns})`,s,i,"RUNTIME",a);let u=new He(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)u.define(c.params[m],n[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,u,o)}catch(m){if(m instanceof Dn)return m.value;throw m}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...n);return d instanceof Promise?await d:d}catch(d){throw d instanceof pt||d?.name==="LMScriptExit"||d?.isControlFlow?d:new P(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new P(`'${l}' is not a function`,s,i,"RUNTIME",a):new P(vr(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},zv=[{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;"}],Yv=[{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:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or object (alias for len).",example:"n = length([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:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(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(clock(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Alias for strftime: epoch milliseconds first, format second, using local time and the same supported tokens and validation.",example:'s = date_format(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:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(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:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Alias for str; lists and plain maps become compact JSON, while scalar text and + coercion stay unchanged.",example:"s = to_string(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");'}],Qv=[{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);"}];Wt=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 zv)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Yv)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Qv)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=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=$.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
|
`)+`
|
|
414
|
-
`;return $.writeFileSync(e,r,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from($.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return $.readdirSync(le.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,n)=>($.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,n)=>($.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,n)=>($.writeFileSync(e,String(n),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,n)=>($.appendFileSync(e,String(n),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let n=$.readFileSync(e,"utf-8");return JSON.parse(n)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,n,r=2)=>($.writeFileSync(e,JSON.stringify(n,null,r),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,n=!0,r=",")=>{let s=$.readFileSync(e,"utf-8");return Eu(s,n,r)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,n,r=",")=>($.writeFileSync(e,Tu(n,r),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",Eu,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",Tu,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=le.resolve($v(),`lmscript-${Dv()}`),n=$.openSync(e,"wx",384);return $.closeSync(n),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>$.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new pt(Number(
|
|
414
|
+
`;return $.writeFileSync(e,r,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from($.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return $.readdirSync(le.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,n)=>($.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,n)=>($.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,n)=>($.writeFileSync(e,String(n),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,n)=>($.appendFileSync(e,String(n),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let n=$.readFileSync(e,"utf-8");return JSON.parse(n)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,n,r=2)=>($.writeFileSync(e,JSON.stringify(n,null,r),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,n=!0,r=",")=>{let s=$.readFileSync(e,"utf-8");return Eu(s,n,r)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null."),this.registerFunction("write_csv",(e,n,r=",")=>($.writeFileSync(e,Tu(n,r),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",Eu,{min:1,max:3},"Parses inline CSV text into records or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null."),this.registerFunction("csv_stringify",Tu,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=le.resolve($v(),`lmscript-${Dv()}`),n=$.openSync(e,"wx",384);return $.closeSync(n),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>$.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{let n=Number(e);throw new pt(Number.isFinite(n)&&n>=0&&n<=255?Math.floor(n):1)},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>$.existsSync(e)?($.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>$.existsSync(e)?($.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,n=!0)=>($.mkdirSync(e,{recursive:!!n}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,n=!1)=>$.existsSync(e)?(n?$.rmSync(e,{recursive:!0,force:!0}):$.rmdirSync(e),!0):!1,{min:1,max:2},"Removes a directory; pass true for recursive removal of a non-empty directory"),this.registerFunction("copy_file",(e,n)=>($.copyFileSync(e,n),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,n)=>($.renameSync(e,n),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,n)=>le.basename(e,n),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>le.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>le.join(...e),{min:0},"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>le.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,n=null)=>process.env[e]!==void 0?process.env[e]:n,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,n=null)=>process.env[e]!==void 0?process.env[e]:n,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,n)=>(process.env[e]=String(n),!0),2,"Sets an environment variable for this process and its children"),this.registerFunction("list",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("array",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("push",(e,...n)=>(e.push(...n),e),{min:1},"Pushes item(s) to end of array and returns the same array",!0,!0),this.registerFunction("pop",e=>e.pop(),1,"Pops item from end of array",!0,!0),this.registerFunction("shift",e=>e.shift(),1,"Removes and returns first element",!0,!0),this.registerFunction("unshift",(e,...n)=>(e.unshift(...n),e),{min:1},"Adds item(s) to front of array and returns the same array",!0,!0),this.registerFunction("insert",(e,n,r)=>{let s=n<0?e.length+n:n;return e.splice(s,0,r),e},3,"Inserts item at index and returns the same array",!0,!0),this.registerFunction("remove_at",(e,n)=>{let r=n<0?e.length+n:n,s=e.splice(r,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...n)=>e.concat(...n),{min:1},"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,n)=>{if(!Array.isArray(e))return e;let r=[...e];return n?r.sort((s,i)=>{let o=s?s[n]:void 0,a=i?i[n]:void 0;return o<a?-1:o>a?1:0}):r.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:String(s).localeCompare(String(i)))},{min:1,max:2},"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("sorted",(e,n)=>this.hostFunctions.get("sort").fn(e,n),{min:1,max:2},"Sorts array numerically, alphabetically, or by object key (alias for sort)"),this.registerFunction("unique",e=>Array.isArray(e)?Array.from(new Set(e)):[],1,"Removes duplicate elements"),this.registerFunction("flatten",e=>Array.isArray(e)?e.flat():[],1,"Flattens array one level"),this.registerFunction("first",e=>Array.isArray(e)&&e.length>0?e[0]:null,1,"Returns first element"),this.registerFunction("last",e=>Array.isArray(e)&&e.length>0?e[e.length-1]:null,1,"Returns last element"),this.registerFunction("sum",e=>Array.isArray(e)?e.reduce((n,r)=>n+(typeof r=="number"?r:Number(r)||0),0):0,1,"Calculates sum of array"),this.registerFunction("avg",e=>!Array.isArray(e)||e.length===0?0:e.reduce((r,s)=>r+(typeof s=="number"?s:Number(s)||0),0)/e.length,1,"Calculates average of array"),this.registerFunction("map",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("hash",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("from_entries",e=>Array.isArray(e)?Object.fromEntries(e):{},1,"Creates map from [key, value] pairs"),this.registerFunction("clear",e=>{if(Array.isArray(e))return e.length=0,e;if(e&&typeof e=="object"){for(let n of Object.keys(e))delete e[n];return e}return e},1,"Clears array or map",!0,!0),this.registerFunction("size",e=>Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns number of elements in array, string, or map"),this.registerFunction("system",(e,n=6e4)=>{if(!Number.isSafeInteger(n)||n<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsyncMode?Nu(e,n):Cu(e,n)},{min:1,max:2},"Executes shell command or argv array directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",!0),this.registerFunction("run_script",(e,n=[])=>{let r=le.resolve(String(e));if(!$.existsSync(r))throw new Error(`run_script: file not found: '${r}'`);let s=$.readFileSync(r,"utf-8"),i=Array.isArray(n)?n.map(String):[],o=new t;for(let[a,l]of this.hostFunctions)o.hasFunction(a)?l.isDefault||o.registerFunction(a,l.fn,l.arity,{description:l.description,params:l.params,doc:l.doc,allowOverwrite:!0,isContainerMutation:l.isContainerMutation},!1,l.isContainerMutation):o.registerFunction(a,l.fn,l.arity,{description:l.description,params:l.params,doc:l.doc,isDefault:l.isDefault,isContainerMutation:l.isContainerMutation});if(o.setGlobal("args",[...i]),o.setGlobal("ARGV",[...i]),this.isAsyncMode)return(async()=>{let a=await o.runAsync(s,{file:r}),l=a.output.join(`
|
|
415
415
|
`)+(a.output.length>0?`
|
|
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?`
|
package/modules/git.lms
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// terminal LF, rather than Git's flattened %s. n must be 0..10000.
|
|
9
9
|
// diff_stat compares rev to index+worktree, excludes untracked paths and
|
|
10
10
|
// reports renames as delete/add (--no-renames); binary counts are null.
|
|
11
|
-
// Command failures
|
|
11
|
+
// Command failures stop the run via require (exit 2) with argv, exit/signal and stderr tail.
|
|
12
12
|
// Launch errors (e.g. absent git) are loud system errors, with no process exit.
|
|
13
13
|
// argv execution and --end-of-options protect user paths/revisions. Query
|
|
14
14
|
// commands: no explicit fetch/push, no commit, no checkout, no import-time effects.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmctl-ai/lmctl",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.75",
|
|
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",
|