@lmctl-ai/lmctl 0.2.16 → 0.2.17

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/dist/cli/index.js CHANGED
@@ -2046,7 +2046,7 @@ fn clamp(val, low, high) {
2046
2046
  `)+(v.output.length>0?`
2047
2047
  `:""),w=v.exitCode!==void 0?v.exitCode:v.success?0:1,x={success:v.success&&w===0,stdout:S,output:[...v.output],value:v.value,exit_code:w,code:w,errors:v.errors??[]};return x.toString=()=>S,x})();{let v=b.run(y,{file:E}),S=v.output.join(`
2048
2048
  `)+(v.output.length>0?`
2049
- `:""),w=v.exitCode!==void 0?v.exitCode:v.success?0:1,x={success:v.success&&w===0,stdout:S,output:[...v.output],value:v.value,exit_code:w,code:w,errors:v.errors??[]};return x.toString=()=>S,x}},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 _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:g=>this.isAsync?EA(g):xg(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,g));let f=Date.now()+g;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new rt,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new rt(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){if(++n>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(s){if(s instanceof er)break;if(s instanceof tr)continue;throw s}}return}case"ForStmt":{let n=new rt(r);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof er)break;if(!(i instanceof tr))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new on(n)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new M("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),rr(n,s,i),i;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)rr(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);if(n==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:ht(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new M(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new M(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof an)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Xi)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",o);let l=new rt(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof on)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...r)}catch(l){throw l instanceof He||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new an(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new rt,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 r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new rt(r);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,n));){if(++s>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,r,n)}catch(i){if(i instanceof er)break;if(i instanceof tr)continue;throw i}}return}case"ForStmt":{let s=new rt(r);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof er)break;if(!(o instanceof tr))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new on(s)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new M(`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,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new M("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),rr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new M(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new M("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),rr(s,i,o),o;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)rr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,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=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:ht(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new M(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),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 M("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Xi)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",a);let u=new rt(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)u.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,u,o)}catch(m){if(m instanceof on)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(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof He||d?.name==="LMScriptExit"||d?.isControlFlow?d:new M(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},bA=[{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 (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",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. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{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;"}],IA=[{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("~/repos/*/*.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:"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.",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:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",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 for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",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.",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:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{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:"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:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("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:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("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:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("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 starting from start index of specified length.",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 Unicode code point 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:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{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 number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: 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, item: 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(a: array, b: array): array",description:"Concatenates two 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:"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:"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:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{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:"getstr",category:"Maps & Key-Value",signature:"getstr(obj: any, path: string|array): string",description:'Typed form of get(): reads a string field, "" when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null", not "" -- getstr never does that).',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): array",description:"Typed form of get(): reads an array field, [] when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{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",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{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 (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { 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]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...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:"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), prints "error: <message>" to stderr 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:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",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:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],xA=[{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:"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:"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);"}];nr=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of bA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of IA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of xA)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,r){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=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,r)}finally{this.currentRegisteringModule=n}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(r=>(r.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 r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.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 r=$.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
2049
+ `:""),w=v.exitCode!==void 0?v.exitCode:v.success?0:1,x={success:v.success&&w===0,stdout:S,output:[...v.output],value:v.value,exit_code:w,code:w,errors:v.errors??[]};return x.toString=()=>S,x}},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 _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:g=>this.isAsync?EA(g):xg(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,g));let f=Date.now()+g;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new rt,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new rt(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){if(++n>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(s){if(s instanceof er)break;if(s instanceof tr)continue;throw s}}return}case"ForStmt":{let n=new rt(r);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof er)break;if(!(i instanceof tr))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new on(n)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new M("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),rr(n,s,i),i;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)rr(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);if(n==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:ht(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new M(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new M(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof an)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Xi)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",o);let l=new rt(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof on)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...r)}catch(l){throw l instanceof He||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new an(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new rt,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 r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new rt(r);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,n));){if(++s>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,r,n)}catch(i){if(i instanceof er)break;if(i instanceof tr)continue;throw i}}return}case"ForStmt":{let s=new rt(r);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof er)break;if(!(o instanceof tr))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new on(s)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new M(`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,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new M("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),rr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new M(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new M("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),rr(s,i,o),o;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)rr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,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=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:ht(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new M(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),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 M("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Xi)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",a);let u=new rt(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)u.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,u,o)}catch(m){if(m instanceof on)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(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof He||d?.name==="LMScriptExit"||d?.isControlFlow?d:new M(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},bA=[{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 (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",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. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{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;"}],IA=[{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("~/repos/*/*.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:"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.",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:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",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 for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",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.",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:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{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:"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:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("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:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("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:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("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 starting from start index of specified length.",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 Unicode code point 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:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{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 number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: 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, item: 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(a: array, b: array): array",description:"Concatenates two 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:"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:"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:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{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:"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:"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",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{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 (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { 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]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...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:"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), prints "error: <message>" to stderr 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:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",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:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],xA=[{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:"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:"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);"}];nr=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of bA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of IA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of xA)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,r){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=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,r)}finally{this.currentRegisteringModule=n}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(r=>(r.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 r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.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 r=$.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
2050
2050
  `)?r=r.slice(0,-2):r.endsWith(`
2051
2051
  `)&&(r=r.slice(0,-1)),n?r.length===0?[""]:r.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,r)=>{if(!Array.isArray(r))throw new Error("write_lines: second argument must be an array of lines");let n=r.length===0?"":r.map(String).join(`
2052
2052
  `)+`
@@ -2055,7 +2055,7 @@ fn clamp(val, low, high) {
2055
2055
  `:""),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:n}),l=a.output.join(`
2056
2056
  `)+(a.output.length>0?`
2057
2057
  `:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
2058
- `):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>xg(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?cs(e):ls(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,r)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,r)},{min:1,max:2},"Parses JSON string into object/array, or stringifies data to JSON string"),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,r=null)=>TA(e,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,r)=>JSON.stringify(e,null,r),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=ss(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r)=>{let n=ss(e,r);return n==null?"":String(n)},2,'Reads a string field from a map/request form; "" when missing or null (never the string "null")'),this.registerFunction("getnum",(e,r,n=0)=>{let s=ss(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=ss(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r)=>{let n=ss(e,r);return Array.isArray(n)?n:[]},2,"Reads an array field from a map/request form; [] when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
2058
+ `):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>xg(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?cs(e):ls(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,r)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,r)},{min:1,max:2},"Parses JSON string into object/array, or stringifies data to JSON string"),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,r=null)=>TA(e,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,r)=>JSON.stringify(e,null,r),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=ss(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r,n="")=>{let s=ss(e,r);return s==null?n:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,r,n=0)=>{let s=ss(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=ss(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r,n=[])=>{let s=ss(e,r);return Array.isArray(s)?s:n},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
2059
2059
  `):console.error(`error: ${String(r)}`),new He(2);return e},2,'Stops the script (stderr message, exit 2) if value is missing -- "", null, [], or false -- else returns value unchanged, so it composes with getstr/getnum/getbool/getlist'),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(ht(i,a)==null||typeof ht(i,a)!="object")&&rr(i,a,{}),i=ht(i,a)}return s.length>0&&rr(i,s[s.length-1],n),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,r)=>Array.isArray(e)?e.map(n=>ht(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&ht(s,r)===n):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,r,n)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&ht(i,r)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,r)=>({...e,...r}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,r)=>(e&&typeof e=="object"&&delete e[r],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...r)=>{let n=as(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/);for(let n=r.length-1;n>=0;n--){let s=r[n].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof an,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>kg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let m=Number(u);o+=m<r.length?a(r[m]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>as(e,r),void 0,"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax)"),this.registerFunction("regex_test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string (alias for regex_test)"),this.registerFunction("regex_match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null"),this.registerFunction("match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("search",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("regex_find_all",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...]"),this.registerFunction("findall",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all)"),this.registerFunction("regex_replace",(e,r,n,s="")=>String(e).replace(new RegExp(r,s),n),{min:3,max:4},'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence, not just the first'),this.registerFunction("split_regex",(e,r,n="")=>String(e).split(new RegExp(r,n)),{min:2,max:3},"Splits a string into an array wherever the regex pattern matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("length",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("count",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("range",(e,r,n=1)=>{let s=r===void 0?0:e,i=r===void 0?e:r,o=[];if(n>0)for(let a=s;a<i;a+=n)o.push(a);else if(n<0)for(let a=s;a>i;a+=n)o.push(a);return o},void 0,"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...r)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},void 0,"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,r)=>Math.pow(e,r),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("clock",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms (alias for clock)"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,r)=>Tg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Tg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,r,n)=>e?r:n,3,"Expression-level ternary: returns thenVal if cond is truthy, else elseVal"),this.registerFunction("str",e=>e===null?"null":String(e),1,"Converts value to string"),this.registerFunction("to_string",e=>e===null?"null":String(e),1,"Converts value to string (alias for str)"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof an?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==m&&!u)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${p}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:kA(e,n),description:a}),this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,r){return this.initialGlobals.set(e,r),this}getGlobal(e){return this.initialGlobals.get(e)}scanAndCheck(e,r={}){try{let{program:n}=SA(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new vc(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof M?{ast:null,diagnostics:[{message:n.message,line:n.line,column:n.column,severity:"error",file:n.file||r.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:n instanceof Error?n.message:String(n),line:1,column:1,severity:"error",file:r.file}],hasConcurrency:!1}}}run(e,r={}){let n=[],{ast:s,diagnostics:i,hasConcurrency:o}=this.scanAndCheck(e,r);if(i.filter(c=>c.severity==="error").length>0||!s)return this.outputLogs=n,{success:!1,diagnostics:i,output:n};if(o)return this.outputLogs=n,{success:!1,diagnostics:[...i,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:r.file}],output:n};let l;try{l=new Ki(this.hostFunctions,u=>n.push(u),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let d=l.getRecordedErrors();return this.lastRecordedErrors=d,{success:!0,value:c,diagnostics:i,output:n,errors:d}}catch(c){let d=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=d,c instanceof He||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let _=typeof c.exitCode=="number"?c.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:i,output:n,errors:d}}let u=c instanceof M?c.line:1,m=c instanceof M?c.column:1,p=c instanceof M&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:m,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new Ki(this.hostFunctions,d=>n.push(d),!0,this.initialGlobals,r.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof He||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof M?l.line:1,u=l instanceof M?l.column:1,m=l instanceof M&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,severity:"error",file:m}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};wg=ye.basename(Sg(import.meta.url));(wg==="lmscript.ts"||wg==="lmscript.js")&&process.argv[1]&&$.existsSync(process.argv[1])&&$.realpathSync(Sg(import.meta.url))===$.realpathSync(ye.resolve(process.argv[1]))&&RA()});import{mkdirSync as Fg,readFileSync as NA,renameSync as LA,writeFileSync as CA,existsSync as Pg}from"node:fs";import{homedir as OA}from"node:os";import{dirname as Ug,join as Yi,resolve as zi}from"node:path";import{fileURLToPath as DA}from"node:url";function UA(){return Yi(OA(),".lmctl","cache","lmprice")}function ln(t,e){return Yi(t,e)}function wr(t){try{return JSON.parse(NA(t,"utf-8"))}catch{return null}}function Bg(t,e){let r=`${t}.tmp-${process.pid}`;CA(r,e),LA(r,t)}function Ic(t){return t===null||typeof t=="number"}function Qi(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.schema_version!==1||!Array.isArray(e.records)||e.records.length===0?!1:e.records.every(r=>{if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.source!="string"||typeof n.source_model_id!="string"||typeof n.pricing!="object"||n.pricing===null)return!1;let s=n.pricing;return Ic(s.input_per_1m_tokens)&&Ic(s.output_per_1m_tokens)&&Ic(s.input_cache_read_per_1m_tokens)})}function Zi(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.schema_version!==1||!Array.isArray(e.standards)||!Array.isArray(e.aliases))return!1;let r=e.standards.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.standard_slug=="string"&&(i.catalog_record_id===null||typeof i.catalog_record_id=="string")}),n=e.aliases.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.alias=="string"&&(i.standard_slug===null||typeof i.standard_slug=="string")&&typeof i.evidence=="string"&&BA.has(i.evidence)});return r&&n}function WA(t){let e=wr(ln(t,jg)),r={etag:typeof e?.model_list?.etag=="string"?e.model_list.etag:null,last_checked:typeof e?.model_list?.last_checked=="string"?e.model_list.last_checked:null},n={etag:typeof e?.aliases?.etag=="string"?e.aliases.etag:null,last_checked:typeof e?.aliases?.last_checked=="string"?e.aliases.last_checked:null};if(e===null){let s=wr(ln(t,jA));s&&(r.etag=typeof s.etag=="string"?s.etag:null,r.last_checked=typeof s.fetchedAt=="string"?s.fetchedAt:null)}return{model_list:r,aliases:n}}function HA(t){let e=WA(t),r=wr(ln(t,xc)),n=wr(ln(t,kc));return{catalog:Qi(r)?r:null,aliases:Zi(n)?n:null,meta:e}}function XA(t,e){try{Fg(t,{recursive:!0}),Bg(ln(t,jg),JSON.stringify(e))}catch{}}function Lg(t,e,r){try{Fg(t,{recursive:!0}),Bg(ln(t,e),JSON.stringify(r))}catch{}}function qA(t,e){let r=GA(t),n=r?[zi(r,"data",e)]:[zi(t,"..","..","data",e)];for(let s of n)if(Pg(s))return s;return null}function GA(t){let e=zi(t);for(;;){if(Pg(zi(e,"package.json")))return e;let r=Ug(e);if(r===e)return null;e=r}}function Cg(t,e,r){let n=r!==void 0?r:qA(t,e);return n===null?null:wr(n)}function JA(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Ng;let e=Number(t);return!Number.isFinite(e)||e<0?Ng:e*1e3}function VA(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function Og(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(FA)});if(!s.ok)return{kind:"failed"};let i=s.headers.get("etag");if(r!==null&&i!==null&&i===n)return{kind:"match"};let o=await t(e,{signal:AbortSignal.timeout(PA)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function eo(t={}){return Object.keys(t).length===0?(Dg??=Mg(t),Dg):Mg(t)}async function Mg(t){let e=Ug(DA(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:VA();if(r!==null&&r!==""){let _=wr(Yi(r,xc)),h=wr(Yi(r,kc));if(Qi(_)&&Zi(h)){let g={catalog:_,aliases:h,source:"pinned",generatedAt:_.generated_at??null};return Ac=g.generatedAt,g}return $g(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??UA(),i=t.now??Date.now(),o=t.ttlMs??JA(),a=HA(s),l=(_,h)=>_!==null&&h.last_checked!==null&&i-Date.parse(h.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},p=!1;if(!l(c,a.meta.model_list)){let _=await Og(n,MA,c,a.meta.model_list.etag);_.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),p=!0,Qi(_.payload)&&(c=_.payload,_.etag!==null&&(m.model_list.etag=_.etag),Lg(s,xc,c),u=!0))}if(!l(d,a.meta.aliases)){let _=await Og(n,$A,d,a.meta.aliases.etag);_.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),p=!0,Zi(_.payload)&&(d=_.payload,_.etag!==null&&(m.aliases.etag=_.etag),Lg(s,kc,d),u=!0))}if((p||u)&&XA(s,m),c!==null||d!==null){let _={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return Ac=_.generatedAt,_}return $g(t,e)}function $g(t,e){let r=Cg(e,"price-data.json",t.bundledPath),n=Cg(e,"price-aliases.json",t.bundledAliasesPath),s=Qi(r)?r:null,i=Zi(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Ac=o.generatedAt,o}function Wg(t,e){if(e===null)return null;let{input_per_1m_tokens:r,output_per_1m_tokens:n,input_cache_read_per_1m_tokens:s}=e;if(r===null||n===null)return null;let i=s??r,o=t.input/1e6*r+t.output/1e6*n+t.cachedInput/1e6*i;return Number(o.toPrecision(10))}var MA,$A,FA,PA,Ng,xc,kc,jg,jA,BA,Ac,Dg,Rc=k(()=>{"use strict";MA="https://lmctl.com/dataset/model_list.json",$A="https://lmctl.com/dataset/aliases.json",FA=1e3,PA=1e4,Ng=6*60*60*1e3;xc="model_list.json",kc="aliases.json",jg="meta.json",jA="model_list.meta.json";BA=new Set(["established","asserted","unresolved"]);Ac=null,Dg=null});function Sr(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function vr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Sr(r)}function Xg(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Sr(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function KA(t,e){let r=new Set,n=l=>{r.add(Sr(l))},s=t.trim().toLowerCase(),i=null,o=s.indexOf(":");o>0&&!s.slice(0,o).includes("/")&&(i=s.slice(0,o),n(s),s=s.slice(o+1)),n(s);let a=s.slice(s.lastIndexOf("/")+1);n(a);for(let l of e)n(`${l}/${a}`);return i!==null&&n(`${i}/${a}`),[...r]}function cn(t){let e=n=>!(n.mode!==void 0&&n.mode!==null&&n.mode!=="chat"||t.nonChatName&&t.nonChatName.test(n.source_model_id.toLowerCase())),r=n=>e(n)&&t.family.test(n.source_model_id.toLowerCase());return{firstPartyProviders:t.firstPartyProviders,isChatModel:e,coversRecord:r,normalize:n=>KA(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=Xg(n);return s.some(o=>i.has(o))}}}function zA(t){let e=t.trim(),r=YA.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function tR(t,e,r){let n=e.trim().toLowerCase(),s=Sr(n);if(r.records.some(o=>o.source_model_id.toLowerCase()===n&&t.matchRow(o,[s])))return!0;let i=t.normalize(e);return i.length>0&&r.records.some(o=>t.matchRow(o,i))}function rR(t,e,r){let n=[];for(let[s,i]of Object.entries(ds))s!==r&&tR(i,t,e)&&n.push(s);return n}function to(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function nR(t,e){return t.input_per_1m_tokens===e.input_per_1m_tokens&&t.output_per_1m_tokens===e.output_per_1m_tokens&&t.input_cache_read_per_1m_tokens===e.input_cache_read_per_1m_tokens}function sR(t){let e=new Map,r=[];for(let n of t){let s=n.source_model_id.toLowerCase(),i=s.lastIndexOf("/"),o=i===-1?"":s.slice(0,i+1),a=i===-1?s:s.slice(i+1),l=`${n.source}:${o}${Sr(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!nR(c.pricing,n.pricing)){r.push(n);continue}/\d\.\d/.test(c.source_model_id)&&!/\d\.\d/.test(n.source_model_id)&&e.set(l,n)}return[...e.values(),...r]}function iR(t){return{route:t.record_id??`${t.source}:${t.source_model_id}`,source:t.source,sourceModelId:t.source_model_id,provider:t.provider??null,pricing:t.pricing,estimated:t.source==="manual"}}function zg(t,e){return t.map(iR).sort((r,n)=>{let s=to(r.source)-to(n.source);if(s!==0)return s;let i=r.provider!==null&&e.includes(r.provider)?0:1,o=n.provider!==null&&e.includes(n.provider)?0:1;return i!==o?i-o:r.sourceModelId.localeCompare(n.sourceModelId)})}function Nc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function oR(t,e,r){let n=sR(t),s=zg(n,r),o=n.find(a=>(a.record_id??`${a.source}:${a.source_model_id}`)===s[0].route)?.context_window?.input_tokens??void 0;return{id:s[0].sourceModelId,normalizedId:e,offers:s,...o!=null?{contextWindow:o}:{}}}function Lc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=oR(t,e,r),s=n.offers.find(Nc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function aR(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function lR(t,e,r){let n=t.standard_slug;if(e===null||e.catalog_record_id===null)return{kind:"known-unpriced",id:n};let s=e.catalog_record_id.toLowerCase(),i=r.records.find(l=>(l.record_id??`${l.source}:${l.source_model_id}`).toLowerCase()===s);if(!i)return{kind:"known-unpriced",id:n};let o=vr(i),a=r.records.filter(l=>vr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:Lc(a,o,Cc)}function Qg(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let h=[e.trim().toLowerCase()];h.push(`${t.toLowerCase()}/${h[0]}`);let g=n.aliases.find(f=>h.includes(f.alias.toLowerCase()));if(g){if(g.evidence==="unresolved"||g.standard_slug===null)return{state:{kind:"unresolved",alias:g.alias},viaAlias:!0,pinRoute:null};let f=aR(n,g.standard_slug);return{state:lR(g,f,r),viaAlias:!0,pinRoute:f?.catalog_record_id?.toLowerCase()??null}}}let s=ds[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=h=>({state:h,viaAlias:!1,pinRoute:null}),l=Sr(i),c=r.records.filter(h=>h.source_model_id.toLowerCase()===i&&s.matchRow(h,[l]));if(c.length>0){let h=vr(c[0]),g=r.records.filter(f=>s.matchRow(f,[h])&&vr(f)===h);return a(Lc(g.length>0?g:c,h,Hg[t]??Cc))}let d=r.records.filter(h=>s.matchRow(h,o));if(d.length===0){let h=rR(e,r,t);return h.length>0?a({kind:"wrong-provider",declared:e,otherProviders:h}):a({kind:"unknown",declared:e})}let u=new Map;for(let h of d){let g=vr(h),f=u.get(g);f?f.push(h):u.set(g,[h])}let m=Hg[t]??Cc,p=null,_=null;for(let h of u.values()){let g=zg(h,m);(_===null||cR(g[0],_[0],m)<0)&&(p=h,_=g)}return a(Lc(p,vr(p[0]),m))}function ro(t,e,r,n){return Qg(t,e,r,n).state}function Zg(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=Qg(t,e,r,n);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(d=>d.route.toLowerCase()===o);if(c!==void 0&&Nc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Nc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function e_(t,e){let r=ds[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(vr(s));return n.size}function cR(t,e,r){let n=to(t.source)-to(e.source);if(n!==0)return n;let s=t.provider!==null&&r.includes(t.provider)?0:1,i=e.provider!==null&&r.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var qg,Gg,Jg,Vg,Kg,Yg,YA,QA,ZA,eR,ds,Hg,Cc,Oc=k(()=>{"use strict";qg=cn({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),Gg=cn({vendorPrefixes:["openai"],family:/(^|\/)(gpt-|o\d|chatgpt|ft:gpt)|openai\//,firstPartyProviders:["openai"],nonChatName:/(^|[-/])(tts|transcribe(?:-\w+)?|realtime(?:-\w+)?|search(?:-\w+)*|image(?:-\w+)?|audio(?:-\w+)?|whisper(?:-\w+)?|dall-e(?:-\w+)?|embedding|moderation)(-|$)/}),Jg=cn({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),Vg=cn({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Kg=cn({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),Yg=cn({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),YA=/\s*\(([^()]+)\)\s*$/;QA={"gemini 3.8 flash":"gemini-3.8-flash","gemini 3.7 flash":"gemini-3.7-flash","gemini 3.6 flash":"gemini-3.6-flash","gemini 3.1 pro":"gemini/gemini-3.1-pro-preview","claude sonnet 4.6":"claude-sonnet-4-6"},ZA=["gemini","google","vertex_ai-language-models","anthropic"],eR={normalize(t){let{model:e}=zA(t),r=QA[e.toLowerCase()];return r===void 0?[]:[Sr(r)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let r=Xg(t);return e.some(n=>r.has(n))}},ds={claude:qg,codex:Gg,gemini:Jg,agy:eR,kimi:Vg,qwen:Kg,hermes:Yg},Hg={claude:qg.firstPartyProviders,codex:Gg.firstPartyProviders,gemini:Jg.firstPartyProviders,agy:ZA,kimi:Vg.firstPartyProviders,qwen:Kg.firstPartyProviders,hermes:Yg.firstPartyProviders};Cc=[]});import{spawnSync as Uc}from"node:child_process";import{existsSync as s_,readFileSync as i_}from"node:fs";import{homedir as o_}from"node:os";import{dirname as hB,resolve as Fc}from"node:path";function dn(t,e){return e.code==="ETIMEDOUT"?`${t} did not respond within lint's own spawn timeout (${e.message}) \u2014 this does not mean the provider itself is unreachable, only that this specific check didn't finish in time.`:`${t} could not be run: ${e.message}`}function fR(){let t=Uc("agy",["models"],{encoding:"utf-8",timeout:mR});return{status:t.status,stdout:t.stdout??"",error:t.error}}function pR(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim(),s=n.indexOf(" ");if(s<0)continue;let i=n.slice(s+1).trim();i&&e.push(i)}return e}function hR(t){if(!t&&Dc)return Dc;let e=s=>(t||(Dc=s),s),r;try{r=(t??fR)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?dn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:dn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=pR(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function _R(){let t=Uc("codex",["debug","models"],{encoding:"utf-8",timeout:gR});return{status:t.status,stdout:t.stdout??"",error:t.error}}function yR(t){let e;try{e=JSON.parse(t)}catch{return}let r=e.models;if(!Array.isArray(r))return;let n=[];for(let s of r){if(!s||typeof s!="object")continue;let{slug:i,visibility:o}=s;typeof i=="string"&&o==="list"&&n.push(i)}return n}function ER(t){if(!t&&Mc)return Mc;let e=s=>(t||(Mc=s),s),r;try{r=(t??_R)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?dn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:dn("codex debug models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`codex debug models exited with status ${r.status??"unknown"}`});let n=yR(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}function wR(t){let e=Uc("opencode",["models",t],{encoding:"utf-8",timeout:TR});return{status:e.status,stdout:e.stdout??"",error:e.error}}function vR(t,e){if(!e&&$c.has(t))return $c.get(t);let r=i=>(e||$c.set(t,i),i),n;try{n=(e??wR)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?dn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:dn(`opencode models ${t}`,n.error)});if(n.status!==0)return r({available:!1,models:[],reason:`opencode models ${t} exited with status ${n.status??"unknown"}`});let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);return s.length===0?r({available:!1,models:[],reason:`opencode models ${t} returned no models`}):r({available:!0,models:s})}function jc(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),!n.model&&uR.has(s)&&r.push(`[${n.alias}] provider=${s} has no model= \u2014 ${s} will use its own ambient default, which cannot be linted or priced and may not be the intended one. Set model= explicitly.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s==="lmplayer"&&!n.model){r.push(`[${n.alias}] provider=lmplayer has no model= \u2014 lmplayer will choose its own default model, which may not be visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model){r.push(`[${n.alias}] provider=opencode has no model= \u2014 opencode will choose its own default model, which may not be servable and isn't visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}let i=IR(e.opencodeConfigPath);if(!i.available){r.push(`[${n.alias}] model="${n.model}" cannot be verified for opencode: ${i.reason}.`);continue}if(i.models.includes(n.model)||/^github-copilot\/(gpt|gemini|o[0-9])/.test(n.model))continue;if(!n.model.includes("/")){let l=i.models.filter(c=>c.endsWith(`/${n.model}`));r.push(l.length>0?`[${n.alias}] model="${n.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model>. Your opencode.json declares it as ${l.join(" / ")}; set model=${l[0]}.`:`[${n.alias}] model="${n.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model> (e.g. github-copilot/${n.model}). Declare it in ~/.config/opencode/opencode.json (see https://lmctl.com/examples/opencode.json).`);continue}let o=n.model.slice(0,n.model.indexOf("/")),a=vR(o,e.opencodeModelsRunner);if(a.available&&a.models.includes(n.model))continue;if(a.available&&!a.models.includes(n.model)){r.push(`[${n.alias}] model="${n.model}" was not found in opencode's LOCALLY-VISIBLE live catalog for "${o}" (checked \`opencode models ${o}\`) -- this is unresolved, not a confirmed unavailability: it could mean opencode genuinely doesn't serve this model, OR that your local catalog/auth for "${o}" is stale/incomplete. Declaring it in opencode.json may or may not help; if it doesn't, check whether a non-opencode provider serves this model directly (e.g. \`lmctl lint\` with model= against provider=codex/claude/gemini/agy).`);continue}r.push(`[${n.alias}] model="${n.model}" is not declared in your opencode.json. opencode resolves github-copilot GPT/Gemini config-free, but copilot Claude and custom providers must be declared \u2014 copy https://lmctl.com/examples/opencode.json to ~/.config/opencode/opencode.json and adjust for your account.`);continue}if(s==="kimi"){if(!n.model)continue;let i=SR(e.kimiConfigPath);i.available?i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not declared in Kimi's [models] config. Valid configured models: ${us(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for kimi: ${i.reason}.`);continue}if(s==="agy"){if(!n.model)continue;let i=hR(e.agyModelsRunner);i.available?i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in agy's live model catalog (\`agy models\`). Valid models: ${us(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||r_.includes(n.model))continue;t_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${us(t_)}. Valid server-resolved aliases (DeepSeek resolves these to its current model server-side -- pinning to a specific version instead is a DOWNGRADE, not a safer choice): ${us(r_)}. The catalog is patchable via dsh profile overlays \u2014 a model added that way warns here even though it may resolve.`);continue}if(s==="hermes"){if(!n.model)continue;let i=n.model.indexOf(":");(i<=0||i===n.model.length-1)&&r.push(`[${n.alias}] model="${n.model}" should use <provider>:<model> from Hermes's ACP catalog. lmctl checks the shape only; provider and model availability are resolved by Hermes.`);continue}if(s!=="pi"){if(s==="codex"){if(!n.model)continue;n.model===n_&&r.push(`[${n.alias}] model="${n_}" is banned as a build model (operator, 2026-09-06) -- it's a fast/cheap classification model, not intended for build work, and there's no cost reason left to reach for it. Use model=gpt-5.6-sol (or leave model= unset) for build work; if this member genuinely does non-build/classification work, this warning can be ignored.`);let i=ER(e.codexModelsRunner);if(!i.available){r.push(`[${n.alias}] model="${n.model}" cannot be verified for codex: ${i.reason}.`);continue}i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in codex's live model catalog (\`codex debug models\`). Valid models: ${us(i.models)}`);continue}n.model&&(a_.has(s)||r.push(`[${n.alias}] model="${n.model}" cannot be verified for provider "${s}": no model validation path exists for this provider.`))}}}return r}async function l_(t,e={}){let r=t.filter(o=>o.model!==void 0&&a_.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await eo();if(n.catalog===null)return{warnings:[],errors:[]};let s=[],i=[];for(let o of r){let a=o.provider.trim().toLowerCase(),l=o.model,c=ro(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let d=e_(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${d} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&dR.test(l)){let d=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${d}" instead.`)}}return{warnings:s,errors:i}}async function c_(t,e={}){return(await l_(t,e)).warnings}async function d_(t,e={}){return(await l_(t,e)).errors}function SR(t){let e=process.env.KIMI_CODE_HOME||Fc(o_(),".kimi-code"),r=t??Fc(e,"config.toml");if(!s_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=i_(r,"utf-8")}catch(i){return{available:!1,models:[],reason:`${r} could not be read: ${i instanceof Error?i.message:String(i)}`}}let s=new Set;for(let i of n.split(/\r?\n/)){if(/^\s*\[/.test(i)&&!/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.test(i))return{available:!1,models:[],reason:`${r} has an invalid TOML table header`};let o=/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(i);if(!o)continue;let a=bR(o[1]);if(o[1].trim().startsWith("models")&&a===null)return{available:!1,models:[],reason:`${r} has an invalid [models] table header`};a?.[0]==="models"&&a.length>=2&&s.add(a[1])}return s.size===0?{available:!1,models:[],reason:`${r} has no [models] entries`}:{available:!0,models:[...s].sort()}}function bR(t){let e=[],r=0;for(;r<t.length;){for(;/\s/.test(t[r]??"");)r++;if(r>=t.length)break;let n="",s=t[r]==='"'||t[r]==="'"?t[r++]:void 0;if(s){for(;r<t.length&&t[r]!==s;)s==='"'&&t[r]==="\\"&&r+1<t.length&&r++,n+=t[r++];if(t[r]!==s)return null;r++}else{for(;r<t.length&&t[r]!==".";)n+=t[r++];n=n.trim()}if(!n)return null;for(e.push(n);/\s/.test(t[r]??"");)r++;if(r>=t.length)break;if(t[r]!==".")return null;r++}return e.length>0?e:null}function IR(t){let e=t??Fc(o_(),".config","opencode","opencode.json");if(!s_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(i_(e,"utf-8"))}catch(n){return{available:!1,models:[],reason:`${e} could not be parsed: ${n instanceof Error?n.message:String(n)}`}}return{available:!0,models:xR(r)}}function xR(t){if(!Pc(t))return[];let e=no(t.provider)??no(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Pc(s))continue;let i=no(s.models)??no(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function no(t){return Pc(t)?t:null}function Pc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function us(t){return t.length>0?t.join(", "):"(none)"}var a_,dR,uR,t_,r_,n_,mR,Dc,gR,Mc,TR,$c,u_=k(()=>{"use strict";Rc();Oc();a_=new Set(Object.keys(ds).filter(t=>t!=="codex"&&t!=="kimi")),dR=/\d\.(?=\d)/,uR=new Set(["claude","codex","gemini","qwen","kimi","agy"]),t_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],r_=["deepseek-flash","deepseek-pro"],n_="gpt-5.3-codex-spark",mR=15e3;Dc=null;gR=5e3;Mc=null;TR=5e3;$c=new Map});import{homedir as kR}from"node:os";import{basename as AR}from"node:path";function m_(t,e){let r=new Set;return{text:t.replace(NR,(s,i)=>{let o=i.trim(),a=RR[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function f_(t){return{workdir:t.workdir,teamfile:t.teamfile,date:LR(t.date)}}function LR(t){return t.toISOString().slice(0,10)}var RR,NR,p_=k(()=>{"use strict";RR={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=AR(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>kR(),date:t=>t.date},NR=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var Vc={};se(Vc,{GEMINI_PROVIDER_NOTICE:()=>w_,_setAgyModelsRunnerForTests:()=>PR,_setCatalogSnapshotForTests:()=>FR,_setCodexModelsRunnerForTests:()=>UR,_setLintOpenCodeConfigProbeForTests:()=>WR,_setLintSessiondirFsOpsForTests:()=>BR,_setTeamfileSeedForTests:()=>jR,buildRootTeamRegistrationRow:()=>k_,registerRootTeam:()=>A_,runLint:()=>xr,runSeed:()=>kr,seedTeamfile:()=>so,sha256Text:()=>x_,validateMemberSpec:()=>kt});import{createHash as CR}from"node:crypto";import{accessSync as OR,constants as h_,existsSync as DR,readFileSync as E_,realpathSync as Hc,statSync as MR,writeFileSync as g_}from"node:fs";import{dirname as Ir,resolve as T_}from"node:path";function FR(t){fs=t??void 0}function b_(t){return c_(t,fs!==void 0?{snapshot:fs}:{})}function I_(t){return d_(t,fs!==void 0?{snapshot:fs}:{})}function PR(t){Gc=t??void 0}function UR(t){Jc=t??void 0}function jR(t){v_=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(bt(),lc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function BR(t){br=t===null?Xc:{...Xc,...t}}function WR(t){S_=t??Fn}async function HR(t,e,r){let n=t.filter(i=>i.teamfile===void 0&&i.provider.trim().toLowerCase()==="opencode"&&i.model!==void 0&&i.model.length>0);return(await Promise.all(n.map(async i=>({member:i,result:await S_({cwd:i.sessiondir??e,model:i.model,...i.effort!==void 0?{effort:i.effort}:{},...r!==void 0?{env:r}:{}})})))).flatMap(({member:i,result:o})=>o.status==="rejected"?[`[${i.alias}] ${o.option}="${o.value}" rejected by opencode: ${o.error}`]:[])}function XR(t,e){let r=Ir(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=T_(o);if(n.has(a))continue;let l=qR(a);l!==void 0&&(n.add(a),s.push(`${i.alias}: sessiondir ${a} is not writable (seed would fail: ${l}) \u2014 fix permissions or set a writable sessiondir`))}return s}function qR(t){try{if(br.existsSync(t)){if(!br.statSync(t).isDirectory())return"ENOTDIR";br.accessSync(t,h_.W_OK);return}let e=JR(t);if(e===void 0)return;if(!br.statSync(e).isDirectory())return"ENOTDIR";br.accessSync(e,h_.W_OK);return}catch(e){return VR(e)??"permission check failed"}}function GR(t){let e=T_(t);try{return Hc(e)}catch{return e}}function JR(t){let e=t;for(;;){try{if(br.existsSync(e))return e}catch{return}let r=Ir(e);if(r===e)return;e=r}}function VR(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}async function xr(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write($R),0;let r=oe(t,[],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
2060
2060
  `),2;if(r.positionals.length!==1)return e.stderr.write(`usage: lmctl lint <teamfile.lmctl>
2061
2061
  `),2;let n=r.positionals[0],s;try{s=await C(e,d=>ge(n,d))}catch(d){return un(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let i;try{i=Ae(s)}catch(d){return un(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let o=sa(i,Ir(s));e.stderr.write(`notice: checking teamfile and models ...
@@ -246,7 +246,7 @@ fn clamp(val, low, high) {
246
246
  `)+(T.output.length>0?`
247
247
  `:""),S=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&S===0,stdout:w,output:[...T.output],value:T.value,exit_code:S,code:S,errors:T.errors??[]};return x.toString=()=>w,x})();{let T=I.run(g,{file:E}),w=T.output.join(`
248
248
  `)+(T.output.length>0?`
249
- `:""),S=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&S===0,stdout:w,output:[...T.output],value:T.value,exit_code:S,code:S,errors:T.errors??[]};return x.toString=()=>w,x}},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 y=e.get("urlget");(!y||y.isDefault)&&this.hostFunctions.set("urlget",{fn:_=>this.isAsync?qf(_):Va(_),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:_=>{if(typeof _!="number"||!Number.isFinite(_)||_<0)throw new Error("sleep() duration must be a non-negative finite number");if(_>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,_));let m=Date.now()+_;for(;Date.now()<m;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Ne,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new Ne(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);if(!Array.isArray(n))throw new L(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){if(++n>1e6)throw new L("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(s){if(s instanceof Je)break;if(s instanceof Ve)continue;throw s}}return}case"ForStmt":{let n=new Ne(r);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new L("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof Je)break;if(!(i instanceof Ve))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new Ot(n)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new L("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new L("'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,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);if(!Array.isArray(n))throw new L(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),Ke(n,s,i),i;throw new L("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)Ke(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);if(n==null)throw new L("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:Oe(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new L(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new L("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new L(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof Dt)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>tn)throw this.callDepth--,new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",o);let l=new Ne(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Ot)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...r)}catch(l){throw l instanceof pe||l?.name==="LMScriptExit"||l?.isControlFlow?l:new L(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new L(`'${e}' is not a function`,s,i,"RUNTIME",o):new L(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new Dt(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Ne,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 r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new Ne(r);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,n);if(!Array.isArray(s))throw new L(`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;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,n));){if(++s>1e6)throw new L("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,r,n)}catch(i){if(i instanceof Je)break;if(i instanceof Ve)continue;throw i}}return}case"ForStmt":{let s=new Ne(r);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new L("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof Je)break;if(!(o instanceof Ve))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new Ot(s)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new L(`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,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new L("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,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Ke(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new L("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 L(`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],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new L("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],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new L(`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;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Ke(s,i,o),o;throw new L("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Ke(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,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=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new L("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]:Oe(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new L(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),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 L("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 L(`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,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>tn)throw this.asyncCallDepth.set(o,d-1),new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",a);let u=new Ne(this.globalEnv,!0);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof Ot)return f.value;throw f}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(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof pe||d?.name==="LMScriptExit"||d?.isControlFlow?d:new L(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new L(`'${l}' is not a function`,s,i,"RUNTIME",a):new L(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},Yf=[{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 (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",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. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{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;"}],zf=[{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("~/repos/*/*.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:"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.",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:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",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 for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",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.",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:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{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:"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:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("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:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("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:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("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 starting from start index of specified length.",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 Unicode code point 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:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{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 number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: 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, item: 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(a: array, b: array): array",description:"Concatenates two 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:"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:"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:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{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:"getstr",category:"Maps & Key-Value",signature:"getstr(obj: any, path: string|array): string",description:'Typed form of get(): reads a string field, "" when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null", not "" -- getstr never does that).',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): array",description:"Typed form of get(): reads an array field, [] when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{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",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{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 (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { 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]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...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:"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), prints "error: <message>" to stderr 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:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",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:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],Qf=[{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:"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:"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);"}];function Zf(t,e){if(e===void 0)return`${t}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${t}(${i.join(", ")}): any`}let r=Array.from({length:e.min},(i,o)=>`arg${o+1}: any`),n=e.max===void 0?[]:Array.from({length:e.max-e.min},(i,o)=>`[arg${e.min+o+1}: any]`),s=e.max===void 0?["...args: any"]:[];return`${t}(${[...r,...n,...s].join(", ")}): any`}function Ba(t,e){let r=new Date(t),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(r.getFullYear());case"%m":return n(r.getMonth()+1);case"%d":return n(r.getDate());case"%H":return n(r.getHours());case"%M":return n(r.getMinutes());case"%S":return n(r.getSeconds());case"%%":return"%";default:return s}})}function ur(t,e){let r=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(t).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[r++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}var je=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of Yf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of zf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Qf)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,r){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=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,r)}finally{this.currentRegisteringModule=n}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(r=>(r.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 r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=D.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
249
+ `:""),S=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&S===0,stdout:w,output:[...T.output],value:T.value,exit_code:S,code:S,errors:T.errors??[]};return x.toString=()=>w,x}},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 y=e.get("urlget");(!y||y.isDefault)&&this.hostFunctions.set("urlget",{fn:_=>this.isAsync?qf(_):Va(_),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:_=>{if(typeof _!="number"||!Number.isFinite(_)||_<0)throw new Error("sleep() duration must be a non-negative finite number");if(_>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,_));let m=Date.now()+_;for(;Date.now()<m;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Ne,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new Ne(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);if(!Array.isArray(n))throw new L(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){if(++n>1e6)throw new L("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(s){if(s instanceof Je)break;if(s instanceof Ve)continue;throw s}}return}case"ForStmt":{let n=new Ne(r);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new L("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof Je)break;if(!(i instanceof Ve))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new Ot(n)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new L("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new L("'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,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);if(!Array.isArray(n))throw new L(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),Ke(n,s,i),i;throw new L("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)Ke(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);if(n==null)throw new L("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:Oe(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new L(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new L("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new L(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof Dt)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>tn)throw this.callDepth--,new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",o);let l=new Ne(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Ot)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...r)}catch(l){throw l instanceof pe||l?.name==="LMScriptExit"||l?.isControlFlow?l:new L(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new L(`'${e}' is not a function`,s,i,"RUNTIME",o):new L(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new Dt(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Ne,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 r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new Ne(r);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,n);if(!Array.isArray(s))throw new L(`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;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,n));){if(++s>1e6)throw new L("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,r,n)}catch(i){if(i instanceof Je)break;if(i instanceof Ve)continue;throw i}}return}case"ForStmt":{let s=new Ne(r);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new L("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof Je)break;if(!(o instanceof Ve))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new Ot(s)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new L(`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,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new L("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,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Ke(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new L("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 L(`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],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new L("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],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new L(`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;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Ke(s,i,o),o;throw new L("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Ke(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,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=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new L("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]:Oe(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new L(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),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 L("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 L(`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,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>tn)throw this.asyncCallDepth.set(o,d-1),new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",a);let u=new Ne(this.globalEnv,!0);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof Ot)return f.value;throw f}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(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof pe||d?.name==="LMScriptExit"||d?.isControlFlow?d:new L(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new L(`'${l}' is not a function`,s,i,"RUNTIME",a):new L(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},Yf=[{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 (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",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. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{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;"}],zf=[{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("~/repos/*/*.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:"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.",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:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",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 for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",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.",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:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{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:"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:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("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:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("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:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("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 starting from start index of specified length.",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 Unicode code point 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:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{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 number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: 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, item: 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(a: array, b: array): array",description:"Concatenates two 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:"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:"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:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{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:"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:"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",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{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 (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { 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]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...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:"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), prints "error: <message>" to stderr 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:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",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:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],Qf=[{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:"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:"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);"}];function Zf(t,e){if(e===void 0)return`${t}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${t}(${i.join(", ")}): any`}let r=Array.from({length:e.min},(i,o)=>`arg${o+1}: any`),n=e.max===void 0?[]:Array.from({length:e.max-e.min},(i,o)=>`[arg${e.min+o+1}: any]`),s=e.max===void 0?["...args: any"]:[];return`${t}(${[...r,...n,...s].join(", ")}): any`}function Ba(t,e){let r=new Date(t),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(r.getFullYear());case"%m":return n(r.getMonth()+1);case"%d":return n(r.getDate());case"%H":return n(r.getHours());case"%M":return n(r.getMinutes());case"%S":return n(r.getSeconds());case"%%":return"%";default:return s}})}function ur(t,e){let r=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(t).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[r++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}var je=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of Yf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of zf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Qf)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,r){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=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,r)}finally{this.currentRegisteringModule=n}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(r=>(r.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 r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=D.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
250
250
  `)?r=r.slice(0,-2):r.endsWith(`
251
251
  `)&&(r=r.slice(0,-1)),n?r.length===0?[""]:r.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,r)=>{if(!Array.isArray(r))throw new Error("write_lines: second argument must be an array of lines");let n=r.length===0?"":r.map(String).join(`
252
252
  `)+`
@@ -255,7 +255,7 @@ fn clamp(val, low, high) {
255
255
  `:""),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:n}),l=a.output.join(`
256
256
  `)+(a.output.length>0?`
257
257
  `:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
258
- `):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>Va(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?fr(e):mr(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,r)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,r)},{min:1,max:2},"Parses JSON string into object/array, or stringifies data to JSON string"),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,r=null)=>Gf(e,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,r)=>JSON.stringify(e,null,r),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=lr(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r)=>{let n=lr(e,r);return n==null?"":String(n)},2,'Reads a string field from a map/request form; "" when missing or null (never the string "null")'),this.registerFunction("getnum",(e,r,n=0)=>{let s=lr(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=lr(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r)=>{let n=lr(e,r);return Array.isArray(n)?n:[]},2,"Reads an array field from a map/request form; [] when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
258
+ `):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>Va(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?fr(e):mr(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,r)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,r)},{min:1,max:2},"Parses JSON string into object/array, or stringifies data to JSON string"),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,r=null)=>Gf(e,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,r)=>JSON.stringify(e,null,r),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=lr(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r,n="")=>{let s=lr(e,r);return s==null?n:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,r,n=0)=>{let s=lr(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=lr(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r,n=[])=>{let s=lr(e,r);return Array.isArray(s)?s:n},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
259
259
  `):console.error(`error: ${String(r)}`),new pe(2);return e},2,'Stops the script (stderr message, exit 2) if value is missing -- "", null, [], or false -- else returns value unchanged, so it composes with getstr/getnum/getbool/getlist'),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(Oe(i,a)==null||typeof Oe(i,a)!="object")&&Ke(i,a,{}),i=Oe(i,a)}return s.length>0&&Ke(i,s[s.length-1],n),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,r)=>Array.isArray(e)?e.map(n=>Oe(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Oe(s,r)===n):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,r,n)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&Oe(i,r)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,r)=>({...e,...r}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,r)=>(e&&typeof e=="object"&&delete e[r],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...r)=>{let n=ur(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/);for(let n=r.length-1;n>=0;n--){let s=r[n].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof Dt,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>Ka(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let f=Number(u);o+=f<r.length?a(r[f]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>ur(e,r),void 0,"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax)"),this.registerFunction("regex_test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string (alias for regex_test)"),this.registerFunction("regex_match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null"),this.registerFunction("match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("search",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("regex_find_all",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...]"),this.registerFunction("findall",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all)"),this.registerFunction("regex_replace",(e,r,n,s="")=>String(e).replace(new RegExp(r,s),n),{min:3,max:4},'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence, not just the first'),this.registerFunction("split_regex",(e,r,n="")=>String(e).split(new RegExp(r,n)),{min:2,max:3},"Splits a string into an array wherever the regex pattern matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("length",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("count",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("range",(e,r,n=1)=>{let s=r===void 0?0:e,i=r===void 0?e:r,o=[];if(n>0)for(let a=s;a<i;a+=n)o.push(a);else if(n<0)for(let a=s;a>i;a+=n)o.push(a);return o},void 0,"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...r)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},void 0,"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,r)=>Math.pow(e,r),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("clock",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms (alias for clock)"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,r)=>Ba(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Ba(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,r,n)=>e?r:n,3,"Expression-level ternary: returns thenVal if cond is truthy, else elseVal"),this.registerFunction("str",e=>e===null?"null":String(e),1,"Converts value to string"),this.registerFunction("to_string",e=>e===null?"null":String(e),1,"Converts value to string (alias for str)"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof Dt?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${p}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:Zf(e,n),description:a}),this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,r){return this.initialGlobals.set(e,r),this}getGlobal(e){return this.initialGlobals.get(e)}scanAndCheck(e,r={}){try{let{program:n}=Kf(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new Hs(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof L?{ast:null,diagnostics:[{message:n.message,line:n.line,column:n.column,severity:"error",file:n.file||r.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:n instanceof Error?n.message:String(n),line:1,column:1,severity:"error",file:r.file}],hasConcurrency:!1}}}run(e,r={}){let n=[],{ast:s,diagnostics:i,hasConcurrency:o}=this.scanAndCheck(e,r);if(i.filter(c=>c.severity==="error").length>0||!s)return this.outputLogs=n,{success:!1,diagnostics:i,output:n};if(o)return this.outputLogs=n,{success:!1,diagnostics:[...i,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:r.file}],output:n};let l;try{l=new an(this.hostFunctions,u=>n.push(u),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let d=l.getRecordedErrors();return this.lastRecordedErrors=d,{success:!0,value:c,diagnostics:i,output:n,errors:d}}catch(c){let d=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=d,c instanceof pe||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let y=typeof c.exitCode=="number"?c.exitCode:0;return{success:y===0,value:y,exitCode:y,diagnostics:i,output:n,errors:d}}let u=c instanceof L?c.line:1,f=c instanceof L?c.column:1,p=c instanceof L&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new an(this.hostFunctions,d=>n.push(d),!0,this.initialGlobals,r.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof pe||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof L?l.line:1,u=l instanceof L?l.column:1,f=l instanceof L&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,severity:"error",file:f}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function ep(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
260
260
  `);let t=new je,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=t.run(`
261
261
  fn factorial(n) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lmctl-ai/lmctl",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
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",