@lmctl-ai/lmctl 0.2.480 → 0.2.481
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/lmscript.js +4 -4
- package/dist/dsl.js +4 -4
- package/package.json +1 -1
package/dist/dsl.js
CHANGED
|
@@ -160,7 +160,7 @@ _xml_ [profile="ID"] ; reads one namespace-aware XML tree, closed by end _xml_.
|
|
|
160
160
|
`;if(n==="topics")return`Topics: conditional, regex, graphql, xml, csv, list, toml, props, json, cmd, lmcode, path, methods, recover, concurrency, resources, agent-files
|
|
161
161
|
`;if(n==="regex")return`Topic: Regular expressions
|
|
162
162
|
JavaScript RegExp patterns; use regex_test, regex_find, regex_matches, regex_match, regex_find_all, pos, set_pos, regex_match_pos, regex_find_pos, regex_test_pos, regex_replace and split_regex.
|
|
163
|
-
Use raw strings for backslashes; g means global matching; y is rejected by stateless capture helpers; *_pos helpers match at pos() (sticky by default, or from pos() with g)
|
|
163
|
+
Use raw strings for backslashes; g means global matching; y is rejected by stateless capture helpers; *_pos helpers match at pos() (sticky by default, or from pos() with g), advance pos() after non-empty matches and leave it unchanged on failure. Empty matches consume no input and leave pos() at the match offset; a repeated empty match at that offset is refused, with g resuming one code unit (one code point with u/v) further on.
|
|
164
164
|
`;if(n&&i.has(n)){let l=i.get(n);return`Function: ${l.signature??l.name}
|
|
165
165
|
${s(l.module??"core")}
|
|
166
166
|
Category: ${l.category}
|
|
@@ -4325,7 +4325,7 @@ ${l}${u}^`}function poe(t,e){if(t.length<2)return t;let n=r=>[...e?.get(r.file??
|
|
|
4325
4325
|
`);if(typeof n=="object"&&n!==null){let r=Object.keys(n),s=r.map(o=>kk(o,e)).join(e),i=t.map(o=>r.map(a=>kk(Ur(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
4326
4326
|
`)}return t.map(r=>kk(r,e)).join(`
|
|
4327
4327
|
`)}function kk(t,e){let n=t==null?"":String(t);return n===""||n.includes(e)||n.includes('"')||n.includes(`
|
|
4328
|
-
`)||n.includes("\r")?`"${n.replaceAll('"','""')}"`:n}function zie(t,e){let n=(i,o=t)=>{throw new B("command: "+i,o.line,o.column,"RUNTIME",o.file)},r=(i,o)=>{if(typeof i!="string"&&typeof i!="number")return n("arguments must be strings or numbers (or a whole-word list of them)",o);let a=String(i);return a.includes("\0")?n("NUL is not allowed in argv",o):a},s=[];return t.words.forEach((i,o)=>{if(i.pieces.length===1&&typeof i.pieces[0]!="string"&&Array.isArray(e[o][0])){let l=e[o][0];o===0&&l.length===0&&n("a program is required; first-word list is empty",i);for(let c of l)s.push(r(c,i))}else s.push(e[o].map((l,c)=>r(l,typeof i.pieces[c]=="string"?i:i.pieces[c])).join(""))}),(!s.length||!s[0])&&n("a non-empty program is required"),s}function Tf(t,e,n="native"){if(typeof e!="string")throw new Error("Regex flags must be a string");let r=new Set;for(let s of e){if(!"dgimsuvy".includes(s))throw new Error(`Unsupported regex flag '${s}'`);if(r.has(s))throw new Error(`Duplicate regex flag '${s}'`);r.add(s)}if(r.has("u")&&r.has("v"))throw new Error("Regex flags cannot combine 'u' and 'v' Unicode modes");if((n==="first"||n==="all")&&r.has("y"))throw new Error("Sticky regex flag 'y' is incompatible with capture helpers that search anywhere");n==="sticky"&&!r.has("y")&&!r.has("g")&&(e+="y");try{return new RegExp(t,n==="all"&&!r.has("g")?e+"g":e)}catch(s){throw new Error(`Invalid regex pattern: ${s instanceof Error?s.message:String(s)}`)}}function v1(t){return Array.from(t,e=>e===void 0?null:e)}function Moe(t,e,n=""){let r=Tf(e,n,"first").exec(String(t));return r===null?null:v1(r)}function yHe(t,e,n=""){let r=Moe(t,e,n);return r===null?null:r[0]}function Doe(t,e,n=""){let r=Tf(e,n,"all"),s=String(t),i=n.includes("u")||n.includes("v"),o=[],a;for(;(a=r.exec(s))!==null;)if(o.push(v1(a)),a[0]===""){let l=r.lastIndex;if(l>=s.length)break;let c=s.charCodeAt(l),u=s.charCodeAt(l+1),d=i&&c>=55296&&c<=56319&&u>=56320&&u<=57343?2:1;r.lastIndex=l+d}return o}function _He(t,e,n=""){return Doe(t,e,n).map(r=>r[0])}function $oe(){return{currentPos:0,lastString:void 0,positions:new Map}}function Dy(t){let e=By.getStore()?.get(t)??t,n=Xie.get(e);return n||(n=$oe(),Xie.set(e,n)),n}function zk(t,e){if(t===null)return 0;if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=0)return t;throw new Error(`${e}: offset must be a non-negative integer or null`)}function Gie(t,...e){if(e.length===0)return t.currentPos;if(e.length===1){let i=e[0];if(i===null||typeof i=="number"){let o=zk(i,"pos");return t.positions.clear(),t.lastString=void 0,t.currentPos=o,o}if(typeof i=="string"){if(t.lastString===void 0&&!t.positions.has(i))return t.lastString=i,t.positions.set(i,t.currentPos),t.currentPos;let o=t.positions.get(i)??0;return t.lastString=i,t.currentPos=o,o}throw new Error("pos: expected (s?: string, offset?: number|null) or (offset: number|null)")}let[n,r]=e;if(typeof n!="string")throw new Error("pos: first argument must be a string when setting offset");let s=zk(r,"pos");return t.lastString=n,t.currentPos=s,t.positions.set(n,s),s}function Vie(t,...e){if(e.length===1){let i=zk(e[0],"set_pos");return t.positions.clear(),t.lastString=void 0,t.currentPos=i,i}let[n,r]=e;if(typeof n!="string")throw new Error("set_pos: first argument must be a string when two arguments are given");let s=zk(r,"set_pos");return t.lastString=n,t.currentPos=s,t.positions.set(n,s),s}function vHe(t,e){if(t.lastString===e)return t.currentPos;if(t.lastString===void 0&&!t.positions.has(e))return t.lastString=e,t.positions.set(e,t.currentPos),t.currentPos;let n=t.positions.get(e)??0;return t.lastString=e,t.currentPos=n,n}function Xk(t,e,n,r=""){let s=Tf(n,r,"sticky"),i=String(e),o=vHe(t,i);if(o>i.length)return null;s.lastIndex=o;let a=s.exec(i);if(a===null)return null;let l=s.lastIndex;if(a[0]===""&&l<i.length){let c=(r.includes("u")||r.includes("v"))&&(i.codePointAt(l)??0)>65535?2:1;l+=c}return t.lastString=i,t.currentPos=l,t.positions.set(i,l),v1(a)}function Jie(t,e,n,r=""){let s=Xk(t,e,n,r);return s===null?null:s[0]}function Kie(t,e,n,r=""){return Xk(t,e,n,r)!==null}function Zie(t,e,n){try{if(n){if(n.at(e),t!==null&&typeof t=="object"&&Rt.isProxy(t))throw Error("Dry iterable cannot be a proxy");let s=[];if(Array.isArray(t)){if(![Array.prototype,null].includes(Object.getPrototypeOf(t)))throw Error("Dry iterable must be a plain array");let i=Math.min(t.length,n.loopLimit??1/0);for(let o=0;o<i;o++){n.check();let a=Object.getOwnPropertyDescriptor(t,String(o));if(a&&!("value"in a))throw Error("Dry iterable cannot contain accessors");s.push(a?.value)}return s}if(typeof t=="string"){for(let i of t)if(n.check(),s.push(i),n.loopLimit!==void 0&&s.length===n.loopLimit)break;return s}if(t!==null&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t))){if(E1(t))throw Error("Dry iterable must be plain data");for(let i in t)if(n.check(),!!Object.hasOwn(t,i)&&(s.push(i),n.loopLimit!==void 0&&s.length===n.loopLimit))break;return s}}if(Array.isArray(t))return Array.from({length:t.length},(s,i)=>t[i]);if(typeof t=="string")return Array.from(t);if(t!==null&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.keys(t);let r=t===null?"null":t instanceof Date?"Date":typeof t;throw new B(`Cannot iterate value of type ${r}; expected list, map or string`,e.line,e.column,"RUNTIME",e.file)}catch(r){throw r instanceof B||n&&r?.isControlFlow?r:new B(`Cannot snapshot iterable: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,"RUNTIME",e.file)}}function JU(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let n of Object.keys(t)){let r=t[n];if(Array.isArray(r))for(let s of r)JU(s,e);else r&&typeof r=="object"&&JU(r,e)}}}function bf(t,e="Call to undefined function"){let n=`${e} '${t}'`;if(!Object.hasOwn(Hy,t))return n;let r=n+`; did you mean '${Hy[t]}'?`;return t==="json"?r+" Use json_stringify for serialization.":t==="count"?r+" Use count_matches for substring occurrences.":t==="parseInt"||t==="parseFloat"?r+" num uses whole-value Number conversion; it does not provide prefix parsing or integer truncation.":r}function wHe(){if(!OU){let e=new qk(bHe,"<std>").tokenize(),r=new Gk(e,"<std>").parse();for(let s of r.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);OU=r}return{kind:"Program",statements:[...OU.statements],line:1,column:1,file:"<std>"}}function Tu(t){if(sn(t))throw Error("lmcode builder is opaque");return t&&typeof t=="object"&&Gy.has(t)?Gy.get(t)():t}function KU(t){if(typeof t!="string"||!/^[_a-zA-Z]\w*(?:\.[_a-zA-Z]\w*)*$/.test(t))throw Error(`Invalid property key '${String(t)}'; use dotted identifier segments`);return t}function Vk(t,e){return e.find(n=>{let r=n.lastIndexOf(".");return n===t||r>=0&&t===n.slice(0,r+1)+n.slice(r+1).toLowerCase()})??t}function oa(t,e,n=new Set){if(t instanceof Date)return t.toISOString();if(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(t&&typeof t=="object"){if(!Array.isArray(t)&&![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw Error(`Property '${e}' has an unsupported object value`);if(n.has(t))throw Error(`Property '${e}' contains a cycle`);n.add(t);try{if(Array.isArray(t))return t.map((s,i)=>oa(s,e+"."+i,n));let r={};for(let[s,i]of Object.entries(t))Qn(r,s,oa(i,e?e+"."+s:s,n));return r}finally{n.delete(t)}}throw Error(`Property '${e}' has an unsupported value type: ${typeof t}`)}function qu(t){let e=oa(t.properties,"");if(!e||typeof e!="object"||Array.isArray(e))throw Error("Property document must be a table in "+t.path);for(let n of["Directory","NonInteractive"])if(Object.hasOwn(e,n))throw Error("Property '"+n+"' is read-only in "+t.path);return{...t,properties:e}}function wf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date)}function ZU(t,e,n,r=""){let s={};for(let[i,o]of Object.entries(t)){let a=r?r+"."+i:i,l=/^[_a-zA-Z]\w*$/.test(i)?Vk(a,e):a,c=l===a?i:l.slice(l.lastIndexOf(".")+1);if(Object.hasOwn(s,c))throw Error("Ambiguous property '"+l+"' in "+n);Qn(s,c,wf(o)?ZU(o,e,n,l):structuredClone(o))}return s}function joe(t,e,n,r,s=""){let i=structuredClone(t);for(let[o,a]of Object.entries(e)){let l=s?s+"."+o:o;if(Object.hasOwn(t,o)&&wf(t[o])!==wf(a))throw Error("Property '"+l+"' cannot merge a table and a value between "+n+" and "+r);Qn(i,o,Object.hasOwn(t,o)&&wf(t[o])&&wf(a)?joe(t[o],a,n,r,l):structuredClone(a))}return i}function Kk(t){if(t.kind==="IdentifierExpr"&&t.name==="PROPS")return"";if(t.kind==="IndexExpr"&&t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"){let e=Kk(t.target);if(e!==void 0)return e?e+"."+t.index.value:t.index.value}}function Uoe(t,e){if(t.isContainerMutation&&Soe(e[0]))throw new Error(Toe)}function NU(t,e){return Uoe(t,e),t.fn(...e)}function Pl(t={}){return Object.freeze({source_kind:t.source_kind??"unknown",script_file:t.script_file===void 0||t.script_file===null?null:le.resolve(t.script_file),source_name:t.source_name??null,run_id:t.run_id??Vy(),parent_run_id:t.parent_run_id??null})}function xk(t){for(let n of["noPreflight","dryrunTimeoutMs","onPreflight"])if(Object.hasOwn(t,n))throw Error("Removed execution option: "+n);t={...t,npmInstallSession:f_(),hostContext:{cwd:t.hostContext?.cwd??process.cwd(),env:Object.freeze({...t.hostContext?.env??process.env}),platform:t.hostContext?.platform}};let e=t.executionOrigin;return{...t,executionOrigin:e?Object.isFrozen(e)?e:Pl(e):Pl({source_kind:t.entryLocation?"file":"unknown",script_file:t.entryLocation?le.resolve(t.hostContext?.cwd??process.cwd(),t.entryLocation):null,source_name:t.file??t.entryLocation??null})}}function Qie(t){let e=[t];for(;e.length;){let n=e.pop();if(!n||typeof n!="object")continue;let r=n,s=r.kind==="CallExpr"?r.callee:r.kind==="IdentifierExpr"?r.name:null;if(s==="tool_call"||s==="tool_parse"||s==="tool_specs"||s==="llm_prompt"||s==="llm_models"||s==="llm_providers"||typeof s=="string"&&s.startsWith("agent_"))return!0;for(let i of Object.values(r))Array.isArray(i)?e.push(...i):i&&typeof i=="object"&&e.push(i)}return!1}function jy(t,e={currentPath:null}){return wu(e),{finished:!1,probe:e,errors:[],pending:t?t.split("."):[],entered:new Set,stack:[],envs:new Map,active:!1,rootTaskId:-1}}function wu(t){t&&(t.currentPath=null,delete t.firstFailure)}function b1(t){t.finished||(t.probe.firstFailure??={path:t.probe.currentPath})}function EHe(t){let e=t;return!!(t instanceof rs||e?.name==="LMScriptExit"||e?.isControlFlow)&&(typeof e?.exitCode=="number"?e.exitCode:0)===0}function eoe(t,e){let n=()=>b1(t);return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&n(),()=>e?.removeEventListener("abort",n)}function $s(t,e){e instanceof Ln||e instanceof Zn||e instanceof Yn||EHe(e)||b1(t)}function Lk(t,e){t.finished||(b1(t),t.errors.push(e))}function SHe(t,e){let n=e.resumepoint;if(n===void 0||!t.ast)return[];let r={severity:"error",line:1,column:1,file:e.file};if(typeof n!="string"||!THe.test(n))return[{...r,message:`Invalid resumepoint path: ${String(n)}; expected NAME(.NAME)*`}];if(!t.hasRecover)return[{...r,message:"Script has no recover block"}];let s=n.split(".")[0];return t.recoverLabels?.includes(s)?[]:[{...r,message:`Unknown resumepoint '${s}': no recover block declares this point`}]}function vu(t,e){let n=t.diagnostics.filter(s=>!t.resumepointDiagnostics?.includes(s)),r=SHe(t,e);return{...t,diagnostics:poe([...n,...r],t.diagnosticPaths),resumepointDiagnostics:r}}function In(t){if(t?.aborted)throw new Error("Execution aborted")}function Rn(t){return t!==null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Zk(t,e,n){if(_n(t)||_n(e??"")){let s=_n(t)?new URL(t):new URL(t,e);if(!["http:","https:"].includes(s.protocol))throw Error("Only http/https module URLs are supported");return s.hash="",s.href}let r=le.resolve(e&&e!=="<main>"&&!e.startsWith("<")?le.dirname(e):n,t);try{return q.realpathSync(r)}catch{return r}}function YU(t){let e=new Set,n=r=>{if(!(!r||typeof r!="object")){r.kind==="AssignExpr"&&e.add(r.target),r.kind==="TupleAssignExpr"&&r.targets.forEach(s=>e.add(s));for(let s of Object.values(r))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};for(let r of t.statements)(r.kind==="FunctionDeclStmt"||r.kind==="VarDeclStmt")&&e.add(r.name),r.kind==="TupleVarDeclStmt"&&r.names.forEach(s=>e.add(s)),r.kind==="ExprStmt"&&n(r.expr);return e}function kHe(t,e){let n=YU(t),r=new Set(t.statements.filter(a=>a.kind==="VarDeclStmt"&&a.constant===!0).map(a=>a.name)),s=(a,l)=>n.has(a)&&!l.locals.has(a)?e+"."+a:a,i=(a,l)=>{if(!a||typeof a!="object")return a;let c={...a};if(a.kind==="IdentifierExpr")return c.name=s(a.name,l),c;if(a.kind==="DataBlockExpr"&&a.schemaHandle&&(c.schemaHandle=s(a.schemaHandle,l)),a.kind==="AssignExpr"||a.kind==="TupleAssignExpr"){c.value=i(a.value,l);let d=(a.kind==="AssignExpr"?[a.target]:a.targets).map(p=>l.fn&&(!r.has(p)||l.locals.has(p))?(l.locals.add(p),p):s(p,l));return a.kind==="AssignExpr"?c.target=d[0]:c.targets=d,c}a.kind==="CallExpr"&&(c.callee=n.has(a.callee)&&!l.locals.has(a.callee)?e+"."+a.callee:a.callee);for(let[u,d]of Object.entries(a))u!=="callee"&&(Array.isArray(d)?c[u]=d.map(p=>p&&typeof p=="object"?i(p,l):p):d&&typeof d=="object"&&(c[u]=i(d,l)));return c},o=(a,l)=>{let c={...a};if(a.kind==="FunctionDeclStmt")return c.name=e+"."+a.name,c.body=o(a.body,{locals:new Set(a.params),root:!1,fn:!0}),c;if(a.kind==="BlockStmt"){let u={...l,locals:new Set(l.locals),root:!1};return c.statements=a.statements.map(d=>o(d,u)),c}if(a.kind==="RecoverStmt"){let u={...l,locals:new Set(l.locals),root:!1};return c.points=a.points.map(d=>({...d,statements:d.statements.map(p=>o(p,u))})),c}if(a.kind==="VarDeclStmt"||a.kind==="TupleVarDeclStmt"){a.initializer&&(c.initializer=i(a.initializer,l));let d=(a.kind==="VarDeclStmt"?[a.name]:a.names).map(p=>l.root?s(p,l):(l.locals.add(p),p));return a.kind==="VarDeclStmt"?c.name=d[0]:c.names=d,c}if(a.kind==="ForInStmt"){c.iterable=i(a.iterable,l);let u={...l,root:!1,locals:new Set(l.locals)};return u.locals.add(a.name),c.body=o(a.body,u),c}if(a.kind==="ForStmt"){let u={...l,root:!1,locals:new Set(l.locals)};return a.init&&(c.init=o(a.init,u)),a.condition&&(c.condition=i(a.condition,u)),a.update&&(c.update=i(a.update,u)),c.body=o(a.body,u),c}a.kind==="SyncAssignStmt"&&(c.target=s(a.target,l));for(let[u,d]of Object.entries(a))u==="target"&&a.kind==="SyncAssignStmt"||d&&typeof d=="object"&&(c[u]=d.kind?.endsWith("Stmt")?o(d,l):i(d,l));return c};return{...t,statements:t.statements.map(a=>o(a,{locals:new Set,root:!0,fn:!1}))}}function*Foe(t,e){let n=e.file??"<main>",r=e.baseDir??(e.file&&!_n(e.file)?le.dirname(le.resolve(e.file)):process.cwd()),s=[],i=new Map,o=new Map,a=[],l=new Map([[n,[]]]);try{let c=(g,h)=>{let y=new qk(g,h),v;try{v=y.tokenize()}finally{s.push(...y.diagnostics)}return new Gk(v,h).parse()};function*u(g,h){let y=g.statements.find(_=>_.kind==="PackageStmt");if(y&&g.statements[0]!==y)throw new B("package must be the first statement in its file",y.line,y.column,"CHECKER",h);if(g.statements.filter(_=>_.kind==="PackageStmt").length>1)throw new B("Only one package declaration is allowed",y.line,y.column,"CHECKER",h);if(y?.kind==="PackageStmt"){if(YU(g).has(y.name))throw new B("Package name collision: "+y.name+" is also a module variable/function",y.line,y.column,"CHECKER",h);let _=o.get(y.name);if(_&&_.location!==h)throw new B("Duplicate package "+y.name+": "+_.location+" and "+h,y.line,y.column,"CHECKER",h);o.set(y.name,{location:h,members:[...YU(g)].map(b=>y.name+"."+b)}),g=kHe(g,y.name)}let v=[];for(let _ of g.statements){if(_.kind!=="ImportStmt"){v.push(_);continue}if(/^(?:native:|@|github:)/.test(_.path)||/(?:^|[\\/])(?:[^/\\]*\.)?cli\.schema\.[^/\\]+\.json$/.test(_.path))throw new B("Removed module import "+JSON.stringify(_.path)+"; use a source import or an lmcode host (load_schema / run_lmcode)",_.line,_.column,"CHECKER",_.file??h);let b;try{b=Zk(_.path,h===d?e.baseDir?_n(r)?new URL("__entry__.lms",r.endsWith("/")?r:r+"/").href:le.join(r,"__entry__.lms"):d:h,r)}catch(T){throw new B("Cannot resolve import "+_.path+": "+String(T),_.line,_.column,"CHECKER",h)}if(i.get(b)==="loading")throw new B("Import cycle: "+h+" -> "+b,_.line,_.column,"CHECKER",h);if(i.get(b)==="loaded")continue;let w=yield{location:b,specifier:_.path,from:h,node:_};if(b=w.location,i.get(b)==="loading")throw new B("Import cycle: "+h+" -> "+b,_.line,_.column,"CHECKER",h);i.get(b)!=="loaded"&&(l.set(b,[...l.get(h)??[],_.line,_.column]),i.set(b,"loading"),a.push(b),v.push(...yield*u(c(w.source,b),b)),i.set(b,"loaded"))}return v}let d=e.entryLocation??n;try{d!=="<main>"&&!d.startsWith("<")&&(d=Zk(d,void 0,r))}catch{}l.set(d,[]),i.set(d,"loading"),a.push(d);let p=yield*u(c(t,n),d);i.set(d,"loaded");let f=g=>{if(!g||typeof g!="object")return g;let h={...g};if(g.kind==="IndexExpr"&&g.target.kind==="IdentifierExpr"&&o.has(g.target.name)&&g.index.kind==="LiteralExpr"&&typeof g.index.value=="string")return{kind:"IdentifierExpr",name:g.target.name+"."+g.index.value,line:g.line,column:g.column,file:g.file};if(g.kind==="MethodCallExpr"&&g.receiver.kind==="IdentifierExpr"&&o.has(g.receiver.name))return{kind:"CallExpr",callee:g.receiver.name+"."+g.method,args:g.args.map(f),line:g.receiver.line,column:g.receiver.column,file:g.file};if(g.kind==="IndexAssignExpr"&&g.target.kind==="IdentifierExpr"&&o.has(g.target.name)&&g.index.kind==="LiteralExpr"&&typeof g.index.value=="string")return{kind:"AssignExpr",target:g.target.name+"."+g.index.value,value:f(g.value),line:g.line,column:g.column,file:g.file};if(g.kind==="SyncIndexAssignStmt"&&g.target.kind==="IdentifierExpr"&&o.has(g.target.name)&&g.index.kind==="LiteralExpr"&&typeof g.index.value=="string")return{kind:"SyncAssignStmt",target:g.target.name+"."+g.index.value,value:f(g.value),line:g.line,column:g.column,file:g.file};for(let[y,v]of Object.entries(g))Array.isArray(v)?h[y]=v.map(f):v&&typeof v=="object"&&(h[y]=f(v));return h};return{program:{kind:"Program",statements:[...e.noStdlib?[]:wHe().statements,...p.map(f)],line:1,column:1,file:n},loadedFiles:a,diagnostics:s,packages:o,diagnosticPaths:l}}catch(c){throw c instanceof zy?c:new zy(c,s,l,n)}}function Boe(t,e){try{if(e.moduleResolver){let n=e.moduleResolver(t.specifier,t.from);return{location:Zk(n.path,void 0,e.baseDir??process.cwd()),source:n.source}}if(_n(t.location))throw Error("URL imports require runAsync or scanAndCheckAsync");return{location:t.location,source:q.readFileSync(t.location,"utf8")}}catch(n){throw new B("Cannot load module "+t.location+": "+String(n instanceof Error?n.message:n),t.node.line,t.node.column,"CHECKER",t.node.file)}}function xHe(t,e={}){let n=Foe(t,e),r=n.next();for(;!r.done;){let s;try{s=Boe(r.value,e)}catch(i){r=n.throw(i);continue}r=n.next(s)}return r.value}async function IHe(t,e={}){let n=e.importCache??new Map,r=Foe(t,e),s=r.next();for(;!s.done;){let i=s.value,o=n.get(i.location);o||(o=(async()=>{if(!_n(i.location)||e.moduleResolver)return Boe(i,e);try{let l=await fetch(i.location,{...e.importTimeoutMs===void 0?{}:{signal:AbortSignal.timeout(e.importTimeoutMs)}});if(!l.ok)throw Error("HTTP "+l.status);return{location:i.location,source:await l.text()}}catch(l){throw new B("Cannot load module URL "+i.location+": "+String(l instanceof Error?l.message:l),i.node.line,i.node.column,"CHECKER",i.node.file)}})(),n.set(i.location,o));let a;try{a=await o}catch(l){s=r.throw(l);continue}s=r.next(a)}return s.value}function ku(t){switch(t.kind){case"IdentifierExpr":return t.name;case"LiteralExpr":return typeof t.value=="string"?JSON.stringify(t.value):String(t.value);case"GroupingExpr":return ku(t.expression);case"IndexExpr":{let e=ku(t.target);return t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"&&(t.dot||/^[A-Za-z_][A-Za-z0-9_]*$/.test(t.index.value))?e+"."+t.index.value:e+"["+ku(t.index)+"]"}case"CallExpr":return t.callee+"(...)";case"MethodCallExpr":return ku(t.receiver)+"."+t.method+"(...)";case"ArrayExpr":case"TupleExpr":return"[...]";case"ObjectExpr":return"{...}";default:return"the value"}}function toe(t,e,n){if(ya(t)||fo(t))throw new B("Data is opaque; use value(), toString() or toLmcode(name)",n.line,n.column,"RUNTIME",n.file);if(kf(t))throw new B("schema descriptor is opaque",n.line,n.column,"RUNTIME",n.file);if(sn(t))throw new B("lmcode builder is opaque; use its add method",n.line,n.column,"RUNTIME",n.file);if(io(t))throw new B(zl,n.line,n.column,"RUNTIME",n.file);let r=wB(t,e,ku(n.target));if(r.ok)return r.value;throw new B(r.message,n.line,n.column,"RUNTIME",n.file)}function noe(t,e,n){if(kf(t))throw new B("schema descriptor is opaque",e.line,e.column,"RUNTIME",e.file);if(sn(t)&&e.method!=="add")throw new B("lmcode builder exposes only add(program, fragment)",e.line,e.column,"RUNTIME",e.file);if(io(t))throw new B(zl,e.line,e.column,"RUNTIME",e.file);let r=vB(t,{isResource:Ft,isProperties:s=>eo.has(s),isFunction:s=>s instanceof Qi,isLmcodeBuilder:sn,isData:ya,isDataSource:fo});return bB(r,e.method,t,n,s=>{throw new B(s,e.line,e.column,"RUNTIME",e.file)})}function roe(t,e){try{return Zx(t.raw,e)}catch(n){throw n instanceof qs?new B(n.message,t.line,t.column,"RUNTIME",t.file):n}}function e1(t,e){t&&typeof t=="object"&&Gy.has(t)&&(t=Gy.get(t)());let n,r=o=>{throw n=e?new B("Cannot interpolate value: "+o,e.line,e.column,"RUNTIME",e.file):new Error("Cannot convert value to text: "+o),n},s=new Set,i=o=>{if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="boolean")return String(o);if(typeof o=="number")return Number.isFinite(o)?String(o):r("nonfinite number");if(typeof o!="object")return r(o===void 0?"undefined":"unsupported "+typeof o);if(sn(o))return r("lmcode builder is opaque");let a=Array.isArray(o),l=Object.getPrototypeOf(o);if(io(t))return r(zl);if(!a&&l!==Object.prototype&&l!==null)return r("unsupported host object");if(s.has(o))return r("cyclic collection");s.add(o);try{if(Reflect.ownKeys(o).some(p=>typeof p=="symbol"))return r("symbol-keyed collection");let c=a?Array.from({length:o.length},(p,f)=>String(f)):Object.keys(o);if(a&&c.some(p=>!Object.hasOwn(o,p)))return r("sparse array");let u=Object.getOwnPropertyNames(o).filter(p=>!a||p!=="length");if(u.length!==c.length||u.some(p=>!c.includes(p)))return r("extra or non-enumerable collection property");let d=[];for(let p of c){let f=Object.getOwnPropertyDescriptor(o,p);if(!f)return r("sparse array");if(!Object.hasOwn(f,"value"))return r("accessor property");let m=i(f.value);d.push(a?m:JSON.stringify(p)+":"+m)}return a?"["+d.join(",")+"]":"{"+d.join(",")+"}"}finally{s.delete(o)}};try{return typeof t=="string"?t:i(t)}catch(o){if(o===n)throw o;return r("serialization failed: "+(o instanceof Error?o.message:String(o)))}}function LU(t){if(t!==null&&typeof t=="object"){let e=Object.getPrototypeOf(t);if(Array.isArray(t)||e===Object.prototype||e===null)return e1(t)}return t===null?"null":String(t)}function Hoe(t,e,n){if(typeof t!="string"||t==="")throw new Error(n+": the database path must be a non-empty string");if(/^file:/i.test(t)||t.includes("\0"))throw new Error(n+": the database path must be a plain file path (URI names such as file:... are not supported)");let r=process.getBuiltinModule?.("node:sqlite");if(!r)throw new Error(n+": node:sqlite is not available in this Node.js (needs Node 22.5 or newer)");if(e&&!q.existsSync(t))throw new Error(n+": database file not found (a read never creates one)");return new r.DatabaseSync(t,{readOnly:e})}function RHe(t,e){let n=0,r=!1;for(;n<t.length;){let s=t[n];if(s==="'"||s==='"'||s==="`"||s==="["){if(r)throw new Error(e+": one statement per call (found text after a ';'); split it into separate calls");let i=s==="["?"]":s;for(n++;n<t.length&&t[n]!==i;)n++;n++;continue}if(s==="-"&&t[n+1]==="-"){for(;n<t.length&&t[n]!==`
|
|
4328
|
+
`)||n.includes("\r")?`"${n.replaceAll('"','""')}"`:n}function zie(t,e){let n=(i,o=t)=>{throw new B("command: "+i,o.line,o.column,"RUNTIME",o.file)},r=(i,o)=>{if(typeof i!="string"&&typeof i!="number")return n("arguments must be strings or numbers (or a whole-word list of them)",o);let a=String(i);return a.includes("\0")?n("NUL is not allowed in argv",o):a},s=[];return t.words.forEach((i,o)=>{if(i.pieces.length===1&&typeof i.pieces[0]!="string"&&Array.isArray(e[o][0])){let l=e[o][0];o===0&&l.length===0&&n("a program is required; first-word list is empty",i);for(let c of l)s.push(r(c,i))}else s.push(e[o].map((l,c)=>r(l,typeof i.pieces[c]=="string"?i:i.pieces[c])).join(""))}),(!s.length||!s[0])&&n("a non-empty program is required"),s}function Tf(t,e,n="native"){if(typeof e!="string")throw new Error("Regex flags must be a string");let r=new Set;for(let s of e){if(!"dgimsuvy".includes(s))throw new Error(`Unsupported regex flag '${s}'`);if(r.has(s))throw new Error(`Duplicate regex flag '${s}'`);r.add(s)}if(r.has("u")&&r.has("v"))throw new Error("Regex flags cannot combine 'u' and 'v' Unicode modes");if((n==="first"||n==="all")&&r.has("y"))throw new Error("Sticky regex flag 'y' is incompatible with capture helpers that search anywhere");n==="sticky"&&!r.has("y")&&!r.has("g")&&(e+="y");try{return new RegExp(t,n==="all"&&!r.has("g")?e+"g":e)}catch(s){throw new Error(`Invalid regex pattern: ${s instanceof Error?s.message:String(s)}`)}}function v1(t){return Array.from(t,e=>e===void 0?null:e)}function Moe(t,e,n=""){let r=Tf(e,n,"first").exec(String(t));return r===null?null:v1(r)}function yHe(t,e,n=""){let r=Moe(t,e,n);return r===null?null:r[0]}function Doe(t,e,n=""){let r=Tf(e,n,"all"),s=String(t),i=n.includes("u")||n.includes("v"),o=[],a;for(;(a=r.exec(s))!==null;)if(o.push(v1(a)),a[0]===""){let l=r.lastIndex;if(l>=s.length)break;let c=s.charCodeAt(l),u=s.charCodeAt(l+1),d=i&&c>=55296&&c<=56319&&u>=56320&&u<=57343?2:1;r.lastIndex=l+d}return o}function _He(t,e,n=""){return Doe(t,e,n).map(r=>r[0])}function $oe(){return{currentPos:0,lastString:void 0,positions:new Map,emptyAt:new Map}}function Dy(t){let e=By.getStore()?.get(t)??t,n=Xie.get(e);return n||(n=$oe(),Xie.set(e,n)),n}function zk(t,e){if(t===null)return 0;if(typeof t=="number"&&Number.isSafeInteger(t)&&t>=0)return t;throw new Error(`${e}: offset must be a non-negative integer or null`)}function Gie(t,...e){if(e.length===0)return t.currentPos;if(e.length===1){let i=e[0];if(i===null||typeof i=="number"){let o=zk(i,"pos");return t.positions.clear(),t.emptyAt.clear(),t.lastString=void 0,t.currentPos=o,o}if(typeof i=="string"){if(t.lastString===void 0&&!t.positions.has(i))return t.lastString=i,t.positions.set(i,t.currentPos),t.currentPos;let o=t.positions.get(i)??0;return t.lastString=i,t.currentPos=o,o}throw new Error("pos: expected (s?: string, offset?: number|null) or (offset: number|null)")}let[n,r]=e;if(typeof n!="string")throw new Error("pos: first argument must be a string when setting offset");let s=zk(r,"pos");return t.lastString=n,t.currentPos=s,t.positions.set(n,s),t.emptyAt.delete(n),s}function Vie(t,...e){if(e.length===1){if(typeof e[0]=="string")throw new Error("set_pos: a string target requires an offset: set_pos(s, offset)");let i=zk(e[0],"set_pos");return t.positions.clear(),t.emptyAt.clear(),t.lastString=void 0,t.currentPos=i,i}let[n,r]=e;if(typeof n!="string")throw new Error("set_pos: first argument must be a string when two arguments are given");let s=zk(r,"set_pos");return t.lastString=n,t.currentPos=s,t.positions.set(n,s),t.emptyAt.delete(n),s}function vHe(t,e){if(t.lastString===e)return t.currentPos;if(t.lastString===void 0&&!t.positions.has(e))return t.lastString=e,t.positions.set(e,t.currentPos),t.currentPos;let n=t.positions.get(e)??0;return t.lastString=e,t.currentPos=n,n}function Xk(t,e,n,r=""){let s=Tf(n,r,"sticky"),i=String(e),o=vHe(t,i);if(o>i.length)return null;s.lastIndex=o;let a=s.exec(i);if(a!==null&&a.index<o&&s.global&&!s.sticky&&(s.lastIndex=o+1,a=s.exec(i)),a===null||a.index<o)return null;if(a[0]===""&&a.index===o&&t.emptyAt.get(i)===o){if(!s.global||s.sticky)return null;let c=r.includes("u")||r.includes("v");if(s.lastIndex=o+(c&&(i.codePointAt(o)??0)>65535?2:1),a=s.exec(i),a===null)return null}let l=s.lastIndex;return a[0]===""?t.emptyAt.set(i,l):t.emptyAt.delete(i),t.lastString=i,t.currentPos=l,t.positions.set(i,l),v1(a)}function Jie(t,e,n,r=""){let s=Xk(t,e,n,r);return s===null?null:s[0]}function Kie(t,e,n,r=""){return Xk(t,e,n,r)!==null}function Zie(t,e,n){try{if(n){if(n.at(e),t!==null&&typeof t=="object"&&Rt.isProxy(t))throw Error("Dry iterable cannot be a proxy");let s=[];if(Array.isArray(t)){if(![Array.prototype,null].includes(Object.getPrototypeOf(t)))throw Error("Dry iterable must be a plain array");let i=Math.min(t.length,n.loopLimit??1/0);for(let o=0;o<i;o++){n.check();let a=Object.getOwnPropertyDescriptor(t,String(o));if(a&&!("value"in a))throw Error("Dry iterable cannot contain accessors");s.push(a?.value)}return s}if(typeof t=="string"){for(let i of t)if(n.check(),s.push(i),n.loopLimit!==void 0&&s.length===n.loopLimit)break;return s}if(t!==null&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t))){if(E1(t))throw Error("Dry iterable must be plain data");for(let i in t)if(n.check(),!!Object.hasOwn(t,i)&&(s.push(i),n.loopLimit!==void 0&&s.length===n.loopLimit))break;return s}}if(Array.isArray(t))return Array.from({length:t.length},(s,i)=>t[i]);if(typeof t=="string")return Array.from(t);if(t!==null&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.keys(t);let r=t===null?"null":t instanceof Date?"Date":typeof t;throw new B(`Cannot iterate value of type ${r}; expected list, map or string`,e.line,e.column,"RUNTIME",e.file)}catch(r){throw r instanceof B||n&&r?.isControlFlow?r:new B(`Cannot snapshot iterable: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,"RUNTIME",e.file)}}function JU(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let n of Object.keys(t)){let r=t[n];if(Array.isArray(r))for(let s of r)JU(s,e);else r&&typeof r=="object"&&JU(r,e)}}}function bf(t,e="Call to undefined function"){let n=`${e} '${t}'`;if(!Object.hasOwn(Hy,t))return n;let r=n+`; did you mean '${Hy[t]}'?`;return t==="json"?r+" Use json_stringify for serialization.":t==="count"?r+" Use count_matches for substring occurrences.":t==="parseInt"||t==="parseFloat"?r+" num uses whole-value Number conversion; it does not provide prefix parsing or integer truncation.":r}function wHe(){if(!OU){let e=new qk(bHe,"<std>").tokenize(),r=new Gk(e,"<std>").parse();for(let s of r.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);OU=r}return{kind:"Program",statements:[...OU.statements],line:1,column:1,file:"<std>"}}function Tu(t){if(sn(t))throw Error("lmcode builder is opaque");return t&&typeof t=="object"&&Gy.has(t)?Gy.get(t)():t}function KU(t){if(typeof t!="string"||!/^[_a-zA-Z]\w*(?:\.[_a-zA-Z]\w*)*$/.test(t))throw Error(`Invalid property key '${String(t)}'; use dotted identifier segments`);return t}function Vk(t,e){return e.find(n=>{let r=n.lastIndexOf(".");return n===t||r>=0&&t===n.slice(0,r+1)+n.slice(r+1).toLowerCase()})??t}function oa(t,e,n=new Set){if(t instanceof Date)return t.toISOString();if(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(t&&typeof t=="object"){if(!Array.isArray(t)&&![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw Error(`Property '${e}' has an unsupported object value`);if(n.has(t))throw Error(`Property '${e}' contains a cycle`);n.add(t);try{if(Array.isArray(t))return t.map((s,i)=>oa(s,e+"."+i,n));let r={};for(let[s,i]of Object.entries(t))Qn(r,s,oa(i,e?e+"."+s:s,n));return r}finally{n.delete(t)}}throw Error(`Property '${e}' has an unsupported value type: ${typeof t}`)}function qu(t){let e=oa(t.properties,"");if(!e||typeof e!="object"||Array.isArray(e))throw Error("Property document must be a table in "+t.path);for(let n of["Directory","NonInteractive"])if(Object.hasOwn(e,n))throw Error("Property '"+n+"' is read-only in "+t.path);return{...t,properties:e}}function wf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date)}function ZU(t,e,n,r=""){let s={};for(let[i,o]of Object.entries(t)){let a=r?r+"."+i:i,l=/^[_a-zA-Z]\w*$/.test(i)?Vk(a,e):a,c=l===a?i:l.slice(l.lastIndexOf(".")+1);if(Object.hasOwn(s,c))throw Error("Ambiguous property '"+l+"' in "+n);Qn(s,c,wf(o)?ZU(o,e,n,l):structuredClone(o))}return s}function joe(t,e,n,r,s=""){let i=structuredClone(t);for(let[o,a]of Object.entries(e)){let l=s?s+"."+o:o;if(Object.hasOwn(t,o)&&wf(t[o])!==wf(a))throw Error("Property '"+l+"' cannot merge a table and a value between "+n+" and "+r);Qn(i,o,Object.hasOwn(t,o)&&wf(t[o])&&wf(a)?joe(t[o],a,n,r,l):structuredClone(a))}return i}function Kk(t){if(t.kind==="IdentifierExpr"&&t.name==="PROPS")return"";if(t.kind==="IndexExpr"&&t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"){let e=Kk(t.target);if(e!==void 0)return e?e+"."+t.index.value:t.index.value}}function Uoe(t,e){if(t.isContainerMutation&&Soe(e[0]))throw new Error(Toe)}function NU(t,e){return Uoe(t,e),t.fn(...e)}function Pl(t={}){return Object.freeze({source_kind:t.source_kind??"unknown",script_file:t.script_file===void 0||t.script_file===null?null:le.resolve(t.script_file),source_name:t.source_name??null,run_id:t.run_id??Vy(),parent_run_id:t.parent_run_id??null})}function xk(t){for(let n of["noPreflight","dryrunTimeoutMs","onPreflight"])if(Object.hasOwn(t,n))throw Error("Removed execution option: "+n);t={...t,npmInstallSession:f_(),hostContext:{cwd:t.hostContext?.cwd??process.cwd(),env:Object.freeze({...t.hostContext?.env??process.env}),platform:t.hostContext?.platform}};let e=t.executionOrigin;return{...t,executionOrigin:e?Object.isFrozen(e)?e:Pl(e):Pl({source_kind:t.entryLocation?"file":"unknown",script_file:t.entryLocation?le.resolve(t.hostContext?.cwd??process.cwd(),t.entryLocation):null,source_name:t.file??t.entryLocation??null})}}function Qie(t){let e=[t];for(;e.length;){let n=e.pop();if(!n||typeof n!="object")continue;let r=n,s=r.kind==="CallExpr"?r.callee:r.kind==="IdentifierExpr"?r.name:null;if(s==="tool_call"||s==="tool_parse"||s==="tool_specs"||s==="llm_prompt"||s==="llm_models"||s==="llm_providers"||typeof s=="string"&&s.startsWith("agent_"))return!0;for(let i of Object.values(r))Array.isArray(i)?e.push(...i):i&&typeof i=="object"&&e.push(i)}return!1}function jy(t,e={currentPath:null}){return wu(e),{finished:!1,probe:e,errors:[],pending:t?t.split("."):[],entered:new Set,stack:[],envs:new Map,active:!1,rootTaskId:-1}}function wu(t){t&&(t.currentPath=null,delete t.firstFailure)}function b1(t){t.finished||(t.probe.firstFailure??={path:t.probe.currentPath})}function EHe(t){let e=t;return!!(t instanceof rs||e?.name==="LMScriptExit"||e?.isControlFlow)&&(typeof e?.exitCode=="number"?e.exitCode:0)===0}function eoe(t,e){let n=()=>b1(t);return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&n(),()=>e?.removeEventListener("abort",n)}function $s(t,e){e instanceof Ln||e instanceof Zn||e instanceof Yn||EHe(e)||b1(t)}function Lk(t,e){t.finished||(b1(t),t.errors.push(e))}function SHe(t,e){let n=e.resumepoint;if(n===void 0||!t.ast)return[];let r={severity:"error",line:1,column:1,file:e.file};if(typeof n!="string"||!THe.test(n))return[{...r,message:`Invalid resumepoint path: ${String(n)}; expected NAME(.NAME)*`}];if(!t.hasRecover)return[{...r,message:"Script has no recover block"}];let s=n.split(".")[0];return t.recoverLabels?.includes(s)?[]:[{...r,message:`Unknown resumepoint '${s}': no recover block declares this point`}]}function vu(t,e){let n=t.diagnostics.filter(s=>!t.resumepointDiagnostics?.includes(s)),r=SHe(t,e);return{...t,diagnostics:poe([...n,...r],t.diagnosticPaths),resumepointDiagnostics:r}}function In(t){if(t?.aborted)throw new Error("Execution aborted")}function Rn(t){return t!==null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function Zk(t,e,n){if(_n(t)||_n(e??"")){let s=_n(t)?new URL(t):new URL(t,e);if(!["http:","https:"].includes(s.protocol))throw Error("Only http/https module URLs are supported");return s.hash="",s.href}let r=le.resolve(e&&e!=="<main>"&&!e.startsWith("<")?le.dirname(e):n,t);try{return q.realpathSync(r)}catch{return r}}function YU(t){let e=new Set,n=r=>{if(!(!r||typeof r!="object")){r.kind==="AssignExpr"&&e.add(r.target),r.kind==="TupleAssignExpr"&&r.targets.forEach(s=>e.add(s));for(let s of Object.values(r))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};for(let r of t.statements)(r.kind==="FunctionDeclStmt"||r.kind==="VarDeclStmt")&&e.add(r.name),r.kind==="TupleVarDeclStmt"&&r.names.forEach(s=>e.add(s)),r.kind==="ExprStmt"&&n(r.expr);return e}function kHe(t,e){let n=YU(t),r=new Set(t.statements.filter(a=>a.kind==="VarDeclStmt"&&a.constant===!0).map(a=>a.name)),s=(a,l)=>n.has(a)&&!l.locals.has(a)?e+"."+a:a,i=(a,l)=>{if(!a||typeof a!="object")return a;let c={...a};if(a.kind==="IdentifierExpr")return c.name=s(a.name,l),c;if(a.kind==="DataBlockExpr"&&a.schemaHandle&&(c.schemaHandle=s(a.schemaHandle,l)),a.kind==="AssignExpr"||a.kind==="TupleAssignExpr"){c.value=i(a.value,l);let d=(a.kind==="AssignExpr"?[a.target]:a.targets).map(p=>l.fn&&(!r.has(p)||l.locals.has(p))?(l.locals.add(p),p):s(p,l));return a.kind==="AssignExpr"?c.target=d[0]:c.targets=d,c}a.kind==="CallExpr"&&(c.callee=n.has(a.callee)&&!l.locals.has(a.callee)?e+"."+a.callee:a.callee);for(let[u,d]of Object.entries(a))u!=="callee"&&(Array.isArray(d)?c[u]=d.map(p=>p&&typeof p=="object"?i(p,l):p):d&&typeof d=="object"&&(c[u]=i(d,l)));return c},o=(a,l)=>{let c={...a};if(a.kind==="FunctionDeclStmt")return c.name=e+"."+a.name,c.body=o(a.body,{locals:new Set(a.params),root:!1,fn:!0}),c;if(a.kind==="BlockStmt"){let u={...l,locals:new Set(l.locals),root:!1};return c.statements=a.statements.map(d=>o(d,u)),c}if(a.kind==="RecoverStmt"){let u={...l,locals:new Set(l.locals),root:!1};return c.points=a.points.map(d=>({...d,statements:d.statements.map(p=>o(p,u))})),c}if(a.kind==="VarDeclStmt"||a.kind==="TupleVarDeclStmt"){a.initializer&&(c.initializer=i(a.initializer,l));let d=(a.kind==="VarDeclStmt"?[a.name]:a.names).map(p=>l.root?s(p,l):(l.locals.add(p),p));return a.kind==="VarDeclStmt"?c.name=d[0]:c.names=d,c}if(a.kind==="ForInStmt"){c.iterable=i(a.iterable,l);let u={...l,root:!1,locals:new Set(l.locals)};return u.locals.add(a.name),c.body=o(a.body,u),c}if(a.kind==="ForStmt"){let u={...l,root:!1,locals:new Set(l.locals)};return a.init&&(c.init=o(a.init,u)),a.condition&&(c.condition=i(a.condition,u)),a.update&&(c.update=i(a.update,u)),c.body=o(a.body,u),c}a.kind==="SyncAssignStmt"&&(c.target=s(a.target,l));for(let[u,d]of Object.entries(a))u==="target"&&a.kind==="SyncAssignStmt"||d&&typeof d=="object"&&(c[u]=d.kind?.endsWith("Stmt")?o(d,l):i(d,l));return c};return{...t,statements:t.statements.map(a=>o(a,{locals:new Set,root:!0,fn:!1}))}}function*Foe(t,e){let n=e.file??"<main>",r=e.baseDir??(e.file&&!_n(e.file)?le.dirname(le.resolve(e.file)):process.cwd()),s=[],i=new Map,o=new Map,a=[],l=new Map([[n,[]]]);try{let c=(g,h)=>{let y=new qk(g,h),v;try{v=y.tokenize()}finally{s.push(...y.diagnostics)}return new Gk(v,h).parse()};function*u(g,h){let y=g.statements.find(_=>_.kind==="PackageStmt");if(y&&g.statements[0]!==y)throw new B("package must be the first statement in its file",y.line,y.column,"CHECKER",h);if(g.statements.filter(_=>_.kind==="PackageStmt").length>1)throw new B("Only one package declaration is allowed",y.line,y.column,"CHECKER",h);if(y?.kind==="PackageStmt"){if(YU(g).has(y.name))throw new B("Package name collision: "+y.name+" is also a module variable/function",y.line,y.column,"CHECKER",h);let _=o.get(y.name);if(_&&_.location!==h)throw new B("Duplicate package "+y.name+": "+_.location+" and "+h,y.line,y.column,"CHECKER",h);o.set(y.name,{location:h,members:[...YU(g)].map(b=>y.name+"."+b)}),g=kHe(g,y.name)}let v=[];for(let _ of g.statements){if(_.kind!=="ImportStmt"){v.push(_);continue}if(/^(?:native:|@|github:)/.test(_.path)||/(?:^|[\\/])(?:[^/\\]*\.)?cli\.schema\.[^/\\]+\.json$/.test(_.path))throw new B("Removed module import "+JSON.stringify(_.path)+"; use a source import or an lmcode host (load_schema / run_lmcode)",_.line,_.column,"CHECKER",_.file??h);let b;try{b=Zk(_.path,h===d?e.baseDir?_n(r)?new URL("__entry__.lms",r.endsWith("/")?r:r+"/").href:le.join(r,"__entry__.lms"):d:h,r)}catch(T){throw new B("Cannot resolve import "+_.path+": "+String(T),_.line,_.column,"CHECKER",h)}if(i.get(b)==="loading")throw new B("Import cycle: "+h+" -> "+b,_.line,_.column,"CHECKER",h);if(i.get(b)==="loaded")continue;let w=yield{location:b,specifier:_.path,from:h,node:_};if(b=w.location,i.get(b)==="loading")throw new B("Import cycle: "+h+" -> "+b,_.line,_.column,"CHECKER",h);i.get(b)!=="loaded"&&(l.set(b,[...l.get(h)??[],_.line,_.column]),i.set(b,"loading"),a.push(b),v.push(...yield*u(c(w.source,b),b)),i.set(b,"loaded"))}return v}let d=e.entryLocation??n;try{d!=="<main>"&&!d.startsWith("<")&&(d=Zk(d,void 0,r))}catch{}l.set(d,[]),i.set(d,"loading"),a.push(d);let p=yield*u(c(t,n),d);i.set(d,"loaded");let f=g=>{if(!g||typeof g!="object")return g;let h={...g};if(g.kind==="IndexExpr"&&g.target.kind==="IdentifierExpr"&&o.has(g.target.name)&&g.index.kind==="LiteralExpr"&&typeof g.index.value=="string")return{kind:"IdentifierExpr",name:g.target.name+"."+g.index.value,line:g.line,column:g.column,file:g.file};if(g.kind==="MethodCallExpr"&&g.receiver.kind==="IdentifierExpr"&&o.has(g.receiver.name))return{kind:"CallExpr",callee:g.receiver.name+"."+g.method,args:g.args.map(f),line:g.receiver.line,column:g.receiver.column,file:g.file};if(g.kind==="IndexAssignExpr"&&g.target.kind==="IdentifierExpr"&&o.has(g.target.name)&&g.index.kind==="LiteralExpr"&&typeof g.index.value=="string")return{kind:"AssignExpr",target:g.target.name+"."+g.index.value,value:f(g.value),line:g.line,column:g.column,file:g.file};if(g.kind==="SyncIndexAssignStmt"&&g.target.kind==="IdentifierExpr"&&o.has(g.target.name)&&g.index.kind==="LiteralExpr"&&typeof g.index.value=="string")return{kind:"SyncAssignStmt",target:g.target.name+"."+g.index.value,value:f(g.value),line:g.line,column:g.column,file:g.file};for(let[y,v]of Object.entries(g))Array.isArray(v)?h[y]=v.map(f):v&&typeof v=="object"&&(h[y]=f(v));return h};return{program:{kind:"Program",statements:[...e.noStdlib?[]:wHe().statements,...p.map(f)],line:1,column:1,file:n},loadedFiles:a,diagnostics:s,packages:o,diagnosticPaths:l}}catch(c){throw c instanceof zy?c:new zy(c,s,l,n)}}function Boe(t,e){try{if(e.moduleResolver){let n=e.moduleResolver(t.specifier,t.from);return{location:Zk(n.path,void 0,e.baseDir??process.cwd()),source:n.source}}if(_n(t.location))throw Error("URL imports require runAsync or scanAndCheckAsync");return{location:t.location,source:q.readFileSync(t.location,"utf8")}}catch(n){throw new B("Cannot load module "+t.location+": "+String(n instanceof Error?n.message:n),t.node.line,t.node.column,"CHECKER",t.node.file)}}function xHe(t,e={}){let n=Foe(t,e),r=n.next();for(;!r.done;){let s;try{s=Boe(r.value,e)}catch(i){r=n.throw(i);continue}r=n.next(s)}return r.value}async function IHe(t,e={}){let n=e.importCache??new Map,r=Foe(t,e),s=r.next();for(;!s.done;){let i=s.value,o=n.get(i.location);o||(o=(async()=>{if(!_n(i.location)||e.moduleResolver)return Boe(i,e);try{let l=await fetch(i.location,{...e.importTimeoutMs===void 0?{}:{signal:AbortSignal.timeout(e.importTimeoutMs)}});if(!l.ok)throw Error("HTTP "+l.status);return{location:i.location,source:await l.text()}}catch(l){throw new B("Cannot load module URL "+i.location+": "+String(l instanceof Error?l.message:l),i.node.line,i.node.column,"CHECKER",i.node.file)}})(),n.set(i.location,o));let a;try{a=await o}catch(l){s=r.throw(l);continue}s=r.next(a)}return s.value}function ku(t){switch(t.kind){case"IdentifierExpr":return t.name;case"LiteralExpr":return typeof t.value=="string"?JSON.stringify(t.value):String(t.value);case"GroupingExpr":return ku(t.expression);case"IndexExpr":{let e=ku(t.target);return t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"&&(t.dot||/^[A-Za-z_][A-Za-z0-9_]*$/.test(t.index.value))?e+"."+t.index.value:e+"["+ku(t.index)+"]"}case"CallExpr":return t.callee+"(...)";case"MethodCallExpr":return ku(t.receiver)+"."+t.method+"(...)";case"ArrayExpr":case"TupleExpr":return"[...]";case"ObjectExpr":return"{...}";default:return"the value"}}function toe(t,e,n){if(ya(t)||fo(t))throw new B("Data is opaque; use value(), toString() or toLmcode(name)",n.line,n.column,"RUNTIME",n.file);if(kf(t))throw new B("schema descriptor is opaque",n.line,n.column,"RUNTIME",n.file);if(sn(t))throw new B("lmcode builder is opaque; use its add method",n.line,n.column,"RUNTIME",n.file);if(io(t))throw new B(zl,n.line,n.column,"RUNTIME",n.file);let r=wB(t,e,ku(n.target));if(r.ok)return r.value;throw new B(r.message,n.line,n.column,"RUNTIME",n.file)}function noe(t,e,n){if(kf(t))throw new B("schema descriptor is opaque",e.line,e.column,"RUNTIME",e.file);if(sn(t)&&e.method!=="add")throw new B("lmcode builder exposes only add(program, fragment)",e.line,e.column,"RUNTIME",e.file);if(io(t))throw new B(zl,e.line,e.column,"RUNTIME",e.file);let r=vB(t,{isResource:Ft,isProperties:s=>eo.has(s),isFunction:s=>s instanceof Qi,isLmcodeBuilder:sn,isData:ya,isDataSource:fo});return bB(r,e.method,t,n,s=>{throw new B(s,e.line,e.column,"RUNTIME",e.file)})}function roe(t,e){try{return Zx(t.raw,e)}catch(n){throw n instanceof qs?new B(n.message,t.line,t.column,"RUNTIME",t.file):n}}function e1(t,e){t&&typeof t=="object"&&Gy.has(t)&&(t=Gy.get(t)());let n,r=o=>{throw n=e?new B("Cannot interpolate value: "+o,e.line,e.column,"RUNTIME",e.file):new Error("Cannot convert value to text: "+o),n},s=new Set,i=o=>{if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="boolean")return String(o);if(typeof o=="number")return Number.isFinite(o)?String(o):r("nonfinite number");if(typeof o!="object")return r(o===void 0?"undefined":"unsupported "+typeof o);if(sn(o))return r("lmcode builder is opaque");let a=Array.isArray(o),l=Object.getPrototypeOf(o);if(io(t))return r(zl);if(!a&&l!==Object.prototype&&l!==null)return r("unsupported host object");if(s.has(o))return r("cyclic collection");s.add(o);try{if(Reflect.ownKeys(o).some(p=>typeof p=="symbol"))return r("symbol-keyed collection");let c=a?Array.from({length:o.length},(p,f)=>String(f)):Object.keys(o);if(a&&c.some(p=>!Object.hasOwn(o,p)))return r("sparse array");let u=Object.getOwnPropertyNames(o).filter(p=>!a||p!=="length");if(u.length!==c.length||u.some(p=>!c.includes(p)))return r("extra or non-enumerable collection property");let d=[];for(let p of c){let f=Object.getOwnPropertyDescriptor(o,p);if(!f)return r("sparse array");if(!Object.hasOwn(f,"value"))return r("accessor property");let m=i(f.value);d.push(a?m:JSON.stringify(p)+":"+m)}return a?"["+d.join(",")+"]":"{"+d.join(",")+"}"}finally{s.delete(o)}};try{return typeof t=="string"?t:i(t)}catch(o){if(o===n)throw o;return r("serialization failed: "+(o instanceof Error?o.message:String(o)))}}function LU(t){if(t!==null&&typeof t=="object"){let e=Object.getPrototypeOf(t);if(Array.isArray(t)||e===Object.prototype||e===null)return e1(t)}return t===null?"null":String(t)}function Hoe(t,e,n){if(typeof t!="string"||t==="")throw new Error(n+": the database path must be a non-empty string");if(/^file:/i.test(t)||t.includes("\0"))throw new Error(n+": the database path must be a plain file path (URI names such as file:... are not supported)");let r=process.getBuiltinModule?.("node:sqlite");if(!r)throw new Error(n+": node:sqlite is not available in this Node.js (needs Node 22.5 or newer)");if(e&&!q.existsSync(t))throw new Error(n+": database file not found (a read never creates one)");return new r.DatabaseSync(t,{readOnly:e})}function RHe(t,e){let n=0,r=!1;for(;n<t.length;){let s=t[n];if(s==="'"||s==='"'||s==="`"||s==="["){if(r)throw new Error(e+": one statement per call (found text after a ';'); split it into separate calls");let i=s==="["?"]":s;for(n++;n<t.length&&t[n]!==i;)n++;n++;continue}if(s==="-"&&t[n+1]==="-"){for(;n<t.length&&t[n]!==`
|
|
4329
4329
|
`;)n++;continue}if(s==="/"&&t[n+1]==="*"){let i=t.indexOf("*/",n+2);n=i<0?t.length:i+2;continue}if(s===";"){r=!0,n++;continue}if(r&&!/\s/.test(s))throw new Error(e+": one statement per call (found text after a ';'); split it into separate calls");n++}}function Woe(t,e){let n=(r,s)=>{if(r===null||typeof r=="string")return r;if(typeof r=="number"){if(!Number.isFinite(r))throw new Error(e+": parameter "+s+" is not a finite number");return r}if(typeof r=="boolean")return r?1:0;throw new Error(e+": parameter "+s+" must be a string, number, boolean or null (lists and maps are not values; use json_stringify)")};if(t==null)return[];if(Array.isArray(t))return t.map((r,s)=>n(r,"#"+(s+1)));if(typeof t=="object"){let r={};for(let[s,i]of Object.entries(t))r[s]=n(i,s);return r}throw new Error(e+": parameters must be a list (positional ?) or a map (named :name)")}function qoe(t,e,n){if(typeof e!="string"||e.trim()==="")throw new Error(n+": the SQL must be a non-empty string");return RHe(e,n),t.prepare(e)}function zoe(t){let e=/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*([A-Za-z]+)/.exec(t);return e?e[1].toUpperCase():""}function AHe(t,e,n){if(typeof e=="string"&&!["SELECT","WITH","VALUES"].includes(zoe(e)))throw new Error("sql_read: only SELECT (or WITH / VALUES) statements; VACUUM, ATTACH, PRAGMA and writes are not reads (use SELECT ... FROM pragma_xxx() for pragmas, sql_exec for writes)");let r=Hoe(t,!0,"sql_read");try{let s=qoe(r,e,"sql_read"),i=Woe(n,"sql_read"),o=[];for(let a of Array.isArray(i)?s.iterate(...i):s.iterate(i)){let l={};for(let[c,u]of Object.entries(a)){if(u instanceof Uint8Array)throw new Error("sql_read: column "+c+" holds a BLOB; CAST("+c+" AS TEXT) or select a text column");l[c]=u}o.push(l)}return o}finally{r.close()}}function CHe(t,e,n){if(typeof e=="string"&&!soe.includes(zoe(e)))throw new Error("sql_exec: only "+soe.join(" / ")+" statements; VACUUM, ATTACH, PRAGMA and SELECT are refused (VACUUM INTO and ATTACH name a second file that would bypass the state-database guard; read with sql_read)");if(typeof t=="string"&&t!==""){let s=process.env.LMCTL_DB||$y.join(process.env.HOME||"",".lmctl","state.db"),i=a=>{try{return q.realpathSync(a)}catch{let l=$y.resolve(a),c=$y.dirname(l);return c===l?l:$y.join(i(c),$y.basename(l))}},o=(a,l)=>{try{let c=q.statSync(a),u=q.statSync(l);return c.dev===u.dev&&c.ino===u.ino}catch{return!1}};if(i(t)===i(s)||o(t,s))throw new Error("sql_exec: refuses the lmctl state database ("+s+"); it is live fleet data, read it with sql_read")}let r=Hoe(t,!1,"sql_exec");try{let s=qoe(r,e,"sql_exec"),i=Woe(n,"sql_exec"),o=Array.isArray(i)?s.run(...i):s.run(i);return{changes:Number(o.changes),last_insert_rowid:Number(o.lastInsertRowid)}}finally{r.close()}}function Goe(t){switch(t){case"boolean":return!0;case"number":return 0;case"string":return"";case"array":return[];case"map":return{};case"SystemResult":return{...Xoe};case"null":case void 0:default:return null}}function w1(t){if(!t)return null;let e=t.trim(),n=e.toLowerCase();return{int:"number",float:"number",bool:"boolean",boolean:"boolean",list:"array",array:"array",map:"map",object:"map"}[n]??e}function r1(t){return typeof t=="object"&&t?Object.freeze({min:t.min,...t.max===void 0?{}:{max:t.max}}):t}function PU(t){if(t)return Object.freeze({...t,parameters:t.parameters?Object.freeze(t.parameters.map(e=>Object.freeze({...e}))):void 0,returns:t.returns?Object.freeze({...t.returns}):void 0})}function s1(t){return Object.freeze({...t,values:t.values?Object.freeze([...t.values]):void 0,keys:t.keys?Object.freeze(t.keys.map(e=>Object.freeze({...e,values:e.values?Object.freeze([...e.values]):void 0}))):void 0})}function go(t,e,n,r,s){if(r!==void 0&&typeof r!="string")throw Error(`Function '${t}' returnType must be a string`);let i=(n??[]).map(s1);for(let d=0;d<i.length;d++){let p=i[d];if(Object.hasOwn(p,"default"))throw Error(`Function '${t}' host parameter defaults are unsupported`);if(p.optional!==void 0&&typeof p.optional!="boolean")throw Error(`Function '${t}' optional must be boolean`);if(p.rest!==void 0&&typeof p.rest!="boolean")throw Error(`Function '${t}' rest must be boolean`);if(p.rest&&(p.optional||d!==i.length-1))throw Error(`Function '${t}' rest parameter must be last and required`);if(p.optional&&i.slice(d+1).some(f=>!f.optional&&!f.rest))throw Error(`Function '${t}' has a required parameter after an optional parameter`)}let o=i.filter(d=>!d.optional&&!d.rest).length,a=e??(i.length?{min:o,...i.some(d=>d.rest)?{}:{max:i.length}}:void 0);if(i.some(d=>d.rest)&&a!==void 0){let d=typeof a=="number"?a:a.min,p=typeof a=="number"?a:a.max;if(d!==o||p!==void 0)throw Error(`Function '${t}' arity does not match its declared parameters`)}let l=i,c=a,u=w1(r??s?.returns?.type);return Object.freeze({name:t,nativeParams:Object.freeze(i),publicParams:Object.freeze(l),nativeArity:r1(a),publicArity:r1(c),returnType:u})}function Ik(t){if(t!==void 0&&typeof t!="function")throw Error("Host dryRun must be a function");return t}function Uy(t,e){let n=t.signature??go("<host>",t.arity,t.params,t.returnType,t.doc),r=n.publicArity,s=typeof r=="number"?r:r?.max,i=typeof r=="number"?r:r?.min;if(i!==void 0&&e.length<i||s!==void 0&&e.length>s)throw new Error(`Function '${n.name}' expects ${i??0}..${s??"unlimited"} public argument(s), but received ${e.length}`);return[...e]}function MU(t){let e=[],n=[{value:t}];for(;n.length;){let r=n.pop();if("text"in r){e.push(r.text);continue}let s=r.value;if(s===null||typeof s!="object"){e.push(JSON.stringify(s)??"null");continue}let i=Array.isArray(s),o=i?Array.from({length:s.length},(a,l)=>String(l)):Object.keys(s).filter(a=>{let l=Object.getOwnPropertyDescriptor(s,a);return!("value"in l)||l.value!==void 0});e.push(i?"[":"{"),n.push({text:i?"]":"}"});for(let a=o.length-1;a>=0;a--){let l=o[a],c=Object.getOwnPropertyDescriptor(s,l);a<o.length-1&&n.push({text:","}),n.push({value:c?"value"in c?c.value:{$type:"accessor"}:null}),i||n.push({text:JSON.stringify(l)+":"})}}return e.join("")}function Oie(t,e="text"){let{version:n,status:r,entries:s,stop:i,diagnostics:o}=t;if(e==="json")return MU({version:n,status:r,entries:s,stop:i,diagnostics:o});let a=l=>/[\x00-\x1f\x7f\u2028\u2029]/.test(l)?JSON.stringify(l).replace(/[\u007f\u2028\u2029]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0")):l;return["PLAN "+r,...s.map(l=>String(l.seq)+". "+a(l.file)+":"+l.line+":"+l.column+" "+(l.kind==="loop"?l.message:l.kind==="lmcode-host-dry"?"dry host run (simulated) "+a(l.host??"")+" "+MU({argv:l.argv,slots:l.slots,envelope:l.envelope,stdout:l.stdout,stderr:l.stderr}):l.kind+" "+a(l.function)+" "+MU(l.arguments)+(l.output===void 0?"":" => "+JSON.stringify(l.output))))].join(`
|
|
4330
4330
|
`)}function OHe(t){if(!(t instanceof Fr)&&(t instanceof rs||t?.name==="LMScriptExit"||t?.isControlFlow)&&t.resourceFailure===void 0)return typeof t.exitCode=="number"?t.exitCode:0}function Re(t){return t[n1]}function ioe(t,e,n,r){if(!r||!eo.has(t))return Ur(t,e);r.at(n);try{return Ur(t,e)}catch(s){throw new B(s instanceof Error?s.message:String(s),n.line,n.column,"RUNTIME",n.file)}}function Sf(t,e=new Map){if(typeof t=="function")throw Error("Dry input cannot contain native functions");if(t===null||typeof t!="object"||ya(t)||fo(t)||Ft(t)||io(t)||kf(t)||sn(t))return t;if(eo.has(t))return Sf(Tu(t),e);if(Rt.isProxy(t))throw Error("Dry input cannot be a proxy");if(e.has(t))return e.get(t);if(!Array.isArray(t)&&Object.getPrototypeOf(t)!==Qi.prototype&&![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw Error("Dry input must be plain data");let n=Array.isArray(t)?new Array(t.length):Object.create(Object.getPrototypeOf(t));e.set(t,n);for(let r of Reflect.ownKeys(t)){if(Array.isArray(t)&&r==="length")continue;let s=Object.getOwnPropertyDescriptor(t,r);if(!("value"in s))throw Error("Dry input cannot contain accessors");Object.defineProperty(n,r,{value:Sf(s.value,e),writable:!0,enumerable:s.enumerable,configurable:!0})}return n}function NHe(t){if(typeof t[0]=="number")return!0;if(typeof t[0]!="string")return!1;try{let e=q.statSync(t[0]);return!e.isFile()&&!e.isDirectory()}catch{return!1}}function di(t){return Voe.add(t),t}function xn(t){return di(t)}function ex(t){return t.map(e=>typeof e=="object"?JSON.stringify(e):String(e)).join(" ")}function Pk(t,e,n,r="<passive-load>"){return{executionOrigin:e.executionOrigin,functionName:r,cwd:e.hostContext?.cwd??process.cwd(),env:t.environment,platform:t.platform,signal:e.signal,propertyStore:e.propertyStore,now:t.wallClock,record:(s,i,o,a)=>t.record(s,t.snapshot(i),n,o,a),reportRecordedError:s=>t.recordError(s,n),output:(s,i,o)=>{t.record(s,t.snapshot(o??[i]),n,"handled",void 0,!1,i)},warning:s=>t.recordWarning(s,n),fail:s=>t.fail(s,n),exit:s=>{throw t.finishExit(s,n),new Fr("script exit with code "+s)}}}function ooe(t,e,n,r,s,i={}){if(s.failure)throw new Fr(s.failure.message);s.at(r);let o=Uy(t,e),a=t.returnsResource?void 0:t.dryRun;if(a)return Uoe(t,o),Eu(Sf(e))&&s.fail("Dry host arguments contain a live or unsupported capability",r),Voe.has(a)||s.record(n,s.snapshot(o),r,"handled"),{skip:!1,invoke:()=>a(o,Pk(s,i,r,n))};let l=t.returnsResource?"null":t.signature?.returnType??w1(t.returnType);return s.record(n,n==="set_env"?[s.snapshot(e[0]),"<redacted>"]:t.dryArgs?s.snapshot(t.dryArgs(o)):s.snapshot(o),r,"dummy"),{skip:!0,value:Goe(l??void 0)}}function Su(t){return{returnsResource:t.returnsResource===!0||void 0,usesResource:t.usesResource===!0||void 0,closesResource:t.closesResource===!0||void 0}}function aoe(){return Joe>0}function Ft(t){return Koe.has(t)}function Rk(t){let e=[];for(let n=t;n;n=n.parent)e.push(n.key);return e.reverse().map(n=>typeof n=="symbol"?`[${String(n)}]`:/^(0|[1-9]\d*)$/.test(n)?`[${String(n)}]`:/^[A-Za-z_$][\w$]*$/.test(n)?`.${String(n)}`:`[${JSON.stringify(n)}]`).join("")}function E1(t){if(typeof t=="function")return"a function";if(Rt.isMap(t)||Rt.isSet(t)||Rt.isWeakMap(t)||Rt.isWeakSet(t))return"a native collection";if(Rt.isPromise(t)||Rt.isDate(t)||Rt.isRegExp(t)||Rt.isBoxedPrimitive(t)||Rt.isNativeError(t))return"a native object";if(Rt.isArrayBufferView(t)||Rt.isAnyArrayBuffer(t))return"binary data";if(Rt.isMapIterator(t)||Rt.isSetIterator(t)||Rt.isGeneratorObject(t)||Rt.isModuleNamespaceObject(t)||Rt.isExternal(t))return"a native object";if(Object.getPrototypeOf(t)===null)try{return WeakRef.prototype.deref.call(t),"a native object"}catch{}}function Eu(t,e=1/0){if(Ft(t))return t;if(t===null||typeof t!="object"&&typeof t!="function")return;let n=new Set([t]),r=[t],s=[void 0],i=0;for(;r.length>0;){let o=r.pop(),a=s.pop();if(Rt.isProxy(o))return{refused:"uninspectable",path:Rk(a),reason:"a proxy"};if(kf(o)||sn(o)||io(o))continue;let l=E1(o);if(l)return{refused:"uninspectable",path:Rk(a),reason:l};let c=Object.getPrototypeOf(o),u=c===Array.prototype&&Array.isArray(o);if(!u&&c!==Object.prototype&&c!==null&&c!==Qi.prototype)return{refused:"uninspectable",path:Rk(a),reason:"not plain data"};if(i+=u?o.length+1:1,i>e)return{refused:"too large"};let d=Reflect.ownKeys(o);if(i+=u?Math.max(0,d.length-o.length):d.length,i>e)return{refused:"too large"};for(let p=0;p<d.length;p++){let f=d[p],m=Reflect.getOwnPropertyDescriptor(o,f);if(!("value"in m))return{refused:"uninspectable",path:Rk({parent:a,key:f}),reason:"an accessor property"};let g=m.value;if(Ft(g))return g;g!==null&&(typeof g=="object"||typeof g=="function")&&!n.has(g)&&(n.add(g),r.push(g),s.push({parent:a,key:f}))}}}function Ak(t,e){return t.refused==="too large"?`The ${e} result is too large to inspect for resources (over the explicit caller budget) and is refused`:`The ${e} result is an uninspectable value at result${t.path} (${t.reason}); results must be plain data`}function PHe(t){for(let e=0;e<t.length;e++)if(Ft(t[e]))return!0;return!1}function Ki(){return Zoe.getStore()}function bu(t){if(t instanceof rs)return t.resourceFailure;if(!(t instanceof Ln||t instanceof Zn||t instanceof Yn))return t}function jHe(t,e){if(typeof t!="number"||!Number.isFinite(t)||typeof e!="string")throw new Error("strftime: expected epoch milliseconds first and format string second");let n=new Date(t);if(!Number.isFinite(n.getTime()))throw new Error("strftime: invalid epoch milliseconds");let r=i=>String(i).padStart(2,"0"),s={"%Y":String(n.getFullYear()),"%m":r(n.getMonth()+1),"%d":r(n.getDate()),"%H":r(n.getHours()),"%M":r(n.getMinutes()),"%S":r(n.getSeconds()),"%%":"%"};return e.replace(/%[YmdHMS%]/g,i=>s[i])}function Mk(t,e,n="sprintf"){let r=0;return String(t).replace(/%(-?0?)(\d+)?(?:\.(\d+))?([sdf%])|%/g,(s,i,o,a,l)=>{if(s==="%%")return"%";if(!l||l==="%")throw new Error(`${n}: unsupported or malformed directive`);if(r>=e.length)throw new Error(`${n}: missing value for ${s}`);let c=o===void 0?0:Number(o),u=a===void 0?void 0:Number(a);if(!Number.isSafeInteger(c)||u!==void 0&&!Number.isSafeInteger(u))throw new Error(`${n}: width and precision must be non-negative safe integers`);if(l==="f"&&u!==void 0&&u>100)throw new Error(`${n}: float precision must be from 0 to 100 (native toFixed range)`);let d=e[r++],p;if(l==="s")p=d!==null&&typeof d=="object"?JSON.stringify(d):String(d),u!==void 0&&(p=p.slice(0,u));else{let f=Number(d);if(!Number.isFinite(f))throw new Error(`${n}: numeric directive needs a finite number`);if(l==="f")p=u===void 0?String(f):f.toFixed(u);else{let m=Math.trunc(f);p=BigInt(Math.abs(m)).toString().padStart(u??0,"0"),m<0&&(p="-"+p)}}return i.includes("-")?p.padEnd(c," "):l!=="s"&&i.includes("0")&&!(l==="d"&&u!==void 0)?p.startsWith("-")?"-"+p.slice(1).padStart(Math.max(0,c-1),"0"):p.padStart(c,"0"):p.padStart(c," ")})}async function UHe(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
4331
4331
|
`);let t=new ta,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let r=t.run(`
|
|
@@ -4822,7 +4822,7 @@ fn clamp(val, low, high) {
|
|
|
4822
4822
|
`)+(O.output.length>0?`
|
|
4823
4823
|
`:""),C=O.exitCode!==void 0?O.exitCode:O.success&&!O.errors?.length?0:1,D={success:O.success&&C===0,stdout:A,output:[...O.output],value:O.value??null,exit_code:C,code:C,errors:O.errors??[]};for(let j of[...O.errors??[],...O.diagnostics.filter(H=>H.severity==="error").map(H=>H.message)])this.recordedErrors.push(j);return D})();{let O=S.run(L,{file:N,entryLocation:N,executionOrigin:Pl({source_kind:"file",script_file:N,source_name:N,parent_run_id:this.executionOrigin?.run_id}),signal:this.abortSignal,platform:this.platform,hostContext:x,propertyStore:this.compileOptions?.propertyStore}),P=O.stdout??O.output.join(`
|
|
4824
4824
|
`)+(O.output.length>0?`
|
|
4825
|
-
`:""),A=O.exitCode!==void 0?O.exitCode:O.success&&!O.errors?.length?0:1,C={success:O.success&&A===0,stdout:P,output:[...O.output],value:O.value??null,exit_code:A,code:A,errors:O.errors??[]};for(let D of[...O.errors??[],...O.diagnostics.filter(j=>j.severity==="error").map(j=>j.message)])this.recordedErrors.push(D);return C}},arity:_?.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 b=e.get("http_get");(!b||b.isDefault)&&this.hostFunctions.set("http_get",{...b,fn:T=>this.isAsync?JBe(T):xoe(T),arity:b?.arity??1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let w=e.get("sleep_ms");(!w||w.isDefault)&&this.hostFunctions.set("sleep_ms",{...w,fn:T=>{if(typeof T!="number"||!Number.isFinite(T)||T<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(T>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(x=>setTimeout(x,T));let k=Date.now()+T;for(;Date.now()<k;);return null},arity:w?.arity??1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new mr,this.initialGlobals)for(let[r,s]of this.initialGlobals.entries())this.globalEnv.define(r,s);this.userFunctions.clear(),this.callDepth=0;for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.userFunctions.set(r.name,r);let n;for(let r of e.statements)r.kind!=="FunctionDeclStmt"&&(n=this.execStmt(r,this.globalEnv));return this.checkRootRemainder(e),n}enterRecover(e,n){if(n)throw new B("recover cannot be entered inside a parallel task",e.line,e.column,"RUNTIME",e.file);let r=this.recovery;if(r.entered.has(e))throw new B("recover statement already entered during this run",e.line,e.column,"RUNTIME",e.file);if(r.entered.add(e),r.active=!0,r.pending.length===0)return{start:0,consumed:!1};let s=r.pending.shift(),i=e.points.findIndex(o=>o.name===s);if(i<0)throw new B(`Unknown resumepoint '${s}' in entered recover; available: ${e.points.map(o=>o.name).join(", ")}`,e.line,e.column,"RUNTIME",e.file);return{start:i,consumed:!0}}enterPoint(e,n){this.recovery.stack.length=e,this.recovery.stack.push(n),this.publishResumepoint()}leaveRecover(e){this.recovery.stack.length=e,this.publishResumepoint()}publishResumepoint(){this.recovery.probe.currentPath=this.recovery.stack.length>0?this.recovery.stack.join("."):null,this.globalEnv.define("RESUMEPOINT",this.recovery.stack.length>0?this.recovery.stack.join("."):null)}checkRemainder(e){if(In(this.abortSignal),this.recovery.pending.length>0)throw new B(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(In(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new B(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRecoverRead(e,n,r,s){let i=this.recoverScopedReads.get(r);if(!i)return;let o=this.recovery.envs.get(i);if(o&&n.resolveBinding(e)?.env!==o)throw new B(`Variable '${e}' was read before its binding was initialized`,s.line,s.column,"RUNTIME",s.file)}recoverWriteScope(e,n){let r=this.recoverScopedWrites.get(n)?.get(e);return r?this.recovery.envs.get(r):void 0}execStmt(e,n){let r=this.tracer;if(!r||e.kind==="BlockStmt"||e.kind==="FunctionDeclStmt"||e.kind==="ImportStmt"||e.kind==="PackageStmt")return this.execStmtCore(e,n);r.stmt(e,n),e.kind==="BreakStmt"?r.jump("break",e):e.kind==="ContinueStmt"&&r.jump("continue",e);try{return this.execStmtCore(e,n)}catch(s){throw s instanceof Ln?e.kind==="ReturnStmt"&&r.jump("return",e):s instanceof Zn||s instanceof Yn||r.raise(s,e),s}}execStmtCore(e,n){switch(this.dry?.at(e),In(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let r=new mr(n);for(let s of e.statements)this.execStmt(s,r);return}case"VarDeclStmt":{let r=null;return e.initializer&&(r=this.evalExpr(e.initializer,n)),e.constant?(r=Fk(r),n.defineConst(e.name,r),r):(n.define(e.name,r),r)}case"TupleVarDeclStmt":{let r=this.evalExpr(e.initializer,n);if(!Array.isArray(r))throw new B(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?(this.tracer?.branch("then",e.thenBranch,n),this.execStmt(e.thenBranch,n)):e.elseBranch?(this.tracer?.branch("else",e.elseBranch,n),this.execStmt(e.elseBranch,n)):void 0}case"WhileStmt":{let r=0,s=this.tracer,i=s?.loopEnter("while",e),o="done";try{for(;!this.dry?.loop(r,e)&&this.isTruthy(this.evalExpr(e.condition,n));){r++,s?.loopIter(i,r,e,n);try{this.execStmt(e.body,n)}catch(a){if(a instanceof Zn){o="break";break}if(a instanceof Yn)continue;throw a}}}catch(a){throw o=a instanceof Ln?"return":"raise",a}finally{s?.loopExit(i,r,o)}return}case"ForInStmt":{let r=Zie(this.evalExpr(e.iterable,n),e,this.dry),s=0,i=this.tracer,o=i?.loopEnter("foreach",e),a="done";try{for(let l=0;(l<r.length||this.dry?.loopLimit!==void 0&&s===this.dry.loopLimit)&&!this.dry?.loop(s,e);l++){let c=r[l];s++;let u=new mr(n);u.define(e.name,c),i?.loopIter(o,s,e,u);try{if(e.body.kind==="BlockStmt")for(let d of e.body.statements)this.execStmt(d,u);else this.execStmt(e.body,u)}catch(d){if(d instanceof Zn){a="break";break}if(d instanceof Yn)continue;throw d}}}catch(l){throw a=l instanceof Ln?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ForStmt":{let r=new mr(n);e.init&&this.execStmt(e.init,r);let s=0,i=this.tracer,o=i?.loopEnter("for",e),a="done";try{for(;!this.dry?.loop(s,e);){if(e.condition){let l=this.evalExpr(e.condition,r);if(!this.isTruthy(l))break}s++,i?.loopIter(o,s,e,r);try{this.execStmt(e.body,r)}catch(l){if(l instanceof Zn){a="break";break}if(!(l instanceof Yn))throw l}if(this.dry?.loop(s,e))break;e.update&&this.evalExpr(e.update,r)}}catch(l){throw a=l instanceof Ln?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new Ln(r)}case"BreakStmt":throw new Zn;case"ContinueStmt":throw new Yn;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new B("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let r=this.evalExpr(e.expr,n);return Sk(this.invokeNamed("system",[r],n,e.expr.line,e.expr.column,e.expr.file))}return Uie(e.expr)?Sk(this.evalExpr(e.expr,n)):this.evalExpr(e.expr,n)}case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new mr(n);this.recovery.envs.set(e,s);let i=this.recovery.stack.length;try{for(let o=r.start;o<e.points.length;o++){let a=e.points[o];this.enterPoint(i,a.name);for(let l of a.statements)this.execStmt(l,s);r.consumed&&o===r.start&&this.checkRemainder(a)}}catch(o){throw $s(this.recovery,o),o}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(In(this.abortSignal),e.kind){case"CommandExpr":{let r=[];for(let i of e.words){let o=[];for(let a of i.pieces)o.push(typeof a=="string"?a:this.evalExpr(a.expression,n));r.push(o)}let s=zie(e,r);return e.mode==="cmd"?s:this.invokeNamed("system",[s],n,e.line,e.column,e.file)}case"InterpolatedStringExpr":{let r="";for(let s of e.parts)r+=typeof s=="string"?s:e1(this.evalExpr(s.expression,n),s);return r}case"ParallelMapExpr":case"ParallelExpr":throw new B("Concurrency constructs require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"PathLiteralExpr":return roe(e,this.platform);case"DataBlockExpr":{e.schemaHandle&&this.resolveIdentifier(e.schemaHandle,n,e);let r=Dk(e,o=>this.evalExpr(o.value,n)),s=e.marker==="dsl"?jU(e,Object.hasOwn(r,"with")?r.with:[]):[],i=[];for(let o of e.lines)for(let a of o.pieces)typeof a!="string"&&i.push(this.evalExpr(a.expression,n));return e.marker==="dsl"?this.constructLmcode(e,i,s):qU(e,r,i,this.compileOptions)}case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let r=this.evalExpr(e.value,n),s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return s?s.define(e.target,r):n.set(e.target,r),r}case"TupleAssignExpr":{let r=this.evalExpr(e.value,n);if(!Array.isArray(r))throw new B(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<r.length?r[s]:null,o=this.recovery.active?this.recoverWriteScope(e.targets[s],e):void 0;o?o.define(e.targets[s],i):n.set(e.targets[s],i)}return r}case"IndexAssignExpr":{let r=this.evalExpr(e.target,n),s=this.evalExpr(e.index,n),i=this.evalExpr(e.value,n);if(Array.isArray(r)||typeof r=="object"&&r!==null)return Array.isArray(r)&&typeof s=="number"&&s<0&&(s=r.length+s),Qn(r,s,i),i;throw new B("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,n);case"TupleExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ArrayExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ObjectExpr":{let r={};for(let s of e.properties)Qn(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Kk(e);if(r)try{this.dry&&this.dry.at(e);let o=this.dry?.prepareProperties(r);if(Rn(o))throw o.catch(()=>{}),Error("Async properties require dryRunAsync");return Ur(this.dry?this.dry.propertyView:this.resolveIdentifier("PROPS",n,e),r)}catch(o){throw this.dry?new B(o instanceof Error?o.message:String(o),e.line,e.column,"RUNTIME",e.file):o}let s=this.evalExpr(e.target,n),i=this.evalExpr(e.index,n);if(s==null)throw new B("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return eo.has(s)?ioe(s,i,e,this.dry):toe(s,i,e)}case"MethodCallExpr":{let r=this.evalExpr(e.receiver,n),s=e.args.map(i=>this.evalExpr(i,n));return noe(r,e,s)}case"UnaryExpr":{let r=this.evalExpr(e.operand,n),s=e.operator;if(s==="!")return!this.isTruthy(r);if(s==="-")return-r;throw new B(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.evalExpr(e.trueArm,n):this.evalExpr(e.falseArm,n)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?this.evalExpr(e.right,n):o}if(e.operator==="||"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?o:this.evalExpr(e.right,n)}let r=this.evalExpr(e.left,n),s=this.evalExpr(e.right,n),i=e.operator;switch(i){case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":if(s===0)throw new B("Division by zero",e.line,e.column,"RUNTIME",e.file);return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:throw new B(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{if(e.schemaOptions)return Ck(this.compileOptions)?.get(e);let r=e.args.map(s=>this.evalExpr(s,n));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),this.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}lmcodeOwner=new k_;constructLmcode(e,n,r){let s=p1(e,"RUNTIME",Fy(this.compileOptions),n,this.compileOptions,r),i=Ck(this.compileOptions).get(e);return this.lmcodeOwner.add(s,fa.bytesOf(s),fa.programOf(s),i.declaredHead,i.schema,!!this.dry),s}runLmcode(e,n,r){let s=i=>{throw i instanceof Fr?i:new B("run_lmcode: "+(i instanceof Error?i.message:String(i)),n.line,n.column,"RUNTIME",n.file)};try{if(e.length<1||e.length>2)throw Error("expected program and optional options map");let i=this.processContext,o=this.lmcodeOwner.plan(e[0],e[1],i.cwd,this.compileOptions?.hostContext?.env??process.env,Nk);if(!r&&!this.dry)throw Error("requires runAsync");let a=By.getStore()?.get(i.env)??i.env,l;if(this.dry){let d=o.builder?[...o.argv,...o.parts.flatMap(p=>p.fragment),...o.args]:[...o.template??[...o.argv,"--lmcode","$DSLFILE"],...o.args];this.dry.record("run_lmcode",[],n,"lmcode-host-dry",d),l=this.dry.entries.at(-1),l.host=o.argv[0],l.slots=o.builder?o.parts.map((p,f)=>f):[0]}let c={dry:!!this.dry,cwd:i.cwd,env:{...a},args:o.args,signal:this.abortSignal,stdout:d=>{l?l.stdout=(l.stdout??"")+d:this.stdout(d,!0)},stderr:d=>{l?l.stderr=(l.stderr??"")+d:this.stderr?.(d)},...o.builder?{parts:o.parts,contracts:o.contracts}:{template:o.template,contract:o.contract}},u=d=>(l&&(l.envelope=this.dry.snapshot(d)),d);return r?this.lmcodeOwner.track(pB(o.bytes,o.argv,c)).then(u).catch(s):u(fB(o.bytes,o.argv,c))}catch(i){return s(i)}}buildLmcode(e,n){let r=s=>{throw new B("lmcode_build: "+(s instanceof Error?s.message:String(s)),n.line,n.column,"RUNTIME",n.file)};try{if(e.length!==1)throw Error("expected exactly one host descriptor, command-prefix string or string list");let s=this.processContext,i=this.compileOptions?.hostContext?.env??process.env,o=e[0];if(kf(o)){if(!o.program)throw Error("schema file descriptors are not hosts; pass an explicit command prefix");return this.lmcodeOwner.build(o.program,s.cwd,i,Nk)}return this.lmcodeOwner.build(o,s.cwd,i,Nk)}catch(s){return r(s)}}resolveIdentifier(e,n,r){if(this.recovery.active&&this.checkRecoverRead(e,n,r,r),n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&o1.has(s)){this.dry&&this.dry.at(r);try{let i=o1.get(s)();return Rn(i)?i.catch(o=>{throw new B(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new B(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new Qi(e);throw new B(`Variable '${e}' was read before its binding was initialized`,r.line,r.column,"RUNTIME",r.file)}resolveCallTarget(e,n){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;let r=n.get(e);return r instanceof Qi?r.name:e}invokeNamed(e,n,r,s,i,o){let a=this.tracer,l=this.userFunctions.get(e);if(!a||!l&&!this.hostFunctions.has(e))return this.invokeNamedCore(e,n,r,s,i,o);if(e==="llm_prompt"||e==="llm_models"||e==="llm_providers"||e==="tool_call"||e==="tool_parse"||e==="tool_specs")return this.invokeNamedCore(e,n,r,s,i,o);a.call(e,l?l.params.map((u,d)=>({name:u,value:n[d]})):n.map((u,d)=>({value:e==="set_env"&&d===1?"<redacted>":u})),!l,l);let c;try{c=this.invokeNamedCore(e,n,r,s,i,o)}catch(u){throw u instanceof Ln||u instanceof Zn||u instanceof Yn||a.raise(u,{line:s,column:i,file:o}),a.ret(null,!0,u),u}return a.ret(!l&&(e==="env"||e==="getenv")&&c!==null&&c!==void 0?"<redacted>":c),c}invokeNamedCore(e,n,r,s,i,o){if(this.dry?.at({line:s,column:i,file:o}),e==="lmcode_build")return this.buildLmcode(n,{line:s,column:i,file:o});if(e==="run_lmcode")return this.runLmcode(n,{line:s,column:i,file:o},!1);if(In(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Ek)throw this.callDepth--,new B(`Execution fuel exhausted: maximum function call depth exceeded (${Ek})`,s,i,"RUNTIME",o);let l=new mr(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],n[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Ln)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{if(!this.dry&&a.dryRun===i1){Uy(a,n);let u=String(n[0]);return this.warningDiagnostics.push({severity:"warning",message:u,line:s,column:i,file:o}),u}if(this.dry){let u=ooe(a,n,e,{line:s,column:i,file:o},this.dry,this.compileOptions);if(u.skip)return u.value;let d=u.invoke();if(this.dry.check(),Rn(d)&&(Promise.resolve(d).catch(()=>{}),this.dry.fail("Async host requires dryRunAsync",{line:s,column:i,file:o})),this.dry.failure)throw new Fr(this.dry.failure.message);return Eu(d)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:o}),d}let l=Uy(a,n);if(a.returnsResource)throw new B(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);In(this.abortSignal);let c=NU(a,l);if(a.returnsResource&&Rn(c))throw c.then(u=>{try{u&&typeof u.finalizeSync=="function"?u.finalizeSync():u&&typeof u.close=="function"&&u.close()}catch{}},()=>{}),new Error("returns a resource asynchronously; use engine.runAsync()");return c}catch(l){throw this.dry?.captureFailure(l,{line:s,column:i,file:o}),l instanceof rs||l?.name==="LMScriptExit"||l?.isControlFlow?l:new B(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new B(`'${e}' is not a function`,s,i,"RUNTIME",o):new B(bf(e,"Undefined function"),s,i,"RUNTIME",o)}ownerFor(e,n){let r=this.resources.scopeFor(e),s=this.temporaryScopes.get(n),i=s&&s[s.length-1];return i&&i.base===r?i:r}pushTemporaryScope(e,n){let r=this.temporaryScopes.get(e);r?r.push(n):this.temporaryScopes.set(e,[n])}popTemporaryScope(e){let n=this.temporaryScopes.get(e);n?.pop(),n&&n.length===0&&this.temporaryScopes.delete(e)}async execLoopBodyAsync(e,n,r){await this.execStmtAsync(e,n,r)}resourceError(e,n,r){return new B(`Resource ${this.resources.describe(e)} ${n}`,r.line,r.column,"RUNTIME",r.file)}refuseResource(e,n,r){if(Ft(e))throw this.resourceError(e,n,r)}bindResource(e,n,r,s){let i=this.resources.bind(e,n,r);if(i)throw new B(i.charAt(0).toUpperCase()+i.slice(1),s.line,s.column,"RUNTIME",s.file)}async resourceCallArgs(e,n,r,s,i,o){if(!r.some(Ft))return r;let a={line:s,column:i,file:o};if(!e.usesResource&&!e.closesResource)throw this.resourceError(r.find(Ft),`cannot be passed to '${n}'`,a);let l=[];for(let c of r){if(!Ft(c)){l.push(c);continue}let u=this.resources.lookup(c);if(!u)throw this.resourceError(c,`cannot be used by '${n}': it belongs to another run`,a);if(e.closesResource)this.resources.borrow(c),await this.resources.close(u,r.slice(1));else if(u.state!=="open")throw this.resourceError(c,`is ${u.state==="closing"?"closing":"closed"}: '${n}' cannot use it`,a);this.resources.borrow(c),l.push(u.raw)}return l}registerHostResource(e,n,r,s,i,o){if(e==null)return e;if(typeof e!="object"||typeof e.close!="function"||typeof e.id!="string"&&typeof e.id!="number"||String(e.id)==="")throw new Error("a returnsResource host must return null or an object with a close method and a stable id");return this.resources.register(e,n,`${o??"<main>"}:${s}:${i}`,r)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new mr,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear();for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let n=this.nextTaskId++;this.recovery.rootTaskId=n;let r;try{for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(r=await this.execStmtAsync(s,this.globalEnv,n))}catch(s){throw $s(this.recovery,s),this.resources.root.failure=bu(s),s}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),Ft(r))r=null;else if(aoe()){let s=Eu(r);if(s)throw new B(Ft(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:Ak(s,"run"),1,1,"RUNTIME")}return r}coOf(e){return e===this.recovery.rootTaskId?"main":"t"+e}async execStmtAsync(e,n,r){let s=this.tracer;if(!s||e.kind==="BlockStmt"||e.kind==="FunctionDeclStmt"||e.kind==="ImportStmt"||e.kind==="PackageStmt")return this.execStmtAsyncCore(e,n,r);let i=this.coOf(r);s.stmt(e,n,i),e.kind==="BreakStmt"?s.jump("break",e,i):e.kind==="ContinueStmt"&&s.jump("continue",e,i);try{return await this.execStmtAsyncCore(e,n,r)}catch(o){throw o instanceof Ln?e.kind==="ReturnStmt"&&s.jump("return",e,i):o instanceof Zn||o instanceof Yn||s.raise(o,e,i),o}}async execStmtAsyncCore(e,n,r){switch(this.dry?.at(e),In(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let s=new mr(n);if(!this.resourcesEnabled){for(let o of e.statements)await this.execStmtAsync(o,s,r);return}let i=this.resources.enterScope(s,this.ownerFor(n,r),"block");try{for(let o of e.statements)await this.execStmtAsync(o,s,r)}catch(o){throw $s(this.recovery,o),i.failure=bu(o),o}finally{i.records.length>0&&await this.resources.drain(i)}return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,n,r)),Ft(s)&&this.bindResource(s,n,e.name,e),e.constant?(s=Fk(s),n.defineConst(e.name,s),s):(n.define(e.name,s),s)}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(Array.isArray(s))for(let i=0;i<e.names.length&&i<s.length;i++)this.bindResource(s[i],n,e.names[i],e);if(!Array.isArray(s))throw new B(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?(this.tracer?.branch("then",e.thenBranch,n,this.coOf(r)),await this.execStmtAsync(e.thenBranch,n,r)):e.elseBranch?(this.tracer?.branch("else",e.elseBranch,n,this.coOf(r)),await this.execStmtAsync(e.elseBranch,n,r)):void 0}case"WhileStmt":{let s=0,i=this.tracer,o=this.coOf(r),a=i?.loopEnter("while",e,o),l="done";try{for(;!this.dry?.loop(s,e)&&this.isTruthy(await this.evalExprAsync(e.condition,n,r));){s++,i?.loopIter(a,s,e,n,o);try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,n,r):await this.execStmtAsync(e.body,n,r)}catch(c){if(c instanceof Zn){l="break";break}if(c instanceof Yn)continue;throw c}}}catch(c){throw l=c instanceof Ln?"return":"raise",c}finally{i?.loopExit(a,s,l,o)}return}case"ForInStmt":{let s=Zie(await this.evalExprAsync(e.iterable,n,r),e,this.dry),i=0,o=this.tracer,a=this.coOf(r),l=o?.loopEnter("foreach",e,a),c="done";try{for(let u=0;(u<s.length||this.dry?.loopLimit!==void 0&&i===this.dry.loopLimit)&&!this.dry?.loop(i,e);u++){let d=s[u];i++;let p=new mr(n);p.define(e.name,d),o?.loopIter(l,i,e,p,a);let f=this.resourcesEnabled?this.resources.enterScope(p,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let m of e.body.statements)await this.execStmtAsync(m,p,r);else await this.execStmtAsync(e.body,p,r)}catch(m){throw $s(this.recovery,m),f&&(f.failure=bu(m)),m}finally{f&&f.records.length>0&&await this.resources.drain(f)}}catch(m){if(m instanceof Zn){c="break";break}if(m instanceof Yn)continue;throw m}}}catch(u){throw c=u instanceof Ln?"return":"raise",u}finally{o?.loopExit(l,i,c,a)}return}case"ForStmt":{let s=new mr(n),i=this.resourcesEnabled?this.resources.enterScope(s,this.ownerFor(n,r),"for"):void 0;try{e.init&&await this.execStmtAsync(e.init,s,r);let o=0,a=this.tracer,l=this.coOf(r),c=a?.loopEnter("for",e,l),u="done";try{for(;!this.dry?.loop(o,e);){if(e.condition){let d=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(d))break}o++,a?.loopIter(c,o,e,s,l);try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,s,r):await this.execStmtAsync(e.body,s,r)}catch(d){if(d instanceof Zn){u="break";break}if(!(d instanceof Yn))throw d}if(this.dry?.loop(o,e))break;e.update&&await this.evalExprAsync(e.update,s,r)}}catch(d){throw u=d instanceof Ln?"return":"raise",d}finally{a?.loopExit(c,o,u,l)}}catch(o){throw $s(this.recovery,o),i&&(i.failure=bu(o)),o}finally{i&&i.records.length>0&&await this.resources.drain(i)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,n,r):null;throw Ft(s)&&this.refuseResource(s,"cannot be returned: a resource stays with its owner (return copied data instead)",e),new Ln(s)}case"BreakStmt":throw new Zn;case"ContinueStmt":throw new Yn;case"SyncAssignStmt":{let s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0,i=s?{env:s,name:e.target}:n.resolveBinding(e.target);if(!i)throw new B(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let o=`bind:${i.env.id}:${i.name}`;await this.lockManager.getBindingLock(o).withLock(async()=>{let l=await this.evalExprAsync(e.value,n,r);this.bindResource(l,i.env,i.name,e),i.env.resolveBinding(i.name)?.env===i.env?i.env.set(i.name,l):i.env.define(i.name,l)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new B("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,n,r),a=await this.evalExprAsync(e.value,n,r);this.refuseResource(s,"cannot be modified",e),this.refuseResource(o,"cannot be used as a map key",e),this.refuseResource(a,"cannot be stored in a container",e),Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Qn(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new B("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 B(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],n,r);if(o==null||typeof o!="object"&&typeof o!="function")throw new B("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let s=await this.evalExprAsync(e.expr,n,r);return Sk(await this.invokeCallAsync("system",[s],n,e.expr.line,e.expr.column,r,e.expr.file))}return Uie(e.expr)?Sk(await this.evalExprAsync(e.expr,n,r)):await this.evalExprAsync(e.expr,n,r)}case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new mr(n);this.recovery.envs.set(e,i);let o=this.resourcesEnabled?this.resources.enterScope(i,this.ownerFor(n,r),"block"):void 0,a=this.recovery.stack.length;try{for(let l=s.start;l<e.points.length;l++){let c=e.points[l];this.enterPoint(a,c.name);for(let u of c.statements)await this.execStmtAsync(u,i,r);s.consumed&&l===s.start&&this.checkRemainder(c)}}catch(l){throw $s(this.recovery,l),o&&(o.failure=bu(l)),l}finally{try{o&&o.records.length>0&&await this.resources.drain(o)}finally{this.leaveRecover(a)}}return}default:return}}async evalExprAsync(e,n,r){switch(In(this.abortSignal),e.kind){case"CommandExpr":{let s=[];for(let o of e.words){let a=[];for(let l of o.pieces)a.push(typeof l=="string"?l:await this.evalExprAsync(l.expression,n,r));s.push(a)}let i=zie(e,s);return e.mode==="cmd"?i:await this.invokeCallAsync("system",[i],n,e.line,e.column,r,e.file)}case"InterpolatedStringExpr":{let s="";for(let i of e.parts){if(typeof i=="string"){s+=i;continue}let o=await this.evalExprAsync(i.expression,n,r);this.refuseResource(o,"cannot be converted to text",i.expression),s+=e1(o,i)}return s}case"LiteralExpr":return e.value;case"PathLiteralExpr":return roe(e,this.platform);case"DataBlockExpr":{e.schemaHandle&&this.resolveIdentifier(e.schemaHandle,n,e);let s={};for(let a of e.options)s[a.name]=await this.evalExprAsync(a.value,n,r);let i=e.marker==="dsl"?jU(e,Object.hasOwn(s,"with")?s.with:[]):[],o=[];for(let a of e.lines)for(let l of a.pieces)typeof l!="string"&&o.push(await this.evalExprAsync(l.expression,n,r));return e.marker==="dsl"?this.constructLmcode(e,o,i):qU(e,Dk(e,a=>s[a.name]),o,this.compileOptions)}case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let s=await this.evalExprAsync(e.value,n,r),i=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return Ft(s)&&this.bindResource(s,i??n.writeTarget(e.target),e.target,e),i?i.define(e.target,s):n.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,n,r);if(!Array.isArray(s))throw new B(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null,a=this.recovery.active?this.recoverWriteScope(e.targets[i],e):void 0;Ft(o)&&this.bindResource(o,a??n.writeTarget(e.targets[i]),e.targets[i],e),a?a.define(e.targets[i],o):n.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,n,r),i=await this.evalExprAsync(e.index,n,r),o=await this.evalExprAsync(e.value,n,r);if(this.refuseResource(s,"cannot be modified",e),this.refuseResource(i,"cannot be used as a map key",e),this.refuseResource(o,"cannot be stored in a container",e),Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Qn(s,i,o),o;throw new B("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,n,r);case"TupleExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ArrayExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ObjectExpr":{let s={};for(let i of e.properties){let o=await this.evalExprAsync(i.value,n,r);this.refuseResource(o,"cannot be stored in a container",i.value),Qn(s,i.key,o)}return s}case"ParallelMapExpr":{let s=await this.evalExprAsync(e.items,n,r),i=await this.evalExprAsync(e.callback,n,r),o=e.limit?await this.evalExprAsync(e.limit,n,r):void 0,a=b=>{throw new B("parallel_map: "+b,e.line,e.column,"RUNTIME",e.file)};Array.isArray(s)||a("items must be a list"),i instanceof Qi||a("fn must be a function reference taking one argument");let l=this.userFunctions.get(i.name),c=this.hostFunctions.get(i.name),u=l?l.params.length:c?.signature?.publicArity??c?.arity??c?.fn.length;(u===void 0||(typeof u=="number"?u!==1:u.min>1||(u.max??1/0)<1))&&a("fn must be a function taking one argument");let d=e.limit?o:this.processContext?.env?.LMSCRIPT_PARALLEL_LIMIT??process.env.LMSCRIPT_PARALLEL_LIMIT,p=e.limit?d:d===void 0?KBe:typeof d=="string"&&/^[0-9]+$/.test(d)?Number(d):NaN;(typeof p!="number"||!Number.isSafeInteger(p)||p<1)&&a("limit must be a positive safe integer"+(e.limit?"":" (LMSCRIPT_PARALLEL_LIMIT)"));let f=Eu(s);f&&a(Ft(f)?"resource handles cannot cross a task input boundary":Ak(f,"parallel_map input"));let m=s.slice(),g=new Array(m.length),h=0,y=!1,v=async()=>{for(;!y&&h<m.length;){if(this.abortSignal?.aborted||this.dry?.failure||this.dry?.scriptExit){y=!0;break}let b=h++;try{let w=await this.runParallelTask(e,n,r,T=>this.invokeCallAsync(i.name,[m[b]],n,e.line,e.column,T,e.file),!0);g[b]={status:"fulfilled",value:w}}catch(w){g[b]={status:"rejected",reason:w}}}};await Promise.all(Array.from({length:Math.min(this.dry?1:p,m.length)},v));let _=[];for(let b=0;b<h;b++){let w=g[b];if(w.status==="rejected")throw w.reason;_.push(w.value)}return In(this.abortSignal),_}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=c=>this.runParallelTask(c,n,r,u=>this.evalExprAsync(c,n,u));if(this.dry){let c=[];for(let u of e.tasks)this.dry.at(u),c.push(await s(u));return c}let i=e.tasks.map(s),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=Kk(e);if(s)try{return this.dry&&(this.dry.at(e),await this.dry.prepareProperties(s)),Ur(this.dry?this.dry.propertyView:await this.resolveIdentifier("PROPS",n,e),s)}catch(a){throw this.dry?new B(a instanceof Error?a.message:String(a),e.line,e.column,"RUNTIME",e.file):a}let i=await this.evalExprAsync(e.target,n,r),o=await this.evalExprAsync(e.index,n,r);if(this.refuseResource(o,"cannot be used as a map key",e),Ft(i)){if(o==="id")return i.id;throw this.resourceError(i,`has no readable field '${String(o)}' (only id)`,e)}if(i==null)throw new B("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return eo.has(i)?ioe(i,o,e,this.dry):toe(i,o,e)}case"MethodCallExpr":{let s=await this.evalExprAsync(e.receiver,n,r),i=[];for(let o of e.args)i.push(await this.evalExprAsync(o,n,r));return this.refuseResource(s,"has no methods",e),noe(s,e,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,n,r),i=e.operator;if(i==="!")return!this.isTruthy(s);if(this.refuseResource(s,"cannot be used in arithmetic",e),i==="-")return-s;throw new B(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,n,r):await this.evalExprAsync(e.falseArm,n,r)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?await this.evalExprAsync(e.right,n,r):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,n,r)}let s=await this.evalExprAsync(e.left,n,r),i=await this.evalExprAsync(e.right,n,r),o=e.operator;switch((Ft(s)||Ft(i))&&o!=="=="&&o!=="!="&&(this.refuseResource(s,`cannot be used with '${o}' (only ==, != and truth tests)`,e),this.refuseResource(i,`cannot be used with '${o}' (only ==, != and truth tests)`,e)),o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new B("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 B(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{if(e.schemaOptions)return Ck(this.compileOptions)?.get(e);let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,n,r));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),await this.invokeCallAsync(e.callee,s,n,e.line,e.column,r,e.file)}}}async runParallelTask(e,n,r,s,i=!1){let o=this.nextTaskId++;this.asyncCallDepth.set(o,this.asyncCallDepth.get(r)??0);let a=this.resourcesEnabled?this.resources.temporaryScope(this.ownerFor(n,r),"task",this.resources.scopeFor(n)):void 0;a&&this.pushTemporaryScope(o,a);let l=this.processContext?.env,c=l?new Map(By.getStore()).set(l,{...l}):void 0;try{In(this.abortSignal);let u=await(c?By.run(c,()=>s(o)):s(o));In(this.abortSignal);let d=i||aoe()?Eu(u):void 0;if(d)throw new B(Ft(d)?`Resource ${this.resources.describe(d)} cannot be a parallel task result: it stays with the task that opened it`:Ak(d,"parallel task"),e.line,e.column,"RUNTIME",e.file);return u}catch(u){throw this.dry?.captureFailure(u,e),$s(this.recovery,u),a&&(a.failure=bu(u)),u}finally{try{a&&(this.popTemporaryScope(o),a.records.length>0&&await this.resources.drain(a))}finally{this.asyncCallDepth.delete(o)}}}async invokeCallAsync(e,n,r,s,i,o,a){let l=this.tracer,c=this.resolveCallTarget(e,r),u=this.userFunctions.get(c);if(!l||!u&&!this.hostFunctions.has(c))return this.invokeCallAsyncCore(e,n,r,s,i,o,a);if(c==="llm_prompt"||c==="llm_models"||c==="llm_providers"||c==="tool_call"||c==="tool_parse"||c==="tool_specs")return this.invokeCallAsyncCore(e,n,r,s,i,o,a);let d=this.coOf(o);l.call(c,u?u.params.map((f,m)=>({name:f,value:n[m]})):n.map((f,m)=>({value:c==="set_env"&&m===1?"<redacted>":f})),!u,u,d);let p;try{p=await this.invokeCallAsyncCore(e,n,r,s,i,o,a)}catch(f){throw f instanceof Ln||f instanceof Zn||f instanceof Yn||l.raise(f,{line:s,column:i,file:a},d),l.ret(null,!0,f,d),f}return l.ret(!u&&(c==="env"||c==="getenv")&&p!==null&&p!==void 0?"<redacted>":p,!1,void 0,d),p}async invokeCallAsyncCore(e,n,r,s,i,o,a){this.dry?.at({line:s,column:i,file:a});let l=this.resolveCallTarget(e,r);if(l==="lmcode_build")return this.buildLmcode(n,{line:s,column:i,file:a});if(l==="run_lmcode")return await this.runLmcode(n,{line:s,column:i,file:a},!0);if(In(this.abortSignal),this.userFunctions.has(l)){let c=this.userFunctions.get(l),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>Ek)throw this.asyncCallDepth.set(o,u-1),new B(`Execution fuel exhausted: maximum function call depth exceeded (${Ek})`,s,i,"RUNTIME",a);let d=new mr(this.globalEnv,!0),p=this.resourcesEnabled?this.resources.enterScope(d,this.ownerFor(r,o),`function ${l}`):void 0;for(let f=0;f<c.params.length;f++)p&&this.resources.borrow(n[f]),d.define(c.params[f],n[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,d,o)}catch(f){if(f instanceof Ln)return f.value;throw this.dry?.captureFailure(f),$s(this.recovery,f),p&&(p.failure=bu(f)),f}finally{p&&p.records.length>0&&await this.resources.drain(p),this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{if(!this.dry&&c.dryRun===i1){Uy(c,n);let g=String(n[0]);return this.warningDiagnostics.push({severity:"warning",message:g,line:s,column:i,file:a}),g}if(this.dry){let g=ooe(c,n,l,{line:s,column:i,file:a},this.dry,this.compileOptions);if(g.skip)return g.value;let h=await this.dry.wait(g.invoke());if(this.dry.failure)throw new Fr(this.dry.failure.message);return Eu(h)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:a}),h}let u=Uy(c,n),d=PHe(u)?await this.resourceCallArgs(c,l,u,s,i,a):u,f=c.returnsResource||c.usesResource||c.closesResource?Zoe.run({runtime:this.resources,scope:this.ownerFor(r,o),site:(a??"<main>")+":"+s+":"+i},()=>NU(c,d)):NU(c,d),m=f instanceof Promise?await f:f;return c.returnsResource?this.registerHostResource(m,l,this.ownerFor(r,o),s,i,a):m}catch(u){throw this.dry?.captureFailure(u,{line:s,column:i,file:a}),u instanceof rs||u?.name==="LMScriptExit"||u?.isControlFlow?u:new B(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new B(`'${l}' is not a function`,s,i,"RUNTIME",a):new B(bf(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},MHe=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. Function bodies establish an isolated local variable scope for assignments, preventing accidental mutation of caller variables.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel_map",category:"Language Constructs",signature:"parallel_map(items, fn[, limit])",description:"Bounded asynchronous fan-out over a runtime list; ordered own-data results, all inputs settle before the first indexed failure. Default 8 (LMSCRIPT_PARALLEL_LIMIT), no fixed concurrency maximum.",example:"fn work(x) { return x * 2; } results = parallel_map([1, 2, 3], work, 2);"},{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;"}],DHe=[{name:"sha256",category:"Math & Utilities",signature:"sha256(text: string): string",description:"Lowercase SHA-256 hex of UTF-8 bytes; rejects non-string inputs.",example:'sha256("abc");'},{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("teams/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"parse_file_blocks",category:"Agent Files",signature:"parse_file_blocks(text: string): array",description:"Parses `=== FILE: relative/path ===` ... `=== END ===` blocks into [{path, content}]. Prose around blocks and whitespace around marker lines are ignored; content wrapped in exactly one markdown fence is unwrapped; content gets a final newline. Incomplete blocks (no END before the next FILE marker or the end of text) are dropped, so a truncated reply yields only its complete files.",example:"files = parse_file_blocks(reply);"},{name:"format_file_blocks",category:"Agent Files",signature:"format_file_blocks(files: array): string",description:"Formats [{path, content}] as file blocks; parse_file_blocks(format_file_blocks(files)) returns files (content normalised to end in a newline). Fence-wrapped content gets an outer fence; content containing a marker line is an error.",example:"context = format_file_blocks(read_tree(dir));"},{name:"write_files",category:"Agent Files",signature:"write_files(dir: string, files: array): map",description:"Writes [{path, content}] under dir (created if missing), each file atomically (temporary file + rename, mode of a replaced file kept). Rejects, never writes: empty, absolute, backslash or '..' paths, any .git segment, a path through a symlink leaving dir, a symlink or directory target, non-string content. Returns {written: [relative paths], rejected: [{path, reason}]}; under --dry-run the language skips it and returns an empty map without classifying paths.",example:'res = write_files(dir, parse_file_blocks(reply)); println("wrote", len(res.written));'},{name:"read_tree",category:"Agent Files",signature:"read_tree(dir: string, [options: map]): array",description:"Reads text files under dir as [{path, content}] sorted by path, relative with / separators. Skips symlinks, binary/non-UTF-8 files, files over maxBytes (omitted means no size limit) and the default ignores .git, node_modules, dist, build, target, .mp, __pycache__, *.lock, package-lock.json. Options: ignore (extra patterns), include (only matching files), maxBytes. A pattern without / matches a single name, with / the whole relative path; * ? ** globs. A missing dir reads as [].",example:'listing = format_file_blocks(read_tree(dir, {ignore: ["*.md"]}));'},{name:"kv_from_last_paragraph",category:"Agent Files",signature:"kv_from_last_paragraph(text: string): map",description:"Parses `key: value` lines (key [A-Za-z_][A-Za-z0-9_-]*, optional - or * bullet, value in one pair of backticks unwrapped, empty values skipped) of the last blank-line-separated paragraph; the last occurrence of a key wins and missing keys are absent. Trailing paragraphs without any key: value line are skipped as chatter, looking at most 3 paragraphs back; a paragraph holding a file-block marker stops the search.",example:'cfg = kv_from_last_paragraph(reply); if (has_key(cfg, "build_command")) { println(cfg.build_command); }'},{name:"split_command",category:"Agent Files",signature:"split_command(text: string): array",description:"Splits one command line into argv with POSIX quoting (single quotes, double quotes, backslash). Unquoted | & ; < > ( ) ` $, $ or ` inside double quotes, a word-start #, a newline and a leading NAME=value are errors, so model-supplied commands run through system() with shell:false and no shell semantics. Globs and ~ stay literal.",example:'res = system(split_command("npm run build"), {cwd: 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:"sql_read",category:"Database",signature:"sql_read(path: string, sql: string, [params: array|map]): array",description:"Runs ONE SELECT on a local SQLite file opened read-only and returns a list of maps (use SQL LIMIT for an explicit row bound). The SQL is a string literal; values are bound parameters.",example:'rows = sql_read("app.db", "SELECT name FROM t WHERE id = ?", [7]);'},{name:"sql_exec",category:"Database",signature:"sql_exec(path: string, sql: string, [params: array|map]): map",description:"Runs ONE write statement on a local SQLite file (created if missing; refuses the lmctl state database) and returns {changes, last_insert_rowid}. The SQL is a string literal; values are bound parameters.",example:'sql_exec("app.db", "INSERT INTO t(name) VALUES (?)", ["ada"]);'},{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:"run_lmcode",category:"File I/O",signature:"run_lmcode(program_or_builder: lmcode, options?: map): map",description:"Runs one opaque lmcode program or one sealed builder in a single host process. Single results are {ok,result}; builder results are {ok,result:[...],parts}. Args are copied; command is single-program only. Returns validated success/failure envelopes. Check never executes; dry invokes the host once with dry metadata and records its simulated envelope in PLAN.",example:'r = run_lmcode(program); require(r.ok, "host failed");'},{name:"lmcode_build",category:"File I/O",signature:"lmcode_build(host: lmcode schema | string | string list): lmcode_builder",description:"Creates a run-local one-process builder for lmcode programs. host is a host-bound load_schema descriptor or an explicit command prefix string/list; add programs with one $DSLFILE fragment each, then pass the builder to run_lmcode.",example:"builder = lmcode_build(schema); builder.add(program); result = run_lmcode(builder);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this run (isolated per parallel/parallel_map task): env()/getenv() and later system() calls, command literals, which(), run_script children and lm_* provider calls see it; null unsets the name, including an inherited value. The Node process environment and the caller's environment object are not changed; on Windows names are case-insensitive.",example:'set_env("DEBUG", "1");'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), reports through injected diagnostics/captured errors and stops with exit 1; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests a JavaScript regex against text.",example:'regex_test("abc", "a");'},{name:"regex_find",category:"Strings",signature:"regex_find(s: string, pattern: string, [flags: string]): string|null",description:"Returns the first matched substring, or null if no match. Rejects sticky y.",example:'regex_find("item=42; item=99", "[0-9]+");'},{name:"regex_matches",category:"Strings",signature:"regex_matches(s: string, pattern: string, [flags: string]): array",description:"Returns a flat list of all matched substrings; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_matches("item=42; item=99", "[0-9]+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns first [full_match, group1, ...], including with g; missing optional groups become null. Rejects sticky y.",example:'regex_match("a1 b2", "([a-z])([0-9])", "g");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns capture arrays for matches; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_find_all("a1 b2", "([a-z])([0-9])");'},{name:"pos",category:"Strings",signature:"pos([s: string|number|null], [offset: number|null]): number",description:"Perl-like stateful regex position (0-based, isolated per run and parallel task): pos() or pos(s) returns the offset where the last successful stateful match left off; pos(offset) or pos(s, offset) sets or resets (0/null) the offset.",example:"pos(0); while (pos() < len(src)) { ... }"},{name:"set_pos",category:"Strings",signature:"set_pos(s_or_offset: string|number|null, [offset: number|null]): number",description:"Sets or resets (0/null) the stateful regex match position for the current run or target string and returns the new offset.",example:"set_pos(src, 0);"},{name:"regex_match_pos",category:"Strings",signature:"regex_match_pos(s: string, pattern: string, [flags: string]): array|null",description:"Stateful regex match starting at pos(s): anchored at pos(s) by default (sticky y) or searching from pos(s) when g is set; advances pos(s) on match and returns [full_match, group1, ...], or leaves pos(s) unchanged and returns null.",example:'m = regex_match_pos(src, r"[A-Za-z_][A-Za-z0-9_]*");'},{name:"regex_find_pos",category:"Strings",signature:"regex_find_pos(s: string, pattern: string, [flags: string]): string|null",description:"Stateful regex substring match starting at pos(s): anchored at pos(s) by default (sticky y) or searching from pos(s) when g is set; advances pos(s) on match and returns the matched substring, or leaves pos(s) unchanged and returns null.",example:'tok = regex_find_pos(src, r"[0-9]+");'},{name:"regex_test_pos",category:"Strings",signature:"regex_test_pos(s: string, pattern: string, [flags: string]): boolean",description:"Stateful regex test starting at pos(s): anchored at pos(s) by default (sticky y) or searching from pos(s) when g is set; advances pos(s) and returns true on match, or leaves pos(s) unchanged and returns false.",example:'if (regex_test_pos(src, r"\\s+")) { continue; }'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:"JavaScript regex replacement with $1 captures; use g for repeated replacement.",example:'regex_replace("a1", "([a-z])([0-9])", "$2$1");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits using JavaScript regex semantics.",example:'split_regex("a b", " +");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"args_parse",category:"System & Process",signature:"args_parse(argv: array, flags: map, [usage: string]): map",description:"Pure long-option parser. Flag declarations have type (string, number or boolean), optional flag spelling, default, required and description. Returns {values,args,provided,help,help_requested}; --help generates text without printing or exiting. Unknown/duplicate options, missing/invalid values and unused declaration fields are errors. -- ends options; booleans use --flag or --flag=false. Caller policy stays outside the parser.",example:'opts = args_parse(ARGV, {region:{type:"string",default:"us-east-1"},live:{type:"boolean"}});'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width and integer precision have no artificial cap. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER) from the last 3 non-blank lines of a string, or null if absent or conflicting.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:"join(arr: array, [separator: string]): string",description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"upper_first",category:"Strings",signature:"upper_first(s: string): string",description:"Capitalizes the first character of a string.",example:'c = upper_first("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the UTF-16 code unit at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"warning",category:"System & Process",signature:"warning(message: any): string",description:"Adds a located warning without failing execution or simulating an effect.",example:'warning("Review this input");'},{name:"which",category:"System & Process",signature:"which(name: string): string|null",description:"Returns the first executable absolute path from invocation PATH/cwd, or null, without spawning.",example:'tool = which("node");'},{name:"cmd_render",category:"System & Process",signature:"cmd_render(argv: array, [dialect: string]): string",description:"Renders string/number argv for posix, windows or powershell; default windows on win32, otherwise posix. Output only; never used for execution.",example:'text = cmd_render(["git", "status"], "posix");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, ...items: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, ...items: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(first: array, ...more: array): array",description:"Concatenates two or more arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:'Safely parses JSON with markdown fence and preamble tolerance, returning fallback on failure without throwing. Use a custom sentinel (e.g. "PARSE_FAILED") to distinguish parse failure from valid JSON null.',example:'data = json_parse_safe(llm_output, "PARSE_FAILED"); if (data == "PARSE_FAILED") { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 0]): string",description:"Serializes a value to compact JSON by default; optional indent formats the output.",example:"text = json_stringify(obj, 2);"},{name:"json_validate",category:"JSON & Data",signature:"json_validate(val: any, schema: map): map",description:"Validates a JSON-compatible value against a small JSON-Schema subset (type, properties, required, enum, items, minimum/maximum, minLength/maxLength, additionalProperties:false), returning {ok: boolean, errors: list}.",example:'res = json_validate(data, {type: "object", required: ["name"]}); if (!res.ok) { error(res.errors[0]); }'},{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(argv: array, [timeoutMs: number = 0 | options: map]): SystemResult",description:"Executes a non-empty string/number argv list directly with shell:false, returning a structured process execution record. The second argument is a timeout in milliseconds or an options map {cwd, timeoutMs, stdin}; a spawn failure or cwd that does not exist gives a result with code null and an error field instead of a failure.",parameters:[{name:"argv",type:"array",description:"Non-empty argv list of strings/numbers; NUL and an empty program are errors"},{name:"timeoutMs|options",type:"number|map",description:"(optional) Timeout in milliseconds (default: 0, no deadline), or options {cwd: string (relative to the invocation directory), timeoutMs: number (default 0), stdin: string}; unknown keys are errors"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null, error?: string }"},example:'res = system(["git", "log", "-n", "1"], {cwd: "."}); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string], [options: map]): string|null; prompt_human(session: map, [options: map]): map",description:"Pauses execution to prompt an operator on terminal stdin or dedicated directory, returning the entered input line or decision map, or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"prompt_human_config",category:"System & Process",signature:"prompt_human_config([config: map|string], [dir: string]): map",description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms). Returns current configuration map.",example:'prompt_human_config({ dir: "/tmp/handoffs", timeout_ms: 60000 });'},{name:"error",category:"System & Process",signature:"error(value: any, ...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats values into an output-log entry rendered as a line by the CLI. Returns the formatted text without adding a newline.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with the sprintf width and precision rules and writes exactly that text to stdout: nothing is added, so end the format with \\n to finish the line.",example:'printf("%s scored %d\\n", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline.",example:'println("Done.");'},{name:"sleep_ms",category:"System & Process",signature:"sleep_ms(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep_ms(1000);"},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in milliseconds.",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now or a supplied epoch-millisecond value.",example:"created = date(0);"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null (including no arguments).",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"http_get",category:"System & Process",signature:"http_get(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = http_get("https://example.com");'}],$He=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];ta=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;promptHumanConfig={mode:"interactive"};builtinProviders=new Map;reservedFunctionPrefixes;builtinProviderNames;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions();for(let[e,n]of[["get_property",{min:1,max:2}],["has_property",1],["get_properties",{min:0,max:1}],["set_property",2]])this.registerFunction(e,()=>{throw Error("Property store is not running")},n,"Read or overlay hierarchical run-local properties; no persistence");this.registerComputedFunction("expand",()=>{throw Error("Template resolver is not running")},{min:1,max:2},"Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque"),this.registerComputedFunction("template_extract",sH,2,{description:"Pure tree projection over parsed JSON-like values; returns {matched,value,candidate,error}; no-match is data, not an exception.",params:[{name:"pattern",type:"any"},{name:"data",type:"any"}],returnType:"map",doc:{name:"template_extract",signature:"template_extract(pattern, data)",category:"Templates",description:"Project nested captures and filter repeated rows; guards compare without coercion. Inputs are parsed values, never auto-detected JSON text."}}),this.registerComputedFunction("template_extract_first",iH,2,{description:"Validate a nonempty candidate list and return the first matching projection as {matched,value,candidate,error}; failure records stay ordered.",params:[{name:"patterns",type:"any"},{name:"data",type:"any"}],returnType:"map",doc:{name:"template_extract_first",signature:"template_extract_first(patterns, data)",category:"Templates",description:"First full candidate wins with fresh captures; loop explicitly over polymorphic streams. No-match is data."}}),this.registerComputedFunction("template_extract_text",oH,2,{description:"Exact whole-string extraction with simple ${name} holes, anchored suffix and earliest separators; returns {matched,value,candidate,error}.",params:[{name:"template",type:"any"},{name:"text",type:"any"}],returnType:"map",doc:{name:"template_extract_text",signature:"template_extract_text(template, text)",category:"Templates",description:"Strings only; $${ escapes, empty captures allowed, no adjacent/duplicate holes, backtracking, expression holes or automatic mode detection."}}),this.registerComputedFunction("warning",e=>String(e),1,{description:"Adds a located non-failure warning",isDefault:!0,returnType:"string"}),this.registerComputedFunction("which",e=>Tk(e,process.cwd(),process.env),1,{description:"Finds the first executable path without spawning",isDefault:!0,returnType:"string|null"}),this.registerComputedFunction("xml_children",HF,1,{description:"Return a native XML element's ordered child array; operate on Data.value() copies.",returnType:"array",doc:{name:"xml_children",category:"JSON & Data",signature:"xml_children(node)",description:"Ordered children of a native XML element snapshot."}}),this.registerComputedFunction("xml_attr",WF,{min:2,max:3},{description:"Look up an unqualified or {URI}local attribute, with optional fallback.",returnType:"any",doc:{name:"xml_attr",category:"JSON & Data",signature:"xml_attr(node, name, fallback=null)",description:"Look up a native XML attribute by expanded name."}}),this.registerComputedFunction("xml_select",qF,2,{description:"Select native XML nodes by *, local tag, .class or #id; returns references inside the supplied copy.",returnType:"array",doc:{name:"xml_select",category:"JSON & Data",signature:"xml_select(tree, selector)",description:"Generic XML selection without XPath or raw markup parsing."}}),this.registerComputedFunction("xml_text",zF,1,{description:"Concatenate descendant XML text in document order, excluding comments.",returnType:"string",doc:{name:"xml_text",category:"JSON & Data",signature:"xml_text(node)",description:"Text from a native XML tree, excluding comments."}}),this.installCoreDryCallbacks(),this.registerDefaultDocs();for(let[e,n,r]of[["get_property","get_property(key, [default])","Returns a copied property value; absent keys are errors unless a default is supplied."],["has_property","has_property(key)","Tests property presence; missing/invalid profile errors remain loud."],["get_properties","get_properties([prefix])","Returns a detached nested property table copy."],["set_property","set_property(key, value)","Returns the previous value and changes only the run-local overlay; invocation facts are read-only."]])this.functionDocs.set(e,{name:e,signature:n,description:r,module:"core",category:"Properties"});this.functionDocs.set("expand",{name:"expand",signature:"expand(text, [vars])",description:"Resolve ${name} from an explicit vars map, ${PROPS.path}, and ${ARGV[n]}; $${ escapes, no caller-local capture or recursive expansion.",module:"core",category:"Strings"})}prepareChildEnv(e,n){let r={...n.hostContext?.env??process.env};return this.bindChildEnv(e,n,dHe(r))}bindChildEnv(e,n,r){let s=e.functions.get("set_env"),i=n.hostContext?.platform??n.platform??process.platform;s&&e.functions.set("set_env",{...s,fn:(a,l)=>{if(typeof a!="string"||a===""||a.includes("=")||a.includes("\0"))throw new Error("set_env: the name must be a non-empty string without '=' or NUL");if(i==="win32")for(let c of Object.keys(r))c!==a&&c.toUpperCase()===a.toUpperCase()&&delete r[c];return l==null?delete r[a]:r[a]=String(l),!0}});for(let a of["env","getenv"]){let l=e.functions.get(a);l&&e.functions.set(a,{...l,fn:(c,u=null)=>Object.hasOwn(r,String(c))?r[String(c)]??u:u})}let o={pos:(...a)=>Gie(Dy(r),...a),set_pos:(...a)=>Vie(Dy(r),...a),regex_match_pos:(a,l,c="")=>Xk(Dy(r),a,l,c),regex_find_pos:(a,l,c="")=>Jie(Dy(r),a,l,c),regex_test_pos:(a,l,c="")=>Kie(Dy(r),a,l,c)};for(let[a,l]of Object.entries(o)){let c=e.functions.get(a);c&&e.functions.set(a,{...c,fn:l,dryRun:di(u=>l(...u))})}return r}registerComputedFunction(...e){this.registerFunction(...e);let[n,r]=e,s=this.hostFunctions.get(n);return s.dryRun=di((i,o)=>r(...i)),this}registerFileReader(...e){this.registerFunction(...e);let[n,r]=e,s=this.hostFunctions.get(n);return s.dryRun=di((i,o)=>NHe(i)?(o.record(n,i,"dummy"),Goe(s.signature?.returnType??void 0)):r(...i)),this}installCoreDryCallbacks(){let e=(r,s)=>{let i=this.hostFunctions.get(r);i&&(i.dryRun=di(s))};e("system",(r,s)=>{let i=rx(r[0],Ooe(r[1]).timeoutMs,s.platform);return s.record(s.functionName,r,"dummy",i),{...Xoe}}),e("print",(r,s)=>{let i=ex(r);return s.output("print",i,r),i}),e("println",(r,s)=>{let i=ex(r);return s.output("println",i,r),i}),e("printf",([r,...s],i)=>{let o=Mk(r,s,"printf");return i.output("printf",o,[r,...s]),o}),e("error",Dj),e("exit",$j),e("warning",i1),e("require",([r,s],i)=>zU(r,s,o=>i.fail(o))),e("env",([r,s=null],i)=>i.env[r]??s),e("getenv",([r,s=null],i)=>i.env[r]??s),e("now",(r,s)=>s.now),e("timestamp",(r,s)=>Math.floor(s.now/1e3)),e("date",([r],s)=>new Date(r??s.now).toISOString()),e("which",([r],s)=>Tk(r,s.cwd,s.env,s.platform));let n=this.hostFunctions.get("temp_file");n&&(n.dryRun=()=>null)}registerDefaultDocs(){for(let e of MHe)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of DHe)this.registerFunctionDoc({...e,module:e.module??"core"});for(let e of $He)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){let n=PU({...e,module:e.module??this.currentRegisteringModule});this.functionDocs.set(e.name,n);let r=this.hostFunctions.get(e.name);return r&&this.hostFunctions.set(e.name,{...r,doc:n,signature:go(e.name,r.arity,r.params,r.returnType,n)}),this}registerModule(e,n){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let r=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,n)}finally{this.currentRegisteringModule=r}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return this.getFunctionDocs().filter(n=>(n.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return[...this.functionDocs.keys()].map(e=>this.getFunctionDoc(e))}getFunctionDoc(e){let n=this.functionDocs.get(e),r=this.hostFunctions.get(e)?.signature;return!n||!r?n:{...n,...r.returnType?{returns:{type:r.returnType,description:n.returns?.description??"Declared result type"}}:{}}}getFunctionCategories(){let e=new Set;for(let n of this.functionDocs.values())e.add(n.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(n=>n.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFileReader("read_file",n=>q.readFileSync(n,"utf-8"),1,{description:"Reads entire file as UTF-8 string",returnType:"string"}),this.registerFileReader("read",n=>q.readFileSync(n,"utf-8"),1,{description:"Reads entire file as UTF-8 string",returnType:"string"}),this.registerFileReader("read_lines",n=>{let r=q.readFileSync(n,"utf-8"),s=r.length>0;return r.endsWith(`\r
|
|
4825
|
+
`:""),A=O.exitCode!==void 0?O.exitCode:O.success&&!O.errors?.length?0:1,C={success:O.success&&A===0,stdout:P,output:[...O.output],value:O.value??null,exit_code:A,code:A,errors:O.errors??[]};for(let D of[...O.errors??[],...O.diagnostics.filter(j=>j.severity==="error").map(j=>j.message)])this.recordedErrors.push(D);return C}},arity:_?.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 b=e.get("http_get");(!b||b.isDefault)&&this.hostFunctions.set("http_get",{...b,fn:T=>this.isAsync?JBe(T):xoe(T),arity:b?.arity??1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let w=e.get("sleep_ms");(!w||w.isDefault)&&this.hostFunctions.set("sleep_ms",{...w,fn:T=>{if(typeof T!="number"||!Number.isFinite(T)||T<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(T>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(x=>setTimeout(x,T));let k=Date.now()+T;for(;Date.now()<k;);return null},arity:w?.arity??1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new mr,this.initialGlobals)for(let[r,s]of this.initialGlobals.entries())this.globalEnv.define(r,s);this.userFunctions.clear(),this.callDepth=0;for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.userFunctions.set(r.name,r);let n;for(let r of e.statements)r.kind!=="FunctionDeclStmt"&&(n=this.execStmt(r,this.globalEnv));return this.checkRootRemainder(e),n}enterRecover(e,n){if(n)throw new B("recover cannot be entered inside a parallel task",e.line,e.column,"RUNTIME",e.file);let r=this.recovery;if(r.entered.has(e))throw new B("recover statement already entered during this run",e.line,e.column,"RUNTIME",e.file);if(r.entered.add(e),r.active=!0,r.pending.length===0)return{start:0,consumed:!1};let s=r.pending.shift(),i=e.points.findIndex(o=>o.name===s);if(i<0)throw new B(`Unknown resumepoint '${s}' in entered recover; available: ${e.points.map(o=>o.name).join(", ")}`,e.line,e.column,"RUNTIME",e.file);return{start:i,consumed:!0}}enterPoint(e,n){this.recovery.stack.length=e,this.recovery.stack.push(n),this.publishResumepoint()}leaveRecover(e){this.recovery.stack.length=e,this.publishResumepoint()}publishResumepoint(){this.recovery.probe.currentPath=this.recovery.stack.length>0?this.recovery.stack.join("."):null,this.globalEnv.define("RESUMEPOINT",this.recovery.stack.length>0?this.recovery.stack.join("."):null)}checkRemainder(e){if(In(this.abortSignal),this.recovery.pending.length>0)throw new B(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(In(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new B(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRecoverRead(e,n,r,s){let i=this.recoverScopedReads.get(r);if(!i)return;let o=this.recovery.envs.get(i);if(o&&n.resolveBinding(e)?.env!==o)throw new B(`Variable '${e}' was read before its binding was initialized`,s.line,s.column,"RUNTIME",s.file)}recoverWriteScope(e,n){let r=this.recoverScopedWrites.get(n)?.get(e);return r?this.recovery.envs.get(r):void 0}execStmt(e,n){let r=this.tracer;if(!r||e.kind==="BlockStmt"||e.kind==="FunctionDeclStmt"||e.kind==="ImportStmt"||e.kind==="PackageStmt")return this.execStmtCore(e,n);r.stmt(e,n),e.kind==="BreakStmt"?r.jump("break",e):e.kind==="ContinueStmt"&&r.jump("continue",e);try{return this.execStmtCore(e,n)}catch(s){throw s instanceof Ln?e.kind==="ReturnStmt"&&r.jump("return",e):s instanceof Zn||s instanceof Yn||r.raise(s,e),s}}execStmtCore(e,n){switch(this.dry?.at(e),In(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let r=new mr(n);for(let s of e.statements)this.execStmt(s,r);return}case"VarDeclStmt":{let r=null;return e.initializer&&(r=this.evalExpr(e.initializer,n)),e.constant?(r=Fk(r),n.defineConst(e.name,r),r):(n.define(e.name,r),r)}case"TupleVarDeclStmt":{let r=this.evalExpr(e.initializer,n);if(!Array.isArray(r))throw new B(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?(this.tracer?.branch("then",e.thenBranch,n),this.execStmt(e.thenBranch,n)):e.elseBranch?(this.tracer?.branch("else",e.elseBranch,n),this.execStmt(e.elseBranch,n)):void 0}case"WhileStmt":{let r=0,s=this.tracer,i=s?.loopEnter("while",e),o="done";try{for(;!this.dry?.loop(r,e)&&this.isTruthy(this.evalExpr(e.condition,n));){r++,s?.loopIter(i,r,e,n);try{this.execStmt(e.body,n)}catch(a){if(a instanceof Zn){o="break";break}if(a instanceof Yn)continue;throw a}}}catch(a){throw o=a instanceof Ln?"return":"raise",a}finally{s?.loopExit(i,r,o)}return}case"ForInStmt":{let r=Zie(this.evalExpr(e.iterable,n),e,this.dry),s=0,i=this.tracer,o=i?.loopEnter("foreach",e),a="done";try{for(let l=0;(l<r.length||this.dry?.loopLimit!==void 0&&s===this.dry.loopLimit)&&!this.dry?.loop(s,e);l++){let c=r[l];s++;let u=new mr(n);u.define(e.name,c),i?.loopIter(o,s,e,u);try{if(e.body.kind==="BlockStmt")for(let d of e.body.statements)this.execStmt(d,u);else this.execStmt(e.body,u)}catch(d){if(d instanceof Zn){a="break";break}if(d instanceof Yn)continue;throw d}}}catch(l){throw a=l instanceof Ln?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ForStmt":{let r=new mr(n);e.init&&this.execStmt(e.init,r);let s=0,i=this.tracer,o=i?.loopEnter("for",e),a="done";try{for(;!this.dry?.loop(s,e);){if(e.condition){let l=this.evalExpr(e.condition,r);if(!this.isTruthy(l))break}s++,i?.loopIter(o,s,e,r);try{this.execStmt(e.body,r)}catch(l){if(l instanceof Zn){a="break";break}if(!(l instanceof Yn))throw l}if(this.dry?.loop(s,e))break;e.update&&this.evalExpr(e.update,r)}}catch(l){throw a=l instanceof Ln?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new Ln(r)}case"BreakStmt":throw new Zn;case"ContinueStmt":throw new Yn;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new B("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let r=this.evalExpr(e.expr,n);return Sk(this.invokeNamed("system",[r],n,e.expr.line,e.expr.column,e.expr.file))}return Uie(e.expr)?Sk(this.evalExpr(e.expr,n)):this.evalExpr(e.expr,n)}case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new mr(n);this.recovery.envs.set(e,s);let i=this.recovery.stack.length;try{for(let o=r.start;o<e.points.length;o++){let a=e.points[o];this.enterPoint(i,a.name);for(let l of a.statements)this.execStmt(l,s);r.consumed&&o===r.start&&this.checkRemainder(a)}}catch(o){throw $s(this.recovery,o),o}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(In(this.abortSignal),e.kind){case"CommandExpr":{let r=[];for(let i of e.words){let o=[];for(let a of i.pieces)o.push(typeof a=="string"?a:this.evalExpr(a.expression,n));r.push(o)}let s=zie(e,r);return e.mode==="cmd"?s:this.invokeNamed("system",[s],n,e.line,e.column,e.file)}case"InterpolatedStringExpr":{let r="";for(let s of e.parts)r+=typeof s=="string"?s:e1(this.evalExpr(s.expression,n),s);return r}case"ParallelMapExpr":case"ParallelExpr":throw new B("Concurrency constructs require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"PathLiteralExpr":return roe(e,this.platform);case"DataBlockExpr":{e.schemaHandle&&this.resolveIdentifier(e.schemaHandle,n,e);let r=Dk(e,o=>this.evalExpr(o.value,n)),s=e.marker==="dsl"?jU(e,Object.hasOwn(r,"with")?r.with:[]):[],i=[];for(let o of e.lines)for(let a of o.pieces)typeof a!="string"&&i.push(this.evalExpr(a.expression,n));return e.marker==="dsl"?this.constructLmcode(e,i,s):qU(e,r,i,this.compileOptions)}case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let r=this.evalExpr(e.value,n),s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return s?s.define(e.target,r):n.set(e.target,r),r}case"TupleAssignExpr":{let r=this.evalExpr(e.value,n);if(!Array.isArray(r))throw new B(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<r.length?r[s]:null,o=this.recovery.active?this.recoverWriteScope(e.targets[s],e):void 0;o?o.define(e.targets[s],i):n.set(e.targets[s],i)}return r}case"IndexAssignExpr":{let r=this.evalExpr(e.target,n),s=this.evalExpr(e.index,n),i=this.evalExpr(e.value,n);if(Array.isArray(r)||typeof r=="object"&&r!==null)return Array.isArray(r)&&typeof s=="number"&&s<0&&(s=r.length+s),Qn(r,s,i),i;throw new B("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,n);case"TupleExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ArrayExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ObjectExpr":{let r={};for(let s of e.properties)Qn(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Kk(e);if(r)try{this.dry&&this.dry.at(e);let o=this.dry?.prepareProperties(r);if(Rn(o))throw o.catch(()=>{}),Error("Async properties require dryRunAsync");return Ur(this.dry?this.dry.propertyView:this.resolveIdentifier("PROPS",n,e),r)}catch(o){throw this.dry?new B(o instanceof Error?o.message:String(o),e.line,e.column,"RUNTIME",e.file):o}let s=this.evalExpr(e.target,n),i=this.evalExpr(e.index,n);if(s==null)throw new B("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return eo.has(s)?ioe(s,i,e,this.dry):toe(s,i,e)}case"MethodCallExpr":{let r=this.evalExpr(e.receiver,n),s=e.args.map(i=>this.evalExpr(i,n));return noe(r,e,s)}case"UnaryExpr":{let r=this.evalExpr(e.operand,n),s=e.operator;if(s==="!")return!this.isTruthy(r);if(s==="-")return-r;throw new B(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.evalExpr(e.trueArm,n):this.evalExpr(e.falseArm,n)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?this.evalExpr(e.right,n):o}if(e.operator==="||"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?o:this.evalExpr(e.right,n)}let r=this.evalExpr(e.left,n),s=this.evalExpr(e.right,n),i=e.operator;switch(i){case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":if(s===0)throw new B("Division by zero",e.line,e.column,"RUNTIME",e.file);return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:throw new B(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{if(e.schemaOptions)return Ck(this.compileOptions)?.get(e);let r=e.args.map(s=>this.evalExpr(s,n));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),this.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}lmcodeOwner=new k_;constructLmcode(e,n,r){let s=p1(e,"RUNTIME",Fy(this.compileOptions),n,this.compileOptions,r),i=Ck(this.compileOptions).get(e);return this.lmcodeOwner.add(s,fa.bytesOf(s),fa.programOf(s),i.declaredHead,i.schema,!!this.dry),s}runLmcode(e,n,r){let s=i=>{throw i instanceof Fr?i:new B("run_lmcode: "+(i instanceof Error?i.message:String(i)),n.line,n.column,"RUNTIME",n.file)};try{if(e.length<1||e.length>2)throw Error("expected program and optional options map");let i=this.processContext,o=this.lmcodeOwner.plan(e[0],e[1],i.cwd,this.compileOptions?.hostContext?.env??process.env,Nk);if(!r&&!this.dry)throw Error("requires runAsync");let a=By.getStore()?.get(i.env)??i.env,l;if(this.dry){let d=o.builder?[...o.argv,...o.parts.flatMap(p=>p.fragment),...o.args]:[...o.template??[...o.argv,"--lmcode","$DSLFILE"],...o.args];this.dry.record("run_lmcode",[],n,"lmcode-host-dry",d),l=this.dry.entries.at(-1),l.host=o.argv[0],l.slots=o.builder?o.parts.map((p,f)=>f):[0]}let c={dry:!!this.dry,cwd:i.cwd,env:{...a},args:o.args,signal:this.abortSignal,stdout:d=>{l?l.stdout=(l.stdout??"")+d:this.stdout(d,!0)},stderr:d=>{l?l.stderr=(l.stderr??"")+d:this.stderr?.(d)},...o.builder?{parts:o.parts,contracts:o.contracts}:{template:o.template,contract:o.contract}},u=d=>(l&&(l.envelope=this.dry.snapshot(d)),d);return r?this.lmcodeOwner.track(pB(o.bytes,o.argv,c)).then(u).catch(s):u(fB(o.bytes,o.argv,c))}catch(i){return s(i)}}buildLmcode(e,n){let r=s=>{throw new B("lmcode_build: "+(s instanceof Error?s.message:String(s)),n.line,n.column,"RUNTIME",n.file)};try{if(e.length!==1)throw Error("expected exactly one host descriptor, command-prefix string or string list");let s=this.processContext,i=this.compileOptions?.hostContext?.env??process.env,o=e[0];if(kf(o)){if(!o.program)throw Error("schema file descriptors are not hosts; pass an explicit command prefix");return this.lmcodeOwner.build(o.program,s.cwd,i,Nk)}return this.lmcodeOwner.build(o,s.cwd,i,Nk)}catch(s){return r(s)}}resolveIdentifier(e,n,r){if(this.recovery.active&&this.checkRecoverRead(e,n,r,r),n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&o1.has(s)){this.dry&&this.dry.at(r);try{let i=o1.get(s)();return Rn(i)?i.catch(o=>{throw new B(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new B(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new Qi(e);throw new B(`Variable '${e}' was read before its binding was initialized`,r.line,r.column,"RUNTIME",r.file)}resolveCallTarget(e,n){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;let r=n.get(e);return r instanceof Qi?r.name:e}invokeNamed(e,n,r,s,i,o){let a=this.tracer,l=this.userFunctions.get(e);if(!a||!l&&!this.hostFunctions.has(e))return this.invokeNamedCore(e,n,r,s,i,o);if(e==="llm_prompt"||e==="llm_models"||e==="llm_providers"||e==="tool_call"||e==="tool_parse"||e==="tool_specs")return this.invokeNamedCore(e,n,r,s,i,o);a.call(e,l?l.params.map((u,d)=>({name:u,value:n[d]})):n.map((u,d)=>({value:e==="set_env"&&d===1?"<redacted>":u})),!l,l);let c;try{c=this.invokeNamedCore(e,n,r,s,i,o)}catch(u){throw u instanceof Ln||u instanceof Zn||u instanceof Yn||a.raise(u,{line:s,column:i,file:o}),a.ret(null,!0,u),u}return a.ret(!l&&(e==="env"||e==="getenv")&&c!==null&&c!==void 0?"<redacted>":c),c}invokeNamedCore(e,n,r,s,i,o){if(this.dry?.at({line:s,column:i,file:o}),e==="lmcode_build")return this.buildLmcode(n,{line:s,column:i,file:o});if(e==="run_lmcode")return this.runLmcode(n,{line:s,column:i,file:o},!1);if(In(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Ek)throw this.callDepth--,new B(`Execution fuel exhausted: maximum function call depth exceeded (${Ek})`,s,i,"RUNTIME",o);let l=new mr(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],n[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Ln)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{if(!this.dry&&a.dryRun===i1){Uy(a,n);let u=String(n[0]);return this.warningDiagnostics.push({severity:"warning",message:u,line:s,column:i,file:o}),u}if(this.dry){let u=ooe(a,n,e,{line:s,column:i,file:o},this.dry,this.compileOptions);if(u.skip)return u.value;let d=u.invoke();if(this.dry.check(),Rn(d)&&(Promise.resolve(d).catch(()=>{}),this.dry.fail("Async host requires dryRunAsync",{line:s,column:i,file:o})),this.dry.failure)throw new Fr(this.dry.failure.message);return Eu(d)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:o}),d}let l=Uy(a,n);if(a.returnsResource)throw new B(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);In(this.abortSignal);let c=NU(a,l);if(a.returnsResource&&Rn(c))throw c.then(u=>{try{u&&typeof u.finalizeSync=="function"?u.finalizeSync():u&&typeof u.close=="function"&&u.close()}catch{}},()=>{}),new Error("returns a resource asynchronously; use engine.runAsync()");return c}catch(l){throw this.dry?.captureFailure(l,{line:s,column:i,file:o}),l instanceof rs||l?.name==="LMScriptExit"||l?.isControlFlow?l:new B(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new B(`'${e}' is not a function`,s,i,"RUNTIME",o):new B(bf(e,"Undefined function"),s,i,"RUNTIME",o)}ownerFor(e,n){let r=this.resources.scopeFor(e),s=this.temporaryScopes.get(n),i=s&&s[s.length-1];return i&&i.base===r?i:r}pushTemporaryScope(e,n){let r=this.temporaryScopes.get(e);r?r.push(n):this.temporaryScopes.set(e,[n])}popTemporaryScope(e){let n=this.temporaryScopes.get(e);n?.pop(),n&&n.length===0&&this.temporaryScopes.delete(e)}async execLoopBodyAsync(e,n,r){await this.execStmtAsync(e,n,r)}resourceError(e,n,r){return new B(`Resource ${this.resources.describe(e)} ${n}`,r.line,r.column,"RUNTIME",r.file)}refuseResource(e,n,r){if(Ft(e))throw this.resourceError(e,n,r)}bindResource(e,n,r,s){let i=this.resources.bind(e,n,r);if(i)throw new B(i.charAt(0).toUpperCase()+i.slice(1),s.line,s.column,"RUNTIME",s.file)}async resourceCallArgs(e,n,r,s,i,o){if(!r.some(Ft))return r;let a={line:s,column:i,file:o};if(!e.usesResource&&!e.closesResource)throw this.resourceError(r.find(Ft),`cannot be passed to '${n}'`,a);let l=[];for(let c of r){if(!Ft(c)){l.push(c);continue}let u=this.resources.lookup(c);if(!u)throw this.resourceError(c,`cannot be used by '${n}': it belongs to another run`,a);if(e.closesResource)this.resources.borrow(c),await this.resources.close(u,r.slice(1));else if(u.state!=="open")throw this.resourceError(c,`is ${u.state==="closing"?"closing":"closed"}: '${n}' cannot use it`,a);this.resources.borrow(c),l.push(u.raw)}return l}registerHostResource(e,n,r,s,i,o){if(e==null)return e;if(typeof e!="object"||typeof e.close!="function"||typeof e.id!="string"&&typeof e.id!="number"||String(e.id)==="")throw new Error("a returnsResource host must return null or an object with a close method and a stable id");return this.resources.register(e,n,`${o??"<main>"}:${s}:${i}`,r)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new mr,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear();for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let n=this.nextTaskId++;this.recovery.rootTaskId=n;let r;try{for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(r=await this.execStmtAsync(s,this.globalEnv,n))}catch(s){throw $s(this.recovery,s),this.resources.root.failure=bu(s),s}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),Ft(r))r=null;else if(aoe()){let s=Eu(r);if(s)throw new B(Ft(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:Ak(s,"run"),1,1,"RUNTIME")}return r}coOf(e){return e===this.recovery.rootTaskId?"main":"t"+e}async execStmtAsync(e,n,r){let s=this.tracer;if(!s||e.kind==="BlockStmt"||e.kind==="FunctionDeclStmt"||e.kind==="ImportStmt"||e.kind==="PackageStmt")return this.execStmtAsyncCore(e,n,r);let i=this.coOf(r);s.stmt(e,n,i),e.kind==="BreakStmt"?s.jump("break",e,i):e.kind==="ContinueStmt"&&s.jump("continue",e,i);try{return await this.execStmtAsyncCore(e,n,r)}catch(o){throw o instanceof Ln?e.kind==="ReturnStmt"&&s.jump("return",e,i):o instanceof Zn||o instanceof Yn||s.raise(o,e,i),o}}async execStmtAsyncCore(e,n,r){switch(this.dry?.at(e),In(this.abortSignal),e.kind){case"PackageStmt":return;case"ImportStmt":return;case"BlockStmt":{let s=new mr(n);if(!this.resourcesEnabled){for(let o of e.statements)await this.execStmtAsync(o,s,r);return}let i=this.resources.enterScope(s,this.ownerFor(n,r),"block");try{for(let o of e.statements)await this.execStmtAsync(o,s,r)}catch(o){throw $s(this.recovery,o),i.failure=bu(o),o}finally{i.records.length>0&&await this.resources.drain(i)}return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,n,r)),Ft(s)&&this.bindResource(s,n,e.name,e),e.constant?(s=Fk(s),n.defineConst(e.name,s),s):(n.define(e.name,s),s)}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(Array.isArray(s))for(let i=0;i<e.names.length&&i<s.length;i++)this.bindResource(s[i],n,e.names[i],e);if(!Array.isArray(s))throw new B(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?(this.tracer?.branch("then",e.thenBranch,n,this.coOf(r)),await this.execStmtAsync(e.thenBranch,n,r)):e.elseBranch?(this.tracer?.branch("else",e.elseBranch,n,this.coOf(r)),await this.execStmtAsync(e.elseBranch,n,r)):void 0}case"WhileStmt":{let s=0,i=this.tracer,o=this.coOf(r),a=i?.loopEnter("while",e,o),l="done";try{for(;!this.dry?.loop(s,e)&&this.isTruthy(await this.evalExprAsync(e.condition,n,r));){s++,i?.loopIter(a,s,e,n,o);try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,n,r):await this.execStmtAsync(e.body,n,r)}catch(c){if(c instanceof Zn){l="break";break}if(c instanceof Yn)continue;throw c}}}catch(c){throw l=c instanceof Ln?"return":"raise",c}finally{i?.loopExit(a,s,l,o)}return}case"ForInStmt":{let s=Zie(await this.evalExprAsync(e.iterable,n,r),e,this.dry),i=0,o=this.tracer,a=this.coOf(r),l=o?.loopEnter("foreach",e,a),c="done";try{for(let u=0;(u<s.length||this.dry?.loopLimit!==void 0&&i===this.dry.loopLimit)&&!this.dry?.loop(i,e);u++){let d=s[u];i++;let p=new mr(n);p.define(e.name,d),o?.loopIter(l,i,e,p,a);let f=this.resourcesEnabled?this.resources.enterScope(p,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let m of e.body.statements)await this.execStmtAsync(m,p,r);else await this.execStmtAsync(e.body,p,r)}catch(m){throw $s(this.recovery,m),f&&(f.failure=bu(m)),m}finally{f&&f.records.length>0&&await this.resources.drain(f)}}catch(m){if(m instanceof Zn){c="break";break}if(m instanceof Yn)continue;throw m}}}catch(u){throw c=u instanceof Ln?"return":"raise",u}finally{o?.loopExit(l,i,c,a)}return}case"ForStmt":{let s=new mr(n),i=this.resourcesEnabled?this.resources.enterScope(s,this.ownerFor(n,r),"for"):void 0;try{e.init&&await this.execStmtAsync(e.init,s,r);let o=0,a=this.tracer,l=this.coOf(r),c=a?.loopEnter("for",e,l),u="done";try{for(;!this.dry?.loop(o,e);){if(e.condition){let d=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(d))break}o++,a?.loopIter(c,o,e,s,l);try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,s,r):await this.execStmtAsync(e.body,s,r)}catch(d){if(d instanceof Zn){u="break";break}if(!(d instanceof Yn))throw d}if(this.dry?.loop(o,e))break;e.update&&await this.evalExprAsync(e.update,s,r)}}catch(d){throw u=d instanceof Ln?"return":"raise",d}finally{a?.loopExit(c,o,u,l)}}catch(o){throw $s(this.recovery,o),i&&(i.failure=bu(o)),o}finally{i&&i.records.length>0&&await this.resources.drain(i)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,n,r):null;throw Ft(s)&&this.refuseResource(s,"cannot be returned: a resource stays with its owner (return copied data instead)",e),new Ln(s)}case"BreakStmt":throw new Zn;case"ContinueStmt":throw new Yn;case"SyncAssignStmt":{let s=this.recovery.active?this.recoverWriteScope(e.target,e):void 0,i=s?{env:s,name:e.target}:n.resolveBinding(e.target);if(!i)throw new B(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let o=`bind:${i.env.id}:${i.name}`;await this.lockManager.getBindingLock(o).withLock(async()=>{let l=await this.evalExprAsync(e.value,n,r);this.bindResource(l,i.env,i.name,e),i.env.resolveBinding(i.name)?.env===i.env?i.env.set(i.name,l):i.env.define(i.name,l)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new B("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,n,r),a=await this.evalExprAsync(e.value,n,r);this.refuseResource(s,"cannot be modified",e),this.refuseResource(o,"cannot be used as a map key",e),this.refuseResource(a,"cannot be stored in a container",e),Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Qn(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new B("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 B(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],n,r);if(o==null||typeof o!="object"&&typeof o!="function")throw new B("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let s=await this.evalExprAsync(e.expr,n,r);return Sk(await this.invokeCallAsync("system",[s],n,e.expr.line,e.expr.column,r,e.expr.file))}return Uie(e.expr)?Sk(await this.evalExprAsync(e.expr,n,r)):await this.evalExprAsync(e.expr,n,r)}case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new mr(n);this.recovery.envs.set(e,i);let o=this.resourcesEnabled?this.resources.enterScope(i,this.ownerFor(n,r),"block"):void 0,a=this.recovery.stack.length;try{for(let l=s.start;l<e.points.length;l++){let c=e.points[l];this.enterPoint(a,c.name);for(let u of c.statements)await this.execStmtAsync(u,i,r);s.consumed&&l===s.start&&this.checkRemainder(c)}}catch(l){throw $s(this.recovery,l),o&&(o.failure=bu(l)),l}finally{try{o&&o.records.length>0&&await this.resources.drain(o)}finally{this.leaveRecover(a)}}return}default:return}}async evalExprAsync(e,n,r){switch(In(this.abortSignal),e.kind){case"CommandExpr":{let s=[];for(let o of e.words){let a=[];for(let l of o.pieces)a.push(typeof l=="string"?l:await this.evalExprAsync(l.expression,n,r));s.push(a)}let i=zie(e,s);return e.mode==="cmd"?i:await this.invokeCallAsync("system",[i],n,e.line,e.column,r,e.file)}case"InterpolatedStringExpr":{let s="";for(let i of e.parts){if(typeof i=="string"){s+=i;continue}let o=await this.evalExprAsync(i.expression,n,r);this.refuseResource(o,"cannot be converted to text",i.expression),s+=e1(o,i)}return s}case"LiteralExpr":return e.value;case"PathLiteralExpr":return roe(e,this.platform);case"DataBlockExpr":{e.schemaHandle&&this.resolveIdentifier(e.schemaHandle,n,e);let s={};for(let a of e.options)s[a.name]=await this.evalExprAsync(a.value,n,r);let i=e.marker==="dsl"?jU(e,Object.hasOwn(s,"with")?s.with:[]):[],o=[];for(let a of e.lines)for(let l of a.pieces)typeof l!="string"&&o.push(await this.evalExprAsync(l.expression,n,r));return e.marker==="dsl"?this.constructLmcode(e,o,i):qU(e,Dk(e,a=>s[a.name]),o,this.compileOptions)}case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let s=await this.evalExprAsync(e.value,n,r),i=this.recovery.active?this.recoverWriteScope(e.target,e):void 0;return Ft(s)&&this.bindResource(s,i??n.writeTarget(e.target),e.target,e),i?i.define(e.target,s):n.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,n,r);if(!Array.isArray(s))throw new B(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null,a=this.recovery.active?this.recoverWriteScope(e.targets[i],e):void 0;Ft(o)&&this.bindResource(o,a??n.writeTarget(e.targets[i]),e.targets[i],e),a?a.define(e.targets[i],o):n.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,n,r),i=await this.evalExprAsync(e.index,n,r),o=await this.evalExprAsync(e.value,n,r);if(this.refuseResource(s,"cannot be modified",e),this.refuseResource(i,"cannot be used as a map key",e),this.refuseResource(o,"cannot be stored in a container",e),Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Qn(s,i,o),o;throw new B("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,n,r);case"TupleExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ArrayExpr":{let s=[];for(let i of e.elements){let o=await this.evalExprAsync(i,n,r);this.refuseResource(o,"cannot be stored in a container",i),s.push(o)}return s}case"ObjectExpr":{let s={};for(let i of e.properties){let o=await this.evalExprAsync(i.value,n,r);this.refuseResource(o,"cannot be stored in a container",i.value),Qn(s,i.key,o)}return s}case"ParallelMapExpr":{let s=await this.evalExprAsync(e.items,n,r),i=await this.evalExprAsync(e.callback,n,r),o=e.limit?await this.evalExprAsync(e.limit,n,r):void 0,a=b=>{throw new B("parallel_map: "+b,e.line,e.column,"RUNTIME",e.file)};Array.isArray(s)||a("items must be a list"),i instanceof Qi||a("fn must be a function reference taking one argument");let l=this.userFunctions.get(i.name),c=this.hostFunctions.get(i.name),u=l?l.params.length:c?.signature?.publicArity??c?.arity??c?.fn.length;(u===void 0||(typeof u=="number"?u!==1:u.min>1||(u.max??1/0)<1))&&a("fn must be a function taking one argument");let d=e.limit?o:this.processContext?.env?.LMSCRIPT_PARALLEL_LIMIT??process.env.LMSCRIPT_PARALLEL_LIMIT,p=e.limit?d:d===void 0?KBe:typeof d=="string"&&/^[0-9]+$/.test(d)?Number(d):NaN;(typeof p!="number"||!Number.isSafeInteger(p)||p<1)&&a("limit must be a positive safe integer"+(e.limit?"":" (LMSCRIPT_PARALLEL_LIMIT)"));let f=Eu(s);f&&a(Ft(f)?"resource handles cannot cross a task input boundary":Ak(f,"parallel_map input"));let m=s.slice(),g=new Array(m.length),h=0,y=!1,v=async()=>{for(;!y&&h<m.length;){if(this.abortSignal?.aborted||this.dry?.failure||this.dry?.scriptExit){y=!0;break}let b=h++;try{let w=await this.runParallelTask(e,n,r,T=>this.invokeCallAsync(i.name,[m[b]],n,e.line,e.column,T,e.file),!0);g[b]={status:"fulfilled",value:w}}catch(w){g[b]={status:"rejected",reason:w}}}};await Promise.all(Array.from({length:Math.min(this.dry?1:p,m.length)},v));let _=[];for(let b=0;b<h;b++){let w=g[b];if(w.status==="rejected")throw w.reason;_.push(w.value)}return In(this.abortSignal),_}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=c=>this.runParallelTask(c,n,r,u=>this.evalExprAsync(c,n,u));if(this.dry){let c=[];for(let u of e.tasks)this.dry.at(u),c.push(await s(u));return c}let i=e.tasks.map(s),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=Kk(e);if(s)try{return this.dry&&(this.dry.at(e),await this.dry.prepareProperties(s)),Ur(this.dry?this.dry.propertyView:await this.resolveIdentifier("PROPS",n,e),s)}catch(a){throw this.dry?new B(a instanceof Error?a.message:String(a),e.line,e.column,"RUNTIME",e.file):a}let i=await this.evalExprAsync(e.target,n,r),o=await this.evalExprAsync(e.index,n,r);if(this.refuseResource(o,"cannot be used as a map key",e),Ft(i)){if(o==="id")return i.id;throw this.resourceError(i,`has no readable field '${String(o)}' (only id)`,e)}if(i==null)throw new B("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return eo.has(i)?ioe(i,o,e,this.dry):toe(i,o,e)}case"MethodCallExpr":{let s=await this.evalExprAsync(e.receiver,n,r),i=[];for(let o of e.args)i.push(await this.evalExprAsync(o,n,r));return this.refuseResource(s,"has no methods",e),noe(s,e,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,n,r),i=e.operator;if(i==="!")return!this.isTruthy(s);if(this.refuseResource(s,"cannot be used in arithmetic",e),i==="-")return-s;throw new B(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,n,r):await this.evalExprAsync(e.falseArm,n,r)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?await this.evalExprAsync(e.right,n,r):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,n,r)}let s=await this.evalExprAsync(e.left,n,r),i=await this.evalExprAsync(e.right,n,r),o=e.operator;switch((Ft(s)||Ft(i))&&o!=="=="&&o!=="!="&&(this.refuseResource(s,`cannot be used with '${o}' (only ==, != and truth tests)`,e),this.refuseResource(i,`cannot be used with '${o}' (only ==, != and truth tests)`,e)),o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new B("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 B(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{if(e.schemaOptions)return Ck(this.compileOptions)?.get(e);let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,n,r));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),await this.invokeCallAsync(e.callee,s,n,e.line,e.column,r,e.file)}}}async runParallelTask(e,n,r,s,i=!1){let o=this.nextTaskId++;this.asyncCallDepth.set(o,this.asyncCallDepth.get(r)??0);let a=this.resourcesEnabled?this.resources.temporaryScope(this.ownerFor(n,r),"task",this.resources.scopeFor(n)):void 0;a&&this.pushTemporaryScope(o,a);let l=this.processContext?.env,c=l?new Map(By.getStore()).set(l,{...l}):void 0;try{In(this.abortSignal);let u=await(c?By.run(c,()=>s(o)):s(o));In(this.abortSignal);let d=i||aoe()?Eu(u):void 0;if(d)throw new B(Ft(d)?`Resource ${this.resources.describe(d)} cannot be a parallel task result: it stays with the task that opened it`:Ak(d,"parallel task"),e.line,e.column,"RUNTIME",e.file);return u}catch(u){throw this.dry?.captureFailure(u,e),$s(this.recovery,u),a&&(a.failure=bu(u)),u}finally{try{a&&(this.popTemporaryScope(o),a.records.length>0&&await this.resources.drain(a))}finally{this.asyncCallDepth.delete(o)}}}async invokeCallAsync(e,n,r,s,i,o,a){let l=this.tracer,c=this.resolveCallTarget(e,r),u=this.userFunctions.get(c);if(!l||!u&&!this.hostFunctions.has(c))return this.invokeCallAsyncCore(e,n,r,s,i,o,a);if(c==="llm_prompt"||c==="llm_models"||c==="llm_providers"||c==="tool_call"||c==="tool_parse"||c==="tool_specs")return this.invokeCallAsyncCore(e,n,r,s,i,o,a);let d=this.coOf(o);l.call(c,u?u.params.map((f,m)=>({name:f,value:n[m]})):n.map((f,m)=>({value:c==="set_env"&&m===1?"<redacted>":f})),!u,u,d);let p;try{p=await this.invokeCallAsyncCore(e,n,r,s,i,o,a)}catch(f){throw f instanceof Ln||f instanceof Zn||f instanceof Yn||l.raise(f,{line:s,column:i,file:a},d),l.ret(null,!0,f,d),f}return l.ret(!u&&(c==="env"||c==="getenv")&&p!==null&&p!==void 0?"<redacted>":p,!1,void 0,d),p}async invokeCallAsyncCore(e,n,r,s,i,o,a){this.dry?.at({line:s,column:i,file:a});let l=this.resolveCallTarget(e,r);if(l==="lmcode_build")return this.buildLmcode(n,{line:s,column:i,file:a});if(l==="run_lmcode")return await this.runLmcode(n,{line:s,column:i,file:a},!0);if(In(this.abortSignal),this.userFunctions.has(l)){let c=this.userFunctions.get(l),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>Ek)throw this.asyncCallDepth.set(o,u-1),new B(`Execution fuel exhausted: maximum function call depth exceeded (${Ek})`,s,i,"RUNTIME",a);let d=new mr(this.globalEnv,!0),p=this.resourcesEnabled?this.resources.enterScope(d,this.ownerFor(r,o),`function ${l}`):void 0;for(let f=0;f<c.params.length;f++)p&&this.resources.borrow(n[f]),d.define(c.params[f],n[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,d,o)}catch(f){if(f instanceof Ln)return f.value;throw this.dry?.captureFailure(f),$s(this.recovery,f),p&&(p.failure=bu(f)),f}finally{p&&p.records.length>0&&await this.resources.drain(p),this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{if(!this.dry&&c.dryRun===i1){Uy(c,n);let g=String(n[0]);return this.warningDiagnostics.push({severity:"warning",message:g,line:s,column:i,file:a}),g}if(this.dry){let g=ooe(c,n,l,{line:s,column:i,file:a},this.dry,this.compileOptions);if(g.skip)return g.value;let h=await this.dry.wait(g.invoke());if(this.dry.failure)throw new Fr(this.dry.failure.message);return Eu(h)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:a}),h}let u=Uy(c,n),d=PHe(u)?await this.resourceCallArgs(c,l,u,s,i,a):u,f=c.returnsResource||c.usesResource||c.closesResource?Zoe.run({runtime:this.resources,scope:this.ownerFor(r,o),site:(a??"<main>")+":"+s+":"+i},()=>NU(c,d)):NU(c,d),m=f instanceof Promise?await f:f;return c.returnsResource?this.registerHostResource(m,l,this.ownerFor(r,o),s,i,a):m}catch(u){throw this.dry?.captureFailure(u,{line:s,column:i,file:a}),u instanceof rs||u?.name==="LMScriptExit"||u?.isControlFlow?u:new B(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new B(`'${l}' is not a function`,s,i,"RUNTIME",a):new B(bf(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},MHe=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. Function bodies establish an isolated local variable scope for assignments, preventing accidental mutation of caller variables.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel_map",category:"Language Constructs",signature:"parallel_map(items, fn[, limit])",description:"Bounded asynchronous fan-out over a runtime list; ordered own-data results, all inputs settle before the first indexed failure. Default 8 (LMSCRIPT_PARALLEL_LIMIT), no fixed concurrency maximum.",example:"fn work(x) { return x * 2; } results = parallel_map([1, 2, 3], work, 2);"},{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;"}],DHe=[{name:"sha256",category:"Math & Utilities",signature:"sha256(text: string): string",description:"Lowercase SHA-256 hex of UTF-8 bytes; rejects non-string inputs.",example:'sha256("abc");'},{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("teams/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"parse_file_blocks",category:"Agent Files",signature:"parse_file_blocks(text: string): array",description:"Parses `=== FILE: relative/path ===` ... `=== END ===` blocks into [{path, content}]. Prose around blocks and whitespace around marker lines are ignored; content wrapped in exactly one markdown fence is unwrapped; content gets a final newline. Incomplete blocks (no END before the next FILE marker or the end of text) are dropped, so a truncated reply yields only its complete files.",example:"files = parse_file_blocks(reply);"},{name:"format_file_blocks",category:"Agent Files",signature:"format_file_blocks(files: array): string",description:"Formats [{path, content}] as file blocks; parse_file_blocks(format_file_blocks(files)) returns files (content normalised to end in a newline). Fence-wrapped content gets an outer fence; content containing a marker line is an error.",example:"context = format_file_blocks(read_tree(dir));"},{name:"write_files",category:"Agent Files",signature:"write_files(dir: string, files: array): map",description:"Writes [{path, content}] under dir (created if missing), each file atomically (temporary file + rename, mode of a replaced file kept). Rejects, never writes: empty, absolute, backslash or '..' paths, any .git segment, a path through a symlink leaving dir, a symlink or directory target, non-string content. Returns {written: [relative paths], rejected: [{path, reason}]}; under --dry-run the language skips it and returns an empty map without classifying paths.",example:'res = write_files(dir, parse_file_blocks(reply)); println("wrote", len(res.written));'},{name:"read_tree",category:"Agent Files",signature:"read_tree(dir: string, [options: map]): array",description:"Reads text files under dir as [{path, content}] sorted by path, relative with / separators. Skips symlinks, binary/non-UTF-8 files, files over maxBytes (omitted means no size limit) and the default ignores .git, node_modules, dist, build, target, .mp, __pycache__, *.lock, package-lock.json. Options: ignore (extra patterns), include (only matching files), maxBytes. A pattern without / matches a single name, with / the whole relative path; * ? ** globs. A missing dir reads as [].",example:'listing = format_file_blocks(read_tree(dir, {ignore: ["*.md"]}));'},{name:"kv_from_last_paragraph",category:"Agent Files",signature:"kv_from_last_paragraph(text: string): map",description:"Parses `key: value` lines (key [A-Za-z_][A-Za-z0-9_-]*, optional - or * bullet, value in one pair of backticks unwrapped, empty values skipped) of the last blank-line-separated paragraph; the last occurrence of a key wins and missing keys are absent. Trailing paragraphs without any key: value line are skipped as chatter, looking at most 3 paragraphs back; a paragraph holding a file-block marker stops the search.",example:'cfg = kv_from_last_paragraph(reply); if (has_key(cfg, "build_command")) { println(cfg.build_command); }'},{name:"split_command",category:"Agent Files",signature:"split_command(text: string): array",description:"Splits one command line into argv with POSIX quoting (single quotes, double quotes, backslash). Unquoted | & ; < > ( ) ` $, $ or ` inside double quotes, a word-start #, a newline and a leading NAME=value are errors, so model-supplied commands run through system() with shell:false and no shell semantics. Globs and ~ stay literal.",example:'res = system(split_command("npm run build"), {cwd: 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:"sql_read",category:"Database",signature:"sql_read(path: string, sql: string, [params: array|map]): array",description:"Runs ONE SELECT on a local SQLite file opened read-only and returns a list of maps (use SQL LIMIT for an explicit row bound). The SQL is a string literal; values are bound parameters.",example:'rows = sql_read("app.db", "SELECT name FROM t WHERE id = ?", [7]);'},{name:"sql_exec",category:"Database",signature:"sql_exec(path: string, sql: string, [params: array|map]): map",description:"Runs ONE write statement on a local SQLite file (created if missing; refuses the lmctl state database) and returns {changes, last_insert_rowid}. The SQL is a string literal; values are bound parameters.",example:'sql_exec("app.db", "INSERT INTO t(name) VALUES (?)", ["ada"]);'},{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:"run_lmcode",category:"File I/O",signature:"run_lmcode(program_or_builder: lmcode, options?: map): map",description:"Runs one opaque lmcode program or one sealed builder in a single host process. Single results are {ok,result}; builder results are {ok,result:[...],parts}. Args are copied; command is single-program only. Returns validated success/failure envelopes. Check never executes; dry invokes the host once with dry metadata and records its simulated envelope in PLAN.",example:'r = run_lmcode(program); require(r.ok, "host failed");'},{name:"lmcode_build",category:"File I/O",signature:"lmcode_build(host: lmcode schema | string | string list): lmcode_builder",description:"Creates a run-local one-process builder for lmcode programs. host is a host-bound load_schema descriptor or an explicit command prefix string/list; add programs with one $DSLFILE fragment each, then pass the builder to run_lmcode.",example:"builder = lmcode_build(schema); builder.add(program); result = run_lmcode(builder);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this run (isolated per parallel/parallel_map task): env()/getenv() and later system() calls, command literals, which(), run_script children and lm_* provider calls see it; null unsets the name, including an inherited value. The Node process environment and the caller's environment object are not changed; on Windows names are case-insensitive.",example:'set_env("DEBUG", "1");'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), reports through injected diagnostics/captured errors and stops with exit 1; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests a JavaScript regex against text.",example:'regex_test("abc", "a");'},{name:"regex_find",category:"Strings",signature:"regex_find(s: string, pattern: string, [flags: string]): string|null",description:"Returns the first matched substring, or null if no match. Rejects sticky y.",example:'regex_find("item=42; item=99", "[0-9]+");'},{name:"regex_matches",category:"Strings",signature:"regex_matches(s: string, pattern: string, [flags: string]): array",description:"Returns a flat list of all matched substrings; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_matches("item=42; item=99", "[0-9]+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns first [full_match, group1, ...], including with g; missing optional groups become null. Rejects sticky y.",example:'regex_match("a1 b2", "([a-z])([0-9])", "g");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns capture arrays for matches; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_find_all("a1 b2", "([a-z])([0-9])");'},{name:"pos",category:"Strings",signature:"pos([s: string|number|null], [offset: number|null]): number",description:"Perl-like stateful regex position (0-based UTF-16 units, kept per string value, isolated per run and parallel task): pos() or pos(s) returns the offset where the last successful stateful match left off; pos(offset) or pos(s, offset) sets or resets (0/null) the offset.",example:'pos(src, 0); tok = regex_find_pos(src, r"[0-9]+"); println(pos(src));'},{name:"set_pos",category:"Strings",signature:"set_pos(s_or_offset: string|number|null, [offset: number|null]): number",description:"Sets or resets (0/null) the stateful regex match position for the current run or target string and returns the new offset.",example:"set_pos(src, 0);"},{name:"regex_match_pos",category:"Strings",signature:"regex_match_pos(s: string, pattern: string, [flags: string]): array|null",description:"Stateful regex match starting at pos(s): anchored at pos(s) by default (sticky y) or searching from pos(s) when g is set; advances pos(s) on match and returns [full_match, group1, ...], or leaves pos(s) unchanged and returns null. An empty match consumes no input and leaves pos(s) at the match offset; a second empty match at the same offset is refused (g resumes further on), so loops terminate.",example:'m = regex_match_pos(src, r"[A-Za-z_][A-Za-z0-9_]*");'},{name:"regex_find_pos",category:"Strings",signature:"regex_find_pos(s: string, pattern: string, [flags: string]): string|null",description:"Stateful regex substring match starting at pos(s): anchored at pos(s) by default (sticky y) or searching from pos(s) when g is set; advances pos(s) on match and returns the matched substring, or leaves pos(s) unchanged and returns null. An empty match consumes no input and leaves pos(s) at the match offset; a second empty match at the same offset is refused (g resumes further on), so loops terminate.",example:'tok = regex_find_pos(src, r"[0-9]+");'},{name:"regex_test_pos",category:"Strings",signature:"regex_test_pos(s: string, pattern: string, [flags: string]): boolean",description:"Stateful regex test starting at pos(s): anchored at pos(s) by default (sticky y) or searching from pos(s) when g is set; advances pos(s) and returns true on match, or leaves pos(s) unchanged and returns false. An empty match consumes no input and leaves pos(s) at the match offset; a second empty match at the same offset is refused (g resumes further on), so loops terminate.",example:'if (regex_test_pos(src, r"\\s+")) { continue; }'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:"JavaScript regex replacement with $1 captures; use g for repeated replacement.",example:'regex_replace("a1", "([a-z])([0-9])", "$2$1");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits using JavaScript regex semantics.",example:'split_regex("a b", " +");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"args_parse",category:"System & Process",signature:"args_parse(argv: array, flags: map, [usage: string]): map",description:"Pure long-option parser. Flag declarations have type (string, number or boolean), optional flag spelling, default, required and description. Returns {values,args,provided,help,help_requested}; --help generates text without printing or exiting. Unknown/duplicate options, missing/invalid values and unused declaration fields are errors. -- ends options; booleans use --flag or --flag=false. Caller policy stays outside the parser.",example:'opts = args_parse(ARGV, {region:{type:"string",default:"us-east-1"},live:{type:"boolean"}});'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width and integer precision have no artificial cap. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER) from the last 3 non-blank lines of a string, or null if absent or conflicting.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:"join(arr: array, [separator: string]): string",description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"upper_first",category:"Strings",signature:"upper_first(s: string): string",description:"Capitalizes the first character of a string.",example:'c = upper_first("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the UTF-16 code unit at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"warning",category:"System & Process",signature:"warning(message: any): string",description:"Adds a located warning without failing execution or simulating an effect.",example:'warning("Review this input");'},{name:"which",category:"System & Process",signature:"which(name: string): string|null",description:"Returns the first executable absolute path from invocation PATH/cwd, or null, without spawning.",example:'tool = which("node");'},{name:"cmd_render",category:"System & Process",signature:"cmd_render(argv: array, [dialect: string]): string",description:"Renders string/number argv for posix, windows or powershell; default windows on win32, otherwise posix. Output only; never used for execution.",example:'text = cmd_render(["git", "status"], "posix");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, ...items: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, ...items: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(first: array, ...more: array): array",description:"Concatenates two or more arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:'Safely parses JSON with markdown fence and preamble tolerance, returning fallback on failure without throwing. Use a custom sentinel (e.g. "PARSE_FAILED") to distinguish parse failure from valid JSON null.',example:'data = json_parse_safe(llm_output, "PARSE_FAILED"); if (data == "PARSE_FAILED") { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 0]): string",description:"Serializes a value to compact JSON by default; optional indent formats the output.",example:"text = json_stringify(obj, 2);"},{name:"json_validate",category:"JSON & Data",signature:"json_validate(val: any, schema: map): map",description:"Validates a JSON-compatible value against a small JSON-Schema subset (type, properties, required, enum, items, minimum/maximum, minLength/maxLength, additionalProperties:false), returning {ok: boolean, errors: list}.",example:'res = json_validate(data, {type: "object", required: ["name"]}); if (!res.ok) { error(res.errors[0]); }'},{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(argv: array, [timeoutMs: number = 0 | options: map]): SystemResult",description:"Executes a non-empty string/number argv list directly with shell:false, returning a structured process execution record. The second argument is a timeout in milliseconds or an options map {cwd, timeoutMs, stdin}; a spawn failure or cwd that does not exist gives a result with code null and an error field instead of a failure.",parameters:[{name:"argv",type:"array",description:"Non-empty argv list of strings/numbers; NUL and an empty program are errors"},{name:"timeoutMs|options",type:"number|map",description:"(optional) Timeout in milliseconds (default: 0, no deadline), or options {cwd: string (relative to the invocation directory), timeoutMs: number (default 0), stdin: string}; unknown keys are errors"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null, error?: string }"},example:'res = system(["git", "log", "-n", "1"], {cwd: "."}); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string], [options: map]): string|null; prompt_human(session: map, [options: map]): map",description:"Pauses execution to prompt an operator on terminal stdin or dedicated directory, returning the entered input line or decision map, or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"prompt_human_config",category:"System & Process",signature:"prompt_human_config([config: map|string], [dir: string]): map",description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms). Returns current configuration map.",example:'prompt_human_config({ dir: "/tmp/handoffs", timeout_ms: 60000 });'},{name:"error",category:"System & Process",signature:"error(value: any, ...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats values into an output-log entry rendered as a line by the CLI. Returns the formatted text without adding a newline.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with the sprintf width and precision rules and writes exactly that text to stdout: nothing is added, so end the format with \\n to finish the line.",example:'printf("%s scored %d\\n", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline.",example:'println("Done.");'},{name:"sleep_ms",category:"System & Process",signature:"sleep_ms(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep_ms(1000);"},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in milliseconds.",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now or a supplied epoch-millisecond value.",example:"created = date(0);"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null (including no arguments).",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"http_get",category:"System & Process",signature:"http_get(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = http_get("https://example.com");'}],$He=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];ta=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;promptHumanConfig={mode:"interactive"};builtinProviders=new Map;reservedFunctionPrefixes;builtinProviderNames;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions();for(let[e,n]of[["get_property",{min:1,max:2}],["has_property",1],["get_properties",{min:0,max:1}],["set_property",2]])this.registerFunction(e,()=>{throw Error("Property store is not running")},n,"Read or overlay hierarchical run-local properties; no persistence");this.registerComputedFunction("expand",()=>{throw Error("Template resolver is not running")},{min:1,max:2},"Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque"),this.registerComputedFunction("template_extract",sH,2,{description:"Pure tree projection over parsed JSON-like values; returns {matched,value,candidate,error}; no-match is data, not an exception.",params:[{name:"pattern",type:"any"},{name:"data",type:"any"}],returnType:"map",doc:{name:"template_extract",signature:"template_extract(pattern, data)",category:"Templates",description:"Project nested captures and filter repeated rows; guards compare without coercion. Inputs are parsed values, never auto-detected JSON text."}}),this.registerComputedFunction("template_extract_first",iH,2,{description:"Validate a nonempty candidate list and return the first matching projection as {matched,value,candidate,error}; failure records stay ordered.",params:[{name:"patterns",type:"any"},{name:"data",type:"any"}],returnType:"map",doc:{name:"template_extract_first",signature:"template_extract_first(patterns, data)",category:"Templates",description:"First full candidate wins with fresh captures; loop explicitly over polymorphic streams. No-match is data."}}),this.registerComputedFunction("template_extract_text",oH,2,{description:"Exact whole-string extraction with simple ${name} holes, anchored suffix and earliest separators; returns {matched,value,candidate,error}.",params:[{name:"template",type:"any"},{name:"text",type:"any"}],returnType:"map",doc:{name:"template_extract_text",signature:"template_extract_text(template, text)",category:"Templates",description:"Strings only; $${ escapes, empty captures allowed, no adjacent/duplicate holes, backtracking, expression holes or automatic mode detection."}}),this.registerComputedFunction("warning",e=>String(e),1,{description:"Adds a located non-failure warning",isDefault:!0,returnType:"string"}),this.registerComputedFunction("which",e=>Tk(e,process.cwd(),process.env),1,{description:"Finds the first executable path without spawning",isDefault:!0,returnType:"string|null"}),this.registerComputedFunction("xml_children",HF,1,{description:"Return a native XML element's ordered child array; operate on Data.value() copies.",returnType:"array",doc:{name:"xml_children",category:"JSON & Data",signature:"xml_children(node)",description:"Ordered children of a native XML element snapshot."}}),this.registerComputedFunction("xml_attr",WF,{min:2,max:3},{description:"Look up an unqualified or {URI}local attribute, with optional fallback.",returnType:"any",doc:{name:"xml_attr",category:"JSON & Data",signature:"xml_attr(node, name, fallback=null)",description:"Look up a native XML attribute by expanded name."}}),this.registerComputedFunction("xml_select",qF,2,{description:"Select native XML nodes by *, local tag, .class or #id; returns references inside the supplied copy.",returnType:"array",doc:{name:"xml_select",category:"JSON & Data",signature:"xml_select(tree, selector)",description:"Generic XML selection without XPath or raw markup parsing."}}),this.registerComputedFunction("xml_text",zF,1,{description:"Concatenate descendant XML text in document order, excluding comments.",returnType:"string",doc:{name:"xml_text",category:"JSON & Data",signature:"xml_text(node)",description:"Text from a native XML tree, excluding comments."}}),this.installCoreDryCallbacks(),this.registerDefaultDocs();for(let[e,n,r]of[["get_property","get_property(key, [default])","Returns a copied property value; absent keys are errors unless a default is supplied."],["has_property","has_property(key)","Tests property presence; missing/invalid profile errors remain loud."],["get_properties","get_properties([prefix])","Returns a detached nested property table copy."],["set_property","set_property(key, value)","Returns the previous value and changes only the run-local overlay; invocation facts are read-only."]])this.functionDocs.set(e,{name:e,signature:n,description:r,module:"core",category:"Properties"});this.functionDocs.set("expand",{name:"expand",signature:"expand(text, [vars])",description:"Resolve ${name} from an explicit vars map, ${PROPS.path}, and ${ARGV[n]}; $${ escapes, no caller-local capture or recursive expansion.",module:"core",category:"Strings"})}prepareChildEnv(e,n){let r={...n.hostContext?.env??process.env};return this.bindChildEnv(e,n,dHe(r))}bindChildEnv(e,n,r){let s=e.functions.get("set_env"),i=n.hostContext?.platform??n.platform??process.platform;s&&e.functions.set("set_env",{...s,fn:(a,l)=>{if(typeof a!="string"||a===""||a.includes("=")||a.includes("\0"))throw new Error("set_env: the name must be a non-empty string without '=' or NUL");if(i==="win32")for(let c of Object.keys(r))c!==a&&c.toUpperCase()===a.toUpperCase()&&delete r[c];return l==null?delete r[a]:r[a]=String(l),!0}});for(let a of["env","getenv"]){let l=e.functions.get(a);l&&e.functions.set(a,{...l,fn:(c,u=null)=>Object.hasOwn(r,String(c))?r[String(c)]??u:u})}let o={pos:(...a)=>Gie(Dy(r),...a),set_pos:(...a)=>Vie(Dy(r),...a),regex_match_pos:(a,l,c="")=>Xk(Dy(r),a,l,c),regex_find_pos:(a,l,c="")=>Jie(Dy(r),a,l,c),regex_test_pos:(a,l,c="")=>Kie(Dy(r),a,l,c)};for(let[a,l]of Object.entries(o)){let c=e.functions.get(a);c&&e.functions.set(a,{...c,fn:l,dryRun:di(u=>l(...u))})}return r}registerComputedFunction(...e){this.registerFunction(...e);let[n,r]=e,s=this.hostFunctions.get(n);return s.dryRun=di((i,o)=>r(...i)),this}registerFileReader(...e){this.registerFunction(...e);let[n,r]=e,s=this.hostFunctions.get(n);return s.dryRun=di((i,o)=>NHe(i)?(o.record(n,i,"dummy"),Goe(s.signature?.returnType??void 0)):r(...i)),this}installCoreDryCallbacks(){let e=(r,s)=>{let i=this.hostFunctions.get(r);i&&(i.dryRun=di(s))};e("system",(r,s)=>{let i=rx(r[0],Ooe(r[1]).timeoutMs,s.platform);return s.record(s.functionName,r,"dummy",i),{...Xoe}}),e("print",(r,s)=>{let i=ex(r);return s.output("print",i,r),i}),e("println",(r,s)=>{let i=ex(r);return s.output("println",i,r),i}),e("printf",([r,...s],i)=>{let o=Mk(r,s,"printf");return i.output("printf",o,[r,...s]),o}),e("error",Dj),e("exit",$j),e("warning",i1),e("require",([r,s],i)=>zU(r,s,o=>i.fail(o))),e("env",([r,s=null],i)=>i.env[r]??s),e("getenv",([r,s=null],i)=>i.env[r]??s),e("now",(r,s)=>s.now),e("timestamp",(r,s)=>Math.floor(s.now/1e3)),e("date",([r],s)=>new Date(r??s.now).toISOString()),e("which",([r],s)=>Tk(r,s.cwd,s.env,s.platform));let n=this.hostFunctions.get("temp_file");n&&(n.dryRun=()=>null)}registerDefaultDocs(){for(let e of MHe)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of DHe)this.registerFunctionDoc({...e,module:e.module??"core"});for(let e of $He)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){let n=PU({...e,module:e.module??this.currentRegisteringModule});this.functionDocs.set(e.name,n);let r=this.hostFunctions.get(e.name);return r&&this.hostFunctions.set(e.name,{...r,doc:n,signature:go(e.name,r.arity,r.params,r.returnType,n)}),this}registerModule(e,n){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let r=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,n)}finally{this.currentRegisteringModule=r}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return this.getFunctionDocs().filter(n=>(n.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return[...this.functionDocs.keys()].map(e=>this.getFunctionDoc(e))}getFunctionDoc(e){let n=this.functionDocs.get(e),r=this.hostFunctions.get(e)?.signature;return!n||!r?n:{...n,...r.returnType?{returns:{type:r.returnType,description:n.returns?.description??"Declared result type"}}:{}}}getFunctionCategories(){let e=new Set;for(let n of this.functionDocs.values())e.add(n.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(n=>n.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFileReader("read_file",n=>q.readFileSync(n,"utf-8"),1,{description:"Reads entire file as UTF-8 string",returnType:"string"}),this.registerFileReader("read",n=>q.readFileSync(n,"utf-8"),1,{description:"Reads entire file as UTF-8 string",returnType:"string"}),this.registerFileReader("read_lines",n=>{let r=q.readFileSync(n,"utf-8"),s=r.length>0;return r.endsWith(`\r
|
|
4826
4826
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
4827
4827
|
`)&&(r=r.slice(0,-1)),s?r.length===0?[""]:r.split(/\r?\n/):[]},1,{description:"Reads file as an array of string lines",returnType:"array"}),this.registerFunction("write_lines",(n,r)=>{if(!Array.isArray(r))throw new Error("write_lines: second argument must be an array of lines");let s=r.length===0?"":r.map(String).join(`
|
|
4828
4828
|
`)+`
|
|
@@ -4831,6 +4831,6 @@ fn clamp(val, low, high) {
|
|
|
4831
4831
|
`:""),d=c.exitCode!==void 0?c.exitCode:c.success&&!c.errors?.length?0:1;return{success:c.success&&d===0,stdout:u,output:[...c.output],value:c.value??null,exit_code:d,code:d,errors:c.errors??[]}})();{let c=a.run(i,l),u=c.stdout??c.output.join(`
|
|
4832
4832
|
`)+(c.output.length>0?`
|
|
4833
4833
|
`:""),d=c.exitCode!==void 0?c.exitCode:c.success&&!c.errors?.length?0:1;return{success:c.success&&d===0,stdout:u,output:[...c.output],value:c.value??null,exit_code:d,code:d,errors:c.errors??[]}}},{min:1,max:2},{description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",returnType:"map",isDefault:!0},!0),this.registerFunction("error",(...n)=>{let r=n.map(s=>typeof s=="object"?JSON.stringify(s):String(s)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
|
|
4834
|
-
`):console.error(`error: ${r}`),r},{min:1},{description:"Formats and logs an error to stderr and records it for the execution error summary",returnType:"string",isDefault:!0,params:[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]},!0),this.registerFunction("http_get",n=>xoe(n),1,{description:"Downloads UTF-8 text from a public HTTP(S) URL",returnType:"string",isDefault:!0,params:[{name:"url",type:"string"}]},!0),this.registerFunction("sleep_ms",n=>{if(typeof n!="number"||!Number.isFinite(n)||n<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(n>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+n;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human_config",(n,r)=>{if(n===void 0)return{mode:this.promptHumanConfig.mode??"interactive",dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200};if(typeof n=="string")n==="interactive"?this.promptHumanConfig.mode="interactive":n==="file"?(this.promptHumanConfig.mode="file",r&&(this.promptHumanConfig.dir=String(r))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=n);else if(n&&typeof n=="object"){let s=n.mode?String(n.mode):n.dir?"file":this.promptHumanConfig.mode??"interactive",i=n.dir!==void 0?String(n.dir):this.promptHumanConfig.dir,o=n.timeout_ms!==void 0?Number(n.timeout_ms):n.timeoutMs!==void 0?Number(n.timeoutMs):this.promptHumanConfig.timeoutMs,a=n.poll_ms!==void 0?Number(n.poll_ms):n.pollIntervalMs!==void 0?Number(n.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=s==="file"?"file":"interactive",this.promptHumanConfig.dir=i,this.promptHumanConfig.timeoutMs=typeof o=="number"&&Number.isFinite(o)?o:void 0,this.promptHumanConfig.pollIntervalMs=typeof a=="number"&&Number.isFinite(a)&&a>0?a:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},{min:0,max:2},{description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",returnType:"map",isDefault:!0},!0),this.registerFunction("prompt_human",(n,r)=>{if((r?.mode??(r?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let i=r?.dir??this.promptHumanConfig.dir;if(!i)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsyncMode)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return Poe(n,{dir:i,sessionId:r?.sessionId??r?.sessionid??r?.id,timeoutMs:r?.timeout_ms??r?.timeoutMs??this.promptHumanConfig.timeoutMs,pollIntervalMs:r?.poll_ms??r?.pollIntervalMs??this.promptHumanConfig.pollIntervalMs})}return this.isAsyncMode?WS(n):Loe(n)},{min:0,max:2},"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",!0),this.registerComputedFunction("json_parse",n=>{try{return JSON.parse(String(n))}catch(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerComputedFunction("json_parse_safe",(n,r=null)=>gHe(n,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerComputedFunction("json_stringify",(n,r)=>JSON.stringify(n,null,r),{min:1,max:2},{description:"Serializes value into JSON string",returnType:"string"}),this.registerComputedFunction("json_validate",(n,r)=>mHe(n,r),2,{description:"Validates a JSON-compatible value against a small JSON-Schema subset (type, properties, required, enum, items, minimum/maximum, minLength/maxLength, additionalProperties:false), returning {ok: boolean, errors: string[]}",returnType:"map"}),this.registerComputedFunction("keys",n=>{if(sn(n))throw Error("lmcode builder is opaque");return n&&typeof n=="object"?Object.keys(n):[]},1,{description:"Returns array of object keys",returnType:"array"}),this.registerComputedFunction("values",n=>n&&typeof n=="object"?Object.values(Tu(n)):[],1,{description:"Returns array of object values",returnType:"array"}),this.registerComputedFunction("entries",n=>n&&typeof n=="object"?Object.entries(Tu(n)):[],1,{description:"Returns array of [key, value] pairs",returnType:"array"}),this.registerComputedFunction("has_key",(n,r)=>{if(sn(n))throw Error("lmcode builder is opaque");return n&&typeof n=="object"?Object.hasOwn(n,r):!1},2,{description:"Checks if object has key",returnType:"boolean"}),this.registerComputedFunction("items",n=>n&&typeof n=="object"?Object.entries(Tu(n)):[],1,{description:"Returns array of [key, value] pairs (alias for entries)",returnType:"array"}),this.registerComputedFunction("get",(n,r,s=null)=>{let i=My(n,r);return i!==void 0?i:s},{min:2,max:3},"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerComputedFunction("getstr",(n,r,s="")=>{let i=My(n,r);return i==null?s:String(i)},{min:2,max:3},{description:'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.',returnType:"string"}),this.registerComputedFunction("getnum",(n,r,s=0)=>{let i=My(n,r);return i==null?s:Number(i)},{min:2,max:3},{description:"Reads a numeric field from a map/request form; fallback (default 0) when missing or null",returnType:"number"}),this.registerComputedFunction("getbool",(n,r,s=!1)=>{let i=My(n,r);if(i==null)return s;if(typeof i=="boolean")return i;if(typeof i=="string"){let o=i.trim().toLowerCase();if(o==="true")return!0;if(o==="false")return!1}return!!i},{min:2,max:3},{description:'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null',returnType:"boolean"}),this.registerComputedFunction("getlist",(n,r,s=[])=>{let i=My(n,r);return Array.isArray(i)?i:s},{min:2,max:3},{description:"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array",returnType:"array"}),this.registerFunction("require",zU,2,"Requires a present value; injected diagnostic/captured error and exit 1 on missing",!0),this.registerComputedFunction("set",(n,r,s)=>{if(n==null||typeof n!="object")return n;let i=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),o=n;for(let a=0;a<i.length-1;a++){let l=i[a];(Ur(o,l)==null||typeof Ur(o,l)!="object")&&Qn(o,l,{}),o=Ur(o,l)}return i.length>0&&Qn(o,i[i.length-1],s),n},3,"Sets nested property by path",!0,!0),this.registerComputedFunction("pluck",(n,r)=>Array.isArray(n)?n.map(s=>Ur(s,r)):[],2,{description:"Extracts key from array of objects",returnType:"array"}),this.registerComputedFunction("filter_by",(n,r,s)=>Array.isArray(n)?n.filter(i=>i!=null&&Ur(i,r)===s):[],3,{description:"Filters array of objects where item[key] == value",returnType:"array"}),this.registerComputedFunction("find_by",(n,r,s)=>{if(!Array.isArray(n))return null;let i=n.find(o=>o!=null&&Ur(o,r)===s);return i!==void 0?i:null},3,"Finds first object in array where item[key] == value"),this.registerComputedFunction("args_parse",QF,{min:2,max:3},{description:"Parses declared long options without effects; returns values, args, provided, help and help_requested",params:[{name:"argv",type:"array"},{name:"flags",type:"map"},{name:"usage",type:"string",optional:!0}],returnType:"map"}),this.registerComputedFunction("merge",(n,r)=>({...Tu(n),...Tu(r)}),2,{description:"Shallow merges two objects",returnType:"map"}),this.registerComputedFunction("clone",n=>n==null||typeof n!="object"?n:JSON.parse(JSON.stringify(n)),1,"Deep clones an object or array"),this.registerComputedFunction("delete_key",(n,r)=>{if(sn(n))throw Error("lmcode builder is opaque");return n&&typeof n=="object"&&delete n[r],n},2,"Deletes key from object",!0,!0),this.registerFunction("print",(...n)=>{let r=n.map(s=>typeof s=="object"?JSON.stringify(s):String(s)).join(" ");return this.outputLogs.push(r),r},{min:0},{description:"Prints formatted values to output log",returnType:"string",isDefault:!0,params:[{name:"values",type:"any",rest:!0}]},!0),this.registerFunction("println",(...n)=>{let r=n.map(s=>typeof s=="object"?JSON.stringify(s):String(s)).join(" ");return this.outputLogs.push(r),r},{min:0},{description:"Prints line to output log",returnType:"string",isDefault:!0,params:[{name:"values",type:"any",rest:!0}]},!0),this.registerComputedFunction("split",(n,r)=>String(n).split(r),2,{description:"Splits string by required delimiter; use explicit empty delimiter for characters",returnType:"array"}),this.registerComputedFunction("lines",n=>String(n).split(/\r?\n/),1,{description:"Splits string into array of lines",returnType:"array"}),this.registerComputedFunction("last_line_as_status",n=>{if(typeof n!="string")return null;let r=n.split(/\r?\n/),s=[],i=0;for(let o=r.length-1;o>=0&&i<3;o--){let a=r[o].trim();a.length!==0&&(i++,a.startsWith("**")&&a.endsWith("**")&&a.length>=4?a=a.slice(2,-2).trim():a.startsWith("`")&&a.endsWith("`")&&a.length>=2&&(a=a.slice(1,-1).trim()),(a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER")&&s.push(a))}if(s.length===0)return null;for(let o=1;o<s.length;o++)if(s[o]!==s[0])return null;return s[0]},1,"Returns the state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER) from the last 3 non-blank lines of a string, or null if absent or conflicting"),this.registerComputedFunction("parse_file_blocks",n=>YBe(n),1,{description:"Parses === FILE: path === ... === END === blocks into [{path, content}]",returnType:"array"}),this.registerComputedFunction("format_file_blocks",n=>QBe(n),1,{description:"Formats [{path, content}] as file blocks; inverse of parse_file_blocks",returnType:"string"}),this.registerFunction("write_files",(n,r)=>sHe(n,r),2,{description:"Writes [{path, content}] under dir atomically, rejecting unsafe paths; returns {written, rejected}",params:[{name:"dir",type:"string"},{name:"files",type:"array"}],returnType:"map"}),this.registerComputedFunction("read_tree",(n,r)=>aHe(n,r),{min:1,max:2},{description:"Reads text files under dir as sorted [{path, content}] with default ignores",returnType:"array"}),this.registerComputedFunction("kv_from_last_paragraph",n=>uHe(n),1,{description:"Parses key: value lines of the last paragraph into a map",returnType:"map"}),this.registerComputedFunction("split_command",n=>Nk(n),1,{description:"Splits one command line into argv with POSIX quoting; shell syntax is an error",returnType:"array"}),this.registerComputedFunction("words",n=>String(n).trim().split(/\s+/).filter(Boolean),1,{description:"Splits string into words",returnType:"array"}),this.registerComputedFunction("join",(n,r=", ")=>Array.isArray(n)?n.join(r):String(n),{min:1,max:2},{description:"Joins array into string",returnType:"string"}),this.registerComputedFunction("trim",n=>String(n).trim(),1,{description:"Trims whitespace from both ends",returnType:"string"}),this.registerComputedFunction("strip",n=>String(n).trim(),1,{description:"Trims whitespace from both ends (alias for trim)",returnType:"string"}),this.registerComputedFunction("trim_start",n=>String(n).trimStart(),1,{description:"Trims leading whitespace",returnType:"string"}),this.registerComputedFunction("lstrip",n=>String(n).trimStart(),1,{description:"Trims leading whitespace (alias for trim_start)",returnType:"string"}),this.registerComputedFunction("trim_end",n=>String(n).trimEnd(),1,{description:"Trims trailing whitespace",returnType:"string"}),this.registerComputedFunction("rstrip",n=>String(n).trimEnd(),1,{description:"Trims trailing whitespace (alias for trim_end)",returnType:"string"}),this.registerComputedFunction("to_upper",n=>String(n).toUpperCase(),1,{description:"Converts string to uppercase",returnType:"string"}),this.registerComputedFunction("upper",n=>String(n).toUpperCase(),1,{description:"Converts string to uppercase",returnType:"string"}),this.registerComputedFunction("to_lower",n=>String(n).toLowerCase(),1,{description:"Converts string to lowercase",returnType:"string"}),this.registerComputedFunction("lower",n=>String(n).toLowerCase(),1,{description:"Converts string to lowercase",returnType:"string"}),this.registerComputedFunction("upper_first",n=>{let r=String(n);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,{description:"Capitalizes first letter",returnType:"string"}),this.registerComputedFunction("title_case",n=>String(n).replace(/\b\w/g,r=>r.toUpperCase()),1,{description:"Converts string to Title Case",returnType:"string"}),this.registerComputedFunction("contains",(n,r)=>Array.isArray(n)?n.includes(r):String(n).includes(String(r)),2,{description:"Checks if string or array contains item",returnType:"boolean"}),this.registerComputedFunction("includes",(n,r)=>Array.isArray(n)?n.includes(r):String(n).includes(String(r)),2,{description:"Checks if string or array contains item",returnType:"boolean"}),this.registerComputedFunction("starts_with",(n,r)=>String(n).startsWith(r),2,{description:"Checks if string starts with prefix",returnType:"boolean"}),this.registerComputedFunction("startswith",(n,r)=>String(n).startsWith(r),2,{description:"Checks if string starts with prefix (alias for starts_with)",returnType:"boolean"}),this.registerComputedFunction("ends_with",(n,r)=>String(n).endsWith(r),2,{description:"Checks if string ends with suffix",returnType:"boolean"}),this.registerComputedFunction("endswith",(n,r)=>String(n).endsWith(r),2,{description:"Checks if string ends with suffix (alias for ends_with)",returnType:"boolean"}),this.registerComputedFunction("index_of",(n,r,s)=>Array.isArray(n)?n.indexOf(r,s):String(n).indexOf(r,s),{min:2,max:3},{description:"Finds substring or strictly equal array element index; -1 if absent",returnType:"number"}),this.registerComputedFunction("last_index_of",(n,r)=>Array.isArray(n)?n.lastIndexOf(r):String(n).lastIndexOf(r),2,{description:"Finds last substring or strictly equal array element index; -1 if absent",returnType:"number"}),this.registerComputedFunction("count_matches",(n,r)=>r?String(n).split(r).length-1:0,2,{description:"Counts occurrences of substring",returnType:"number"}),this.registerComputedFunction("substr",(n,r,s)=>{let i=String(n),o=Math.trunc(Number(r))||0,a=o<0?Math.max(0,i.length+o):Math.min(i.length,o);if(s===void 0)return i.slice(a);let l=Math.max(0,Math.trunc(Number(s))||0);return i.slice(a,a+l)},{min:2,max:3},{description:"Returns substring by end-relative start and optional length",returnType:"string"}),this.registerComputedFunction("substring",(n,r,s)=>String(n).substring(r,s),{min:2,max:3},{description:"Returns substring between indices",returnType:"string"}),this.registerComputedFunction("slice",(n,r,s)=>n!=null?n.slice(r,s):"",{min:2,max:3},"Slices string or array"),this.registerComputedFunction("char_at",(n,r)=>String(n).charAt(r),2,{description:"Returns character at index",returnType:"string"}),this.registerComputedFunction("char_code",(n,r=0)=>String(n).charCodeAt(r),{min:1,max:2},{description:"Returns character code at index",returnType:"number"}),this.registerComputedFunction("from_char_code",(...n)=>String.fromCharCode(...n),{min:0},{description:"Returns string from character codes",returnType:"string"}),this.registerComputedFunction("replace",(n,r,s)=>String(n).replace(r,s),3,{description:"Replaces first occurrence",returnType:"string"}),this.registerComputedFunction("replace_all",(n,r,s)=>String(n).replaceAll(r,s),3,{description:"Replaces all occurrences",returnType:"string"}),this.registerComputedFunction("repeat",(n,r)=>String(n).repeat(r),2,{description:"Repeats string count times",returnType:"string"}),this.registerComputedFunction("pad_start",(n,r,s=" ")=>String(n).padStart(r,s),{min:2,max:3},{description:"Left-pads string",returnType:"string"}),this.registerComputedFunction("pad_end",(n,r,s=" ")=>String(n).padEnd(r,s),{min:2,max:3},{description:"Right-pads string",returnType:"string"}),this.registerComputedFunction("reverse_str",n=>String(n).split("").reverse().join(""),1,{description:"Reverses string",returnType:"string"}),this.registerComputedFunction("is_empty",n=>{if(sn(n))throw Error("lmcode builder is opaque");return n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:typeof n=="object"?Object.keys(n).length===0:!1},1,{description:"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace.",returnType:"boolean"}),this.registerComputedFunction("is_digit",n=>/^\d+$/.test(String(n)),1,{description:"Checks if string contains only digits",returnType:"boolean"}),this.registerComputedFunction("is_alpha",n=>/^[a-zA-Z]+$/.test(String(n)),1,{description:"Checks if string contains only letters",returnType:"boolean"}),this.registerComputedFunction("is_alnum",n=>/^[a-zA-Z0-9]+$/.test(String(n)),1,{description:"Checks if string contains only letters and digits",returnType:"boolean"}),this.registerComputedFunction("is_array",n=>Array.isArray(n),1,{description:"Checks if value is an array",returnType:"boolean"}),this.registerComputedFunction("is_string",n=>typeof n=="string",1,{description:"Checks if value is a string",returnType:"boolean"}),this.registerComputedFunction("is_number",n=>typeof n=="number",1,{description:"Checks if value is a number",returnType:"boolean"}),this.registerComputedFunction("is_map",n=>n!==null&&typeof n=="object"&&!Array.isArray(n)&&!sn(n),1,{description:"Checks if value is a map/object",returnType:"boolean"}),this.registerComputedFunction("is_function",n=>n instanceof Qi,1,{description:"Checks if value is a first-class function reference",returnType:"boolean"}),this.registerComputedFunction("cmd_render",(n,r)=>h1(n,r),{min:1,max:2},{description:"Renders argv as posix, windows or powershell text; execution never uses rendered text",returnType:"string",isDefault:!0,params:[{name:"argv",type:"array"},{name:"dialect",type:"string",optional:!0}]},!0),this.registerComputedFunction("sprintf",(n,...r)=>Mk(n,r),{min:1},{description:"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax",returnType:"string"}),this.registerFunction("printf",(n,...r)=>Mk(n,r,"printf"),{min:1},{description:"Formats %s, %d, %f and %% with the sprintf rules and writes exactly that text to stdout (no newline added)",returnType:"string",isDefault:!0,params:[{name:"format",type:"string"},{name:"values",type:"any",rest:!0}]},!0),this.registerComputedFunction("format",(n,...r)=>{let s=String(n),i=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,o=0,a="",l=c=>typeof c=="object"&&c!==null?JSON.stringify(c):String(c);for(let c=0;c<s.length;){let u=s[c];if(u==="{"&&s[c+1]==="{"){a+="{",c+=2;continue}if(u==="}"&&s[c+1]==="}"){a+="}",c+=2;continue}if(u!=="{"){a+=u,c+=1;continue}let d=s.indexOf("}",c+1);if(d<0){a+=u,c+=1;continue}let p=s.slice(c+1,d);if(p==="")a+=o<r.length?l(r[o++]):"{}";else if(/^\d+$/.test(p)){let f=Number(p);a+=f<r.length?l(r[f]):`{${p}}`}else i&&/^[a-zA-Z0-9_]+$/.test(p)&&Object.hasOwn(i,p)?a+=l(i[p]):a+=`{${p}}`;c=d+1}return a},{min:1},{description:"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution",returnType:"string"});let e=$oe();this.registerComputedFunction("regex_test",(n,r,s="")=>Tf(r,s).test(String(n)),{min:2,max:3},{description:"Tests a JavaScript regular expression against text",returnType:"boolean"}),this.registerComputedFunction("regex_find",yHe,{min:2,max:3},{description:"Returns first matched substring or null; g retains first-match shape, y is rejected",returnType:"string|null"}),this.registerComputedFunction("regex_matches",_He,{min:2,max:3},{description:"Returns flat array of matched substrings with Unicode-aware zero-width progress; y is rejected",returnType:"array"}),this.registerComputedFunction("regex_match",Moe,{min:2,max:3},{description:"Returns first full match and captures; g retains first-match shape, y is rejected",returnType:"array"}),this.registerComputedFunction("regex_find_all",Doe,{min:2,max:3},{description:"Returns capture arrays with Unicode-aware zero-width progress; y is rejected",returnType:"array"}),this.registerComputedFunction("pos",(...n)=>Gie(e,...n),{min:0,max:2},{description:"Reads or sets the Perl-like stateful regex match offset (0-based, isolated per run and parallel task)",returnType:"number"}),this.registerComputedFunction("set_pos",(...n)=>Vie(e,...n),{min:1,max:2},{description:"Sets or resets the stateful regex match offset and returns the new offset",returnType:"number"}),this.registerComputedFunction("regex_match_pos",(n,r,s="")=>Xk(e,n,r,s),{min:2,max:3},{description:"Matches at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) on success and leaving pos(s) unchanged on failure",returnType:"array"}),this.registerComputedFunction("regex_find_pos",(n,r,s="")=>Jie(e,n,r,s),{min:2,max:3},{description:"Matches substring at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) on success and leaving pos(s) unchanged on failure",returnType:"string|null"}),this.registerComputedFunction("regex_test_pos",(n,r,s="")=>Kie(e,n,r,s),{min:2,max:3},{description:"Tests pattern at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) on success and leaving pos(s) unchanged on failure",returnType:"boolean"}),this.registerComputedFunction("regex_replace",(n,r,s,i="")=>String(n).replace(Tf(r,i),s),{min:3,max:4},{description:"Replaces matches using JavaScript regex replacement semantics",returnType:"string"}),this.registerComputedFunction("split_regex",(n,r,s="")=>String(n).split(Tf(r,s)),{min:2,max:3},{description:"Splits text at regular expression matches",returnType:"array"}),this.registerComputedFunction("len",n=>{if(sn(n))throw Error("lmcode builder is opaque");return typeof n=="string"||Array.isArray(n)?n.length:n&&typeof n=="object"?Object.keys(n).length:0},1,{description:"Returns length of string, array, or object",returnType:"number"}),this.registerComputedFunction("range",(n,r,s=1)=>{let i=r===void 0?0:n,o=r===void 0?n:r,a=[];if(s>0)for(let l=i;l<o;l+=s)a.push(l);else if(s<0)for(let l=i;l>o;l+=s)a.push(l);return a},{min:1,max:3},{description:"Generates an array of numbers",returnType:"array"}),this.registerComputedFunction("abs",n=>Math.abs(n),1,{description:"Absolute value",returnType:"number"}),this.registerComputedFunction("min",(...n)=>{let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return Math.min(...r)},{min:0},{description:"Minimum value",returnType:"number"}),this.registerComputedFunction("max",(...n)=>{let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return Math.max(...r)},{min:0},{description:"Maximum value",returnType:"number"}),this.registerComputedFunction("floor",n=>Math.floor(n),1,{description:"Floor value",returnType:"number"}),this.registerComputedFunction("ceil",n=>Math.ceil(n),1,{description:"Ceil value",returnType:"number"}),this.registerComputedFunction("round",n=>Math.round(n),1,{description:"Round value",returnType:"number"}),this.registerComputedFunction("sqrt",n=>Math.sqrt(n),1,{description:"Square root",returnType:"number"}),this.registerComputedFunction("pow",(n,r)=>Math.pow(n,r),2,{description:"Power calculation",returnType:"number"}),this.registerFunction("random",()=>Math.random(),0,{description:"Random float between 0 and 1",returnType:"number"}),this.registerComputedFunction("sha256",n=>{if(typeof n!="string")throw new Error("sha256: expected a string");return u1("sha256").update(n,"utf8").digest("hex")},1,{description:"Returns lowercase SHA-256 of UTF-8 text; strings only",returnType:"string"}),this.registerFunction("now",()=>Date.now(),0,{description:"Returns current epoch in ms",returnType:"number"}),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,{description:"Returns current Unix epoch in whole seconds",returnType:"number"}),this.registerFunction("date",n=>new Date(n??Date.now()).toISOString(),{min:0,max:1},{description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp",returnType:"string"}),this.registerComputedFunction("strftime",(n,r)=>jHe(n,r),2,{description:"Formats local time: epoch milliseconds first, format string second",returnType:"string"}),this.registerComputedFunction("coalesce",(...n)=>{for(let r of n)if(r!=null)return r;return null},{min:0},"Returns the first non-null/non-undefined argument, else null"),this.registerComputedFunction("if_null",(n,r)=>n??r,2,"Returns fallback if value is null/undefined, else value"),this.registerComputedFunction("if_else",(n,r,s)=>n?r:s,3,"Eager compatibility helper: arguments evaluate eagerly; use condition ? thenValue : elseValue for lazy selection"),this.registerComputedFunction("str",n=>LU(n),1,{description:"Converts lists and maps to compact JSON; scalars to normal text",returnType:"string"}),this.registerComputedFunction("num",n=>Number(n),1,{description:"Converts value to number",returnType:"number"}),this.registerComputedFunction("type",n=>n===null?"null":Array.isArray(n)?"array":n instanceof Qi?"function":ya(n)?"Data":fo(n)?"Data source":io(n)?"lmcode":sn(n)?"lmcode_builder":typeof n,1,{description:"Returns runtime type of value",returnType:"string"}),this.registerComputedFunction("assert",(n,r="Assertion failed")=>{if(!n)throw new Error(r);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,n,r,s,i=!1,o=!1){if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is reserved; rename this function");let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=PU(typeof s=="object"?s.doc:void 0),d=typeof s=="object"?!!s.allowOverwrite:!1,p=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,f=this.functionOriginModule.get(e);if(f&&f!==p&&!d)throw new Error(`Cannot register function '${e}' from module '${p}': already registered by module '${f}'`);let m=typeof s=="object"?{returnsResource:s.returnsResource===!0||void 0,usesResource:s.usesResource===!0||void 0,closesResource:s.closesResource===!0||void 0}:{},g=typeof s=="object"?s.params?.map(s1):void 0,h=typeof s=="object"?s.returnType:void 0,y=go(e,r,g,h,u);this.functionOriginModule.set(e,p);let v=Ik(typeof s=="object"?s.dryRun:void 0),_=typeof s=="object"&&typeof s.dryArgs=="function"?s.dryArgs:void 0;if(this.hostFunctions.set(e,{fn:n,arity:y.nativeArity,description:a,isDefault:l,isContainerMutation:c,doc:u,params:y.nativeParams,returnType:h,dryRun:v,..._?{dryArgs:_}:{},signature:y,...m}),u)this.functionDocs.set(e,{...u,module:u.module??p});else{let b=y.publicArity,w=typeof b=="number"?b:b?.min??0,T=typeof b=="number"?b:b?.max,k=y.publicParams.length?y.publicParams.map(x=>x.optional?`[${x.name}]`:x.rest?`...${x.name}`:x.name):Array.from({length:T??w},(x,N)=>(N>=w?"[":"")+"arg"+(N+1)+(N>=w?"]":""));T===void 0&&!y.publicParams.some(x=>x.rest)&&k.push("...args"),this.functionDocs.set(e,{name:e,module:p,category:"Uncategorized",signature:e+"("+k.join(", ")+")",description:a??"Host function "+e})}return this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,n){if(e==="PROPS")throw Error("PROPS is a reserved read-only map binding");if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is a reserved read-only binding: the running resumepoint path or null");return this.initialGlobals.set(e,n),this}getGlobal(e){return this.initialGlobals.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}createChildEngine(e={}){let n=new t;n.reservedFunctionPrefixes=this.reservedFunctionPrefixes,n.builtinProviderNames=this.builtinProviderNames;for(let[s,i]of this.hostFunctions)n.hasFunction(s)?i.isDefault||n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,dryRun:i.dryRun,dryArgs:i.dryArgs,doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...Su(i)},!1,i.isContainerMutation):n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,dryRun:i.dryRun,dryArgs:i.dryArgs,doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...Su(i)});let r=new Set(e.excludeBuiltins??[]);for(let s of this.builtinProviders.values())r.has(s.name)||n.registerBuiltinProvider(s);return e.args&&(n.setGlobal("args",[...e.args]),n.setGlobal("ARGV",[...e.args])),n}async scanAndCheckAsync(e,n={}){return this.scanAndCheckAsyncIsolated(e,n)}async scanAndCheckAsyncIsolated(e,n){try{n.reservedFunctionPrefixes&&(this.reservedFunctionPrefixes=n.reservedFunctionPrefixes),n.builtinProviderNames&&(this.builtinProviderNames=n.builtinProviderNames);let r=n.compiledSource??await IHe(e,{...n,reservedFunctionPrefixes:n.reservedFunctionPrefixes??this.reservedFunctionPrefixes,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??this.builtinProviderNames??[]]});return{...this.scanAndCheck(e,{...n,compiledSource:r}),compiledSource:r}}catch(r){return{ast:null,hasConcurrency:!1,diagnostics:Die(r,n.file)}}}scanAndCheck(e,n={}){return this.scanAndCheckIsolated(e,n)}scanAndCheckIsolated(e,n){let r=[],s;try{n.reservedFunctionPrefixes&&(this.reservedFunctionPrefixes=n.reservedFunctionPrefixes),n.builtinProviderNames&&(this.builtinProviderNames=n.builtinProviderNames);let i=n.compiledSource??xHe(e,{...n,reservedFunctionPrefixes:n.reservedFunctionPrefixes??this.reservedFunctionPrefixes,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??this.builtinProviderNames??[]]}),{program:o,packages:a}=i;r=i.diagnostics,s=i.diagnosticPaths;let l=new Map(this.hostFunctions),c=[],u=new Map,d=new Map,p=new Set,f=[],m={known:[],closedTables:[],removedGlobals:{}};for(let _ of[...this.builtinProviders.keys()].map(b=>({name:b,line:1,column:1,file:n.file}))){if(c.some(T=>T.name===_.name))continue;let b=this.builtinProviders.get(_.name),w;try{let T=b.declarations,k=T?.functions,x=T?.globals;Array.isArray(k)&&Array.isArray(x)&&(w={functions:k.map(N=>Object.freeze({...N,arity:r1(N.arity),params:N.params?Object.freeze(N.params.map(s1)):void 0,doc:PU(N.doc)})),globals:x.map(N=>({...N})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(b.name!==_.name||!w||typeof b.activate!="function")throw new B(`Invalid declarations for module '${_.name}'`,_.line,_.column,"CHECKER",_.file);for(let T of w.functions){let k=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Wk,T.name)&&T.name!=="system"||T.name==="RESUMEPOINT"||!k||!Number.isSafeInteger(k.min)||k.min<0||k.max!==void 0&&(!Number.isSafeInteger(k.max)||k.max<k.min))throw new B(`Invalid function declaration in module '${_.name}'`,_.line,_.column,"CHECKER",_.file);let x=d.get(T.name);if(T.override===!0&&l.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new B(`Module '${_.name}' cannot override ${x===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${x}'`}; permitted overrides: prompt_human, run_script`,_.line,_.column,"CHECKER",_.file);if(l.has(T.name)&&!(T.override===!0&&l.get(T.name)?.isDefault))throw new B(`Module function collision: '${T.name}' in module '${_.name}'${x===void 0?"":` is already declared by module '${x}'`}`,_.line,_.column,"CHECKER",_.file);let N=go(T.name,T.arity,T.params,T.returnType,T.doc);l.set(T.name,{arity:N.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:N.nativeParams,returnType:N.returnType??void 0,dryRun:Ik(T.dryRun),...typeof T.dryArgs=="function"?{dryArgs:T.dryArgs}:{},signature:N,...Su(T)}),d.set(T.name,_.name)}for(let T of w.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Wk,T.name)||p.has(T.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(T.name)||this.initialGlobals.has(T.name)||n.globals?.includes(T.name))throw new B(`Module global collision or invalid name: '${T.name}'`,_.line,_.column,"CHECKER",_.file);p.add(T.name),this.builtinProviders.has(_.name)&&f.push(T.name)}w.properties&&(m.known=[...m.known,...w.properties.known],m.closedTables=[...m.closedTables??[],...w.properties.closedTables??[]],m.removedGlobals={...m.removedGlobals,...w.properties.removedGlobals}),c.push(b),u.set(b,w)}let g=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],h=new QU(l,{...n,globals:g,builtinGlobals:f,propertyDeclarations:m,sourcePackages:a}),y=[...r,...h.check(o)],v={lmcodeSchemas:h.lmcodeSchemas,ast:o,diagnosticPaths:s,diagnostics:y,hasConcurrency:h.hasConcurrency,hostModules:c,hostDeclarations:u,usedGlobals:[...h.usedGlobals],usedProperties:h.usedProperties,recoverLabels:[...h.recoverLabels],hasRecover:h.hasRecover,recoverScopedReads:h.recoverScopedReads,recoverScopedWrites:h.recoverScopedWrites};return vu(v,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:Die(i,n.file,r,s)}}}installBuiltinStubs(e,n,r,s,i){let o=n.hostDeclarations.get(e);for(let a of o.globals)r.globals.set(a.name,new Wy(()=>i(a.name)));for(let a of o.functions){let l=go(a.name,a.arity,a.params,a.returnType,a.doc);r.functions.set(a.name,{fn:s(a.name),arity:l.nativeArity,doc:a.doc,params:l.nativeParams,returnType:l.returnType??void 0,dryRun:Ik(a.dryRun),...typeof a.dryArgs=="function"?{dryArgs:a.dryArgs}:{},signature:l,...Su(a)})}}installPassiveProperties(e,n,r,s,i){let o=Re(s),a=n.hostDeclarations?.get(e)?.properties;if(!o||!a||!e.loadDryProperties)return;let l,c,u=()=>{if(l)return;if(c)return c;let d=e.loadDryProperties(Pk(o,s,o.lastSite));if(Rn(d)){if(!i)throw Promise.resolve(d).catch(()=>{}),Error("Async property loader requires dryRunAsync");return c=Promise.resolve(d).then(p=>{l=p})}l=d};o.propertyLoads.push(u),r.addProviderSource(e.name,()=>{if(!l){let d=u();if(Rn(d))throw Error("Passive property snapshot is not ready")}return l},a.known)}activationContext(e,n,r,s,i=!1,o){let a=(l,c=0)=>{In(n.signal);let u={cwd:n.hostContext?.cwd??process.cwd(),env:n.childEnv??n.hostContext?.env??process.env};return i?Aoe([...l],c,n.hostContext?.platform??process.platform,n.signal,u):Roe([...l],c,n.hostContext?.platform??process.platform,u)};return{executionOrigin:n.executionOrigin,runProgram:a,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:l=>{let c=Re(n);if(c){c.recordError(l);return}Lk(s,l)},cwd:n.hostContext?.cwd??process.cwd(),env:n.childEnv&&!Re(n)?pHe(n.childEnv):Object.freeze({...n.hostContext?.env??process.env}),signal:n.signal,propertyStore:n.propertyStore,usedGlobals:(e.usedGlobals??[]).filter(l=>(e.hostDeclarations?.get(r)??r.declarations).globals.some(c=>c.name===l)),builtinProviders:[...this.builtinProviders.values()],reservedFunctionPrefixes:n.reservedFunctionPrefixes,builtinProviderNames:n.builtinProviderNames??[...this.builtinProviders.keys()],createChildEngine:l=>this.createChildEngine(l),tracer:o}}bindModule(e,n,r,s){if(!n||typeof n.dispose!="function")throw new Error(`Module '${e.name}' did not return a disposable`);let i=r.hostDeclarations?.get(e)??e.declarations;if(i.properties){if(!n.loadProperties)throw Error(`Provider '${e.name}' did not supply properties`);s.properties?.addProviderSource(e.name,()=>n.loadProperties(),i.properties.known)}for(let o of i.functions){if(typeof n.functions?.[o.name]!="function")throw new Error(`Module '${e.name}' did not bind '${o.name}'`);let a=go(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:n.functions[o.name],arity:a.nativeArity,doc:o.doc,params:a.nativeParams,returnType:a.returnType??void 0,dryRun:Ik(o.dryRun),...typeof o.dryArgs=="function"?{dryArgs:o.dryArgs}:{},signature:a,...Su(o)})}for(let o of i.globals)if(Object.hasOwn(n.globals??{},o.name))s.globals.set(o.name,n.globals[o.name]);else if(r.usedGlobals?.includes(o.name))throw new Error(`Module '${e.name}' did not provide global '${o.name}'`)}moduleFailure(e,n,r){return{success:!1,output:[],diagnostics:[...n.diagnostics,{severity:"error",message:e instanceof Error?e.message:String(e),line:1,column:1,file:r.file}]}}collectModuleErrors(e,n,r=!1){for(let s of e)try{let i=s.getRecordedErrors;if(i===void 0)continue;let o=i.call(s);if(!Array.isArray(o))throw new Error("getRecordedErrors must return an array");r&&o.length&&n.diagnostics.push({severity:"warning",message:"Provider collector errors have no recovery attribution; use reportRecordedError for live events",line:1,column:1}),n.errors=[...n.errors??[],...o.map(a=>typeof a=="string"?a:JSON.stringify(a)??String(a))]}catch(i){n.diagnostics.push({severity:"warning",message:`Host module error collection failed: ${i instanceof Error?i.message:String(i)}`,line:1,column:1})}}cleanupWarning(e,n){n.diagnostics.push({severity:"warning",message:`Host module cleanup failed: ${e instanceof Error?e.message:String(e)}`,line:1,column:1})}dryRun(e,n={}){return this.dryRunIsolated(e,n)}dryRunIsolated(e,n){n=xk({...n,lmcodeDiscovery:void 0}),wu(n.recoveryProbe);let r=new Qk(n);try{let s=this.runPhase(e,{...n,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?vu(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[n1]:r});return s.diagnostics.some(i=>i.severity==="error")||r.check(),r.report(s)}catch(s){return r.report({success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]})}}async dryRunAsync(e,n={}){return this.dryRunAsyncIsolated(e,n)}async dryRunAsyncIsolated(e,n){n=xk({...n,lmcodeDiscovery:void 0}),wu(n.recoveryProbe);let r=new Qk(n);try{return r.report(await r.wait(this.runPhaseAsync(e,{...n,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?vu(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[n1]:r})))}catch(s){return r.report({success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]})}}run(e,n={}){return this.runIsolated(e,n)}runIsolated(e,n){if(n.dryLoopLimit!==void 0)throw Error("dryLoopLimit requires dryRun or dryRunAsync");if(n=xk({...n,lmcodeSync:!0,lmcodeDiscovery:"real"}),n.propertyOverlay)try{n={...n,propertyOverlay:qu(n.propertyOverlay)}}catch(s){return{success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]}}this.outputLogs=[],this.lastRecordedErrors=[],wu(n.recoveryProbe);let r=n.preparedCheck?vu(n.preparedCheck,n):this.scanAndCheck(e,n);return!r.ast||r.diagnostics.some(s=>s.severity==="error")?{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]}:this.runPhase(e,{...n,preparedCheck:r})}async runAsync(e,n={}){return this.runAsyncIsolated(e,n)}async runAsyncIsolated(e,n){if(n.dryLoopLimit!==void 0)throw Error("dryLoopLimit requires dryRun or dryRunAsync");if(n=xk({...n,lmcodeDiscovery:"real"}),n.propertyOverlay)try{n={...n,propertyOverlay:qu(n.propertyOverlay)}}catch(s){return{success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]}}this.outputLogs=[],this.lastRecordedErrors=[],wu(n.recoveryProbe);let r=n.preparedCheck?vu(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);return!r.ast||r.diagnostics.some(s=>s.severity==="error")?{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]}:this.runPhaseAsync(e,{...n,preparedCheck:r})}runPhase(e,n={}){wu(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?vu(n.preparedCheck,n):this.scanAndCheck(e,n);if(n={...n,preparedCheck:r},Re(n)&&(!r.ast||r.diagnostics.some(p=>p.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};n={...n,propertyStore:n.propertyStore??new Jk(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let s=n.propertyStore;n.propertyOverlay&&s.setOverlay(n.propertyOverlay);let i=n.trace&&!Re(n)?new Jl(n.trace):void 0,o={functions:new Map(this.hostFunctions),globals:Re(n)?new Map(Sf([...this.initialGlobals])):new Map(this.initialGlobals),properties:s,tracer:i};n={...n,childEnv:this.prepareChildEnv(o,n)},o.functions.get("which")?.isDefault&&o.functions.set("which",{...o.functions.get("which"),fn:p=>Tk(p,n.hostContext?.cwd??process.cwd(),Re(n)?.environment??n.childEnv??n.hostContext?.env??process.env,n.hostContext?.platform??n.platform??process.platform)}),o.globals.set("PROPS",s.view()),o.globals.set("Directory",s.get("Directory")),o.globals.set("NonInteractive",s.get("NonInteractive"));let a=Re(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new Wy(()=>{let p=a.prepareProperties();return Rn(p)?p.then(()=>a.propertyView):a.propertyView}))),o.globals.set("RESUMEPOINT",null);let c={expand:(p,f={})=>{if(!f||typeof f!="object"||Array.isArray(f)||![Object.prototype,null].includes(Object.getPrototypeOf(f)))throw Error("expand: vars must be a map");let m=o.globals.get("ARGV")??[];return U_(p,g=>g.kind==="property"?s.get(g.key):g.kind==="argument"?Array.isArray(m)&&Object.hasOwn(m,g.index)?m[g.index]:void 0:Object.hasOwn(f,g.name)?Ur(f,g.name):void 0,LU)},get_property:(p,...f)=>s.get(p,...f),has_property:p=>s.has(p),get_properties:p=>s.copy(p),set_property:(p,f)=>s.set(p,f)};for(let[p,f]of Object.entries(c))o.functions.set(p,{...o.functions.get(p),fn:Re(n)&&p!=="set_property"?(...m)=>{let h=p!=="expand"||typeof m[0]=="string"&&ec(m[0]).some(y=>typeof y!="string"&&y.kind==="property")?Re(n).prepareProperties(p==="expand"?void 0:m[0]):void 0;return Rn(h)?h.then(()=>f(...m)):f(...m)}:f,dryRun:p==="set_property"?void 0:di(m=>{let h=p!=="expand"||typeof m[0]=="string"&&ec(m[0]).some(y=>typeof y!="string"&&y.kind==="property")?Re(n)?.prepareProperties(p==="expand"?void 0:m[0]):void 0;return Rn(h)?h.then(()=>f(...m)):f(...m)})});if(!r.ast||r.diagnostics.some(p=>p.severity==="error")||r.hasConcurrency)return this.executeSync(e,n,r,o);let u=jy(n.resumepoint,n.recoveryProbe),d=eoe(u,n.signal);try{let p=[],f;try{In(n.signal);for(let g of r.hostModules??[]){let h,y=()=>{if(h)return h;In(n.signal);let v=g.activate(this.activationContext(r,n,g,u,!1,o.tracer));if(Rn(v))throw v.then(_=>_.dispose()).catch(()=>{}),new Error(`Module '${g.name}' requires runAsync for activation`);if(!v||typeof v.dispose!="function")throw new Error(`Module '${g.name}' did not return a disposable`);return h=v,p.push(h),Re(n)?.own(h),this.bindModule(g,h,r,o),h};this.installBuiltinStubs(g,r,o,v=>(..._)=>(y(),o.functions.get(v).fn(..._)),v=>{let _=Re(n);if(_){if(!g.loadDryGlobals)throw Error("No passive dry loader for global "+v);let b=_.loadGlobals(g,Pk(_,n,_.lastSite));if(Rn(b))throw Promise.resolve(b).catch(()=>{}),Error("Async global requires dryRunAsync");return b[v]}return y(),o.globals.get(v)}),this.installPassiveProperties(g,r,s,n,!1),Re(n)||r.usedProperties&&r.hostDeclarations?.get(g)?.properties&&y()}f=this.executeSync(e,n,r,o,u),n.signal?.aborted&&(f={...f,success:!1,diagnostics:f.diagnostics.some(g=>g.severity==="error"&&g.message==="Execution aborted")?f.diagnostics:[...f.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(g){$s(u,g),f={...this.moduleFailure(g,r,n),errors:[...u.errors]}}Re(n)?.capture(f);let m=u.errors.length;this.collectModuleErrors(p,f,n.recoveryProbe!==void 0),Re(n)?.capture(f);for(let g of p.reverse())try{let h=Re(n)?Re(n).dispose(g):g.dispose();if(Rn(h))throw h.catch(()=>{}),new Error("Async disposal requires runAsync");Re(n)?.check()}catch(h){let y=Re(n);y&&(y.failure??={site:y.lastSite,message:h instanceof Error?h.message:String(h),untrusted:y.tainted}),this.cleanupWarning(h,f)}return f.errors=[...f.errors??[],...u.errors.slice(m)],this.lastRecordedErrors=[...f.errors],this.finishTrace(o,f),f}finally{u.finished=!0,d()}}async runPhaseAsync(e,n={}){wu(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?vu(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(n={...n,preparedCheck:s},Re(n)&&(!s.ast||s.diagnostics.some(f=>f.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};n={...n,propertyStore:n.propertyStore??new Jk(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let i=n.propertyStore;n.propertyOverlay&&i.setOverlay(n.propertyOverlay);let o=n.trace&&!Re(n)?new Jl(n.trace):void 0,a={functions:new Map(this.hostFunctions),globals:Re(n)?new Map(Sf([...this.initialGlobals])):new Map(this.initialGlobals),properties:i,tracer:o};n={...n,childEnv:this.prepareChildEnv(a,n)},a.functions.get("which")?.isDefault&&a.functions.set("which",{...a.functions.get("which"),fn:f=>Tk(f,n.hostContext?.cwd??process.cwd(),Re(n)?.environment??n.childEnv??n.hostContext?.env??process.env,n.hostContext?.platform??n.platform??process.platform)}),a.globals.set("PROPS",i.view()),a.globals.set("Directory",i.get("Directory")),a.globals.set("NonInteractive",i.get("NonInteractive"));let l=Re(n);l&&(l.propertyView=a.globals.get("PROPS"),a.globals.set("PROPS",new Wy(()=>{let f=l.prepareProperties();return Rn(f)?f.then(()=>l.propertyView):l.propertyView}))),a.globals.set("RESUMEPOINT",null);let u={expand:(f,m={})=>{if(!m||typeof m!="object"||Array.isArray(m)||![Object.prototype,null].includes(Object.getPrototypeOf(m)))throw Error("expand: vars must be a map");let g=a.globals.get("ARGV")??[];return U_(f,h=>h.kind==="property"?i.get(h.key):h.kind==="argument"?Array.isArray(g)&&Object.hasOwn(g,h.index)?g[h.index]:void 0:Object.hasOwn(m,h.name)?Ur(m,h.name):void 0,LU)},get_property:(f,...m)=>i.get(f,...m),has_property:f=>i.has(f),get_properties:f=>i.copy(f),set_property:(f,m)=>i.set(f,m)};for(let[f,m]of Object.entries(u))a.functions.set(f,{...a.functions.get(f),fn:Re(n)&&f!=="set_property"?(...g)=>{let y=f!=="expand"||typeof g[0]=="string"&&ec(g[0]).some(v=>typeof v!="string"&&v.kind==="property")?Re(n).prepareProperties(f==="expand"?void 0:g[0]):void 0;return Rn(y)?y.then(()=>m(...g)):m(...g)}:m,dryRun:f==="set_property"?void 0:di(g=>{let y=f!=="expand"||typeof g[0]=="string"&&ec(g[0]).some(v=>typeof v!="string"&&v.kind==="property")?Re(n)?.prepareProperties(f==="expand"?void 0:g[0]):void 0;return Rn(y)?y.then(()=>m(...g)):m(...g)})});if(!s.ast||s.diagnostics.some(f=>f.severity==="error"))return this.executeAsync(e,n,s,a);let d=jy(n.resumepoint,n.recoveryProbe),p=eoe(d,n.signal);try{let f=[],m;try{In(n.signal);for(let h of s.hostModules??[]){let y,v,_=()=>y??=Promise.resolve().then(async()=>{In(n.signal);let b=await h.activate(this.activationContext(s,n,h,d,!0,a.tracer));if(!b||typeof b.dispose!="function")throw new Error(`Module '${h.name}' did not return a disposable`);if(Re(n)?.sealed){try{await b.dispose()}catch{}throw new Fr("Dry pass finished")}return v=b,f.push(b),Re(n)?.own(b),this.bindModule(h,b,s,a),In(n.signal),b});this.installBuiltinStubs(h,s,a,b=>async(...w)=>{let T=await _();return Re(n)?.check(),a.functions.get(b).fn(...w)},async b=>{let w=Re(n);if(w){if(!h.loadDryGlobals)throw Error("No passive dry loader for global "+b);return(await w.loadGlobals(h,Pk(w,n,w.lastSite)))[b]}return await _(),a.globals.get(b)}),this.installPassiveProperties(h,s,i,n,!0),Re(n)||s.usedProperties&&s.hostDeclarations?.get(h)?.properties&&await _()}m=await this.executeAsync(e,n,s,a,d),n.signal?.aborted&&(m={...m,success:!1,diagnostics:m.diagnostics.some(h=>h.severity==="error"&&h.message==="Execution aborted")?m.diagnostics:[...m.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(h){$s(d,h),m={...this.moduleFailure(h,s,n),errors:[...d.errors]}}Re(n)?.capture(m);let g=d.errors.length;this.collectModuleErrors(f,m,n.recoveryProbe!==void 0),Re(n)?.capture(m);for(let h of f.reverse())try{let y=Re(n)?Re(n).dispose(h):h.dispose();Re(n)?await Re(n).wait(y):await y}catch(y){let v=Re(n);v&&(v.failure??={site:v.lastSite,message:y instanceof Error?y.message:String(y),untrusted:v.tainted}),this.cleanupWarning(y,m)}return m.errors=[...m.errors??[],...d.errors.slice(g)],this.lastRecordedErrors=[...m.errors],this.finishTrace(a,m),m}finally{d.finished=!0,p()}}finishTrace(e,n){if(e.tracer)try{for(let r of n.errors??[])e.tracer.error(r);e.tracer.end(n.exitCode??(n.success&&!n.errors?.length?0:1))}catch(r){n.success=!1,n.exitCode=1,n.diagnostics.push({severity:"error",message:"Trace write failed: "+String(r),line:1,column:1})}}executeSync(e,n,r,s,i){let o=[],a="",{ast:l,diagnostics:c,hasConcurrency:u}=r;if(c.filter(h=>h.severity==="error").length>0||!l)return this.outputLogs=o,{success:!1,diagnostics:c,output:o};if(u)return this.outputLogs=o,{success:!1,diagnostics:[...c,{message:"Concurrency constructs ('parallel', 'parallel_map', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:n.file}],output:o};let p=i??jy(n.resumepoint,n.recoveryProbe),f,m,g=s.tracer??(n.trace&&!Re(n)?new Jl(n.trace):void 0);s.tracer=g;try{f=new tx(s.functions,(v,_)=>{o.push(v);let b=_?v:v+`
|
|
4834
|
+
`):console.error(`error: ${r}`),r},{min:1},{description:"Formats and logs an error to stderr and records it for the execution error summary",returnType:"string",isDefault:!0,params:[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]},!0),this.registerFunction("http_get",n=>xoe(n),1,{description:"Downloads UTF-8 text from a public HTTP(S) URL",returnType:"string",isDefault:!0,params:[{name:"url",type:"string"}]},!0),this.registerFunction("sleep_ms",n=>{if(typeof n!="number"||!Number.isFinite(n)||n<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(n>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+n;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human_config",(n,r)=>{if(n===void 0)return{mode:this.promptHumanConfig.mode??"interactive",dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200};if(typeof n=="string")n==="interactive"?this.promptHumanConfig.mode="interactive":n==="file"?(this.promptHumanConfig.mode="file",r&&(this.promptHumanConfig.dir=String(r))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=n);else if(n&&typeof n=="object"){let s=n.mode?String(n.mode):n.dir?"file":this.promptHumanConfig.mode??"interactive",i=n.dir!==void 0?String(n.dir):this.promptHumanConfig.dir,o=n.timeout_ms!==void 0?Number(n.timeout_ms):n.timeoutMs!==void 0?Number(n.timeoutMs):this.promptHumanConfig.timeoutMs,a=n.poll_ms!==void 0?Number(n.poll_ms):n.pollIntervalMs!==void 0?Number(n.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=s==="file"?"file":"interactive",this.promptHumanConfig.dir=i,this.promptHumanConfig.timeoutMs=typeof o=="number"&&Number.isFinite(o)?o:void 0,this.promptHumanConfig.pollIntervalMs=typeof a=="number"&&Number.isFinite(a)&&a>0?a:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},{min:0,max:2},{description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",returnType:"map",isDefault:!0},!0),this.registerFunction("prompt_human",(n,r)=>{if((r?.mode??(r?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let i=r?.dir??this.promptHumanConfig.dir;if(!i)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsyncMode)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return Poe(n,{dir:i,sessionId:r?.sessionId??r?.sessionid??r?.id,timeoutMs:r?.timeout_ms??r?.timeoutMs??this.promptHumanConfig.timeoutMs,pollIntervalMs:r?.poll_ms??r?.pollIntervalMs??this.promptHumanConfig.pollIntervalMs})}return this.isAsyncMode?WS(n):Loe(n)},{min:0,max:2},"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",!0),this.registerComputedFunction("json_parse",n=>{try{return JSON.parse(String(n))}catch(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerComputedFunction("json_parse_safe",(n,r=null)=>gHe(n,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerComputedFunction("json_stringify",(n,r)=>JSON.stringify(n,null,r),{min:1,max:2},{description:"Serializes value into JSON string",returnType:"string"}),this.registerComputedFunction("json_validate",(n,r)=>mHe(n,r),2,{description:"Validates a JSON-compatible value against a small JSON-Schema subset (type, properties, required, enum, items, minimum/maximum, minLength/maxLength, additionalProperties:false), returning {ok: boolean, errors: string[]}",returnType:"map"}),this.registerComputedFunction("keys",n=>{if(sn(n))throw Error("lmcode builder is opaque");return n&&typeof n=="object"?Object.keys(n):[]},1,{description:"Returns array of object keys",returnType:"array"}),this.registerComputedFunction("values",n=>n&&typeof n=="object"?Object.values(Tu(n)):[],1,{description:"Returns array of object values",returnType:"array"}),this.registerComputedFunction("entries",n=>n&&typeof n=="object"?Object.entries(Tu(n)):[],1,{description:"Returns array of [key, value] pairs",returnType:"array"}),this.registerComputedFunction("has_key",(n,r)=>{if(sn(n))throw Error("lmcode builder is opaque");return n&&typeof n=="object"?Object.hasOwn(n,r):!1},2,{description:"Checks if object has key",returnType:"boolean"}),this.registerComputedFunction("items",n=>n&&typeof n=="object"?Object.entries(Tu(n)):[],1,{description:"Returns array of [key, value] pairs (alias for entries)",returnType:"array"}),this.registerComputedFunction("get",(n,r,s=null)=>{let i=My(n,r);return i!==void 0?i:s},{min:2,max:3},"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerComputedFunction("getstr",(n,r,s="")=>{let i=My(n,r);return i==null?s:String(i)},{min:2,max:3},{description:'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.',returnType:"string"}),this.registerComputedFunction("getnum",(n,r,s=0)=>{let i=My(n,r);return i==null?s:Number(i)},{min:2,max:3},{description:"Reads a numeric field from a map/request form; fallback (default 0) when missing or null",returnType:"number"}),this.registerComputedFunction("getbool",(n,r,s=!1)=>{let i=My(n,r);if(i==null)return s;if(typeof i=="boolean")return i;if(typeof i=="string"){let o=i.trim().toLowerCase();if(o==="true")return!0;if(o==="false")return!1}return!!i},{min:2,max:3},{description:'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null',returnType:"boolean"}),this.registerComputedFunction("getlist",(n,r,s=[])=>{let i=My(n,r);return Array.isArray(i)?i:s},{min:2,max:3},{description:"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array",returnType:"array"}),this.registerFunction("require",zU,2,"Requires a present value; injected diagnostic/captured error and exit 1 on missing",!0),this.registerComputedFunction("set",(n,r,s)=>{if(n==null||typeof n!="object")return n;let i=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),o=n;for(let a=0;a<i.length-1;a++){let l=i[a];(Ur(o,l)==null||typeof Ur(o,l)!="object")&&Qn(o,l,{}),o=Ur(o,l)}return i.length>0&&Qn(o,i[i.length-1],s),n},3,"Sets nested property by path",!0,!0),this.registerComputedFunction("pluck",(n,r)=>Array.isArray(n)?n.map(s=>Ur(s,r)):[],2,{description:"Extracts key from array of objects",returnType:"array"}),this.registerComputedFunction("filter_by",(n,r,s)=>Array.isArray(n)?n.filter(i=>i!=null&&Ur(i,r)===s):[],3,{description:"Filters array of objects where item[key] == value",returnType:"array"}),this.registerComputedFunction("find_by",(n,r,s)=>{if(!Array.isArray(n))return null;let i=n.find(o=>o!=null&&Ur(o,r)===s);return i!==void 0?i:null},3,"Finds first object in array where item[key] == value"),this.registerComputedFunction("args_parse",QF,{min:2,max:3},{description:"Parses declared long options without effects; returns values, args, provided, help and help_requested",params:[{name:"argv",type:"array"},{name:"flags",type:"map"},{name:"usage",type:"string",optional:!0}],returnType:"map"}),this.registerComputedFunction("merge",(n,r)=>({...Tu(n),...Tu(r)}),2,{description:"Shallow merges two objects",returnType:"map"}),this.registerComputedFunction("clone",n=>n==null||typeof n!="object"?n:JSON.parse(JSON.stringify(n)),1,"Deep clones an object or array"),this.registerComputedFunction("delete_key",(n,r)=>{if(sn(n))throw Error("lmcode builder is opaque");return n&&typeof n=="object"&&delete n[r],n},2,"Deletes key from object",!0,!0),this.registerFunction("print",(...n)=>{let r=n.map(s=>typeof s=="object"?JSON.stringify(s):String(s)).join(" ");return this.outputLogs.push(r),r},{min:0},{description:"Prints formatted values to output log",returnType:"string",isDefault:!0,params:[{name:"values",type:"any",rest:!0}]},!0),this.registerFunction("println",(...n)=>{let r=n.map(s=>typeof s=="object"?JSON.stringify(s):String(s)).join(" ");return this.outputLogs.push(r),r},{min:0},{description:"Prints line to output log",returnType:"string",isDefault:!0,params:[{name:"values",type:"any",rest:!0}]},!0),this.registerComputedFunction("split",(n,r)=>String(n).split(r),2,{description:"Splits string by required delimiter; use explicit empty delimiter for characters",returnType:"array"}),this.registerComputedFunction("lines",n=>String(n).split(/\r?\n/),1,{description:"Splits string into array of lines",returnType:"array"}),this.registerComputedFunction("last_line_as_status",n=>{if(typeof n!="string")return null;let r=n.split(/\r?\n/),s=[],i=0;for(let o=r.length-1;o>=0&&i<3;o--){let a=r[o].trim();a.length!==0&&(i++,a.startsWith("**")&&a.endsWith("**")&&a.length>=4?a=a.slice(2,-2).trim():a.startsWith("`")&&a.endsWith("`")&&a.length>=2&&(a=a.slice(1,-1).trim()),(a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER")&&s.push(a))}if(s.length===0)return null;for(let o=1;o<s.length;o++)if(s[o]!==s[0])return null;return s[0]},1,"Returns the state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER) from the last 3 non-blank lines of a string, or null if absent or conflicting"),this.registerComputedFunction("parse_file_blocks",n=>YBe(n),1,{description:"Parses === FILE: path === ... === END === blocks into [{path, content}]",returnType:"array"}),this.registerComputedFunction("format_file_blocks",n=>QBe(n),1,{description:"Formats [{path, content}] as file blocks; inverse of parse_file_blocks",returnType:"string"}),this.registerFunction("write_files",(n,r)=>sHe(n,r),2,{description:"Writes [{path, content}] under dir atomically, rejecting unsafe paths; returns {written, rejected}",params:[{name:"dir",type:"string"},{name:"files",type:"array"}],returnType:"map"}),this.registerComputedFunction("read_tree",(n,r)=>aHe(n,r),{min:1,max:2},{description:"Reads text files under dir as sorted [{path, content}] with default ignores",returnType:"array"}),this.registerComputedFunction("kv_from_last_paragraph",n=>uHe(n),1,{description:"Parses key: value lines of the last paragraph into a map",returnType:"map"}),this.registerComputedFunction("split_command",n=>Nk(n),1,{description:"Splits one command line into argv with POSIX quoting; shell syntax is an error",returnType:"array"}),this.registerComputedFunction("words",n=>String(n).trim().split(/\s+/).filter(Boolean),1,{description:"Splits string into words",returnType:"array"}),this.registerComputedFunction("join",(n,r=", ")=>Array.isArray(n)?n.join(r):String(n),{min:1,max:2},{description:"Joins array into string",returnType:"string"}),this.registerComputedFunction("trim",n=>String(n).trim(),1,{description:"Trims whitespace from both ends",returnType:"string"}),this.registerComputedFunction("strip",n=>String(n).trim(),1,{description:"Trims whitespace from both ends (alias for trim)",returnType:"string"}),this.registerComputedFunction("trim_start",n=>String(n).trimStart(),1,{description:"Trims leading whitespace",returnType:"string"}),this.registerComputedFunction("lstrip",n=>String(n).trimStart(),1,{description:"Trims leading whitespace (alias for trim_start)",returnType:"string"}),this.registerComputedFunction("trim_end",n=>String(n).trimEnd(),1,{description:"Trims trailing whitespace",returnType:"string"}),this.registerComputedFunction("rstrip",n=>String(n).trimEnd(),1,{description:"Trims trailing whitespace (alias for trim_end)",returnType:"string"}),this.registerComputedFunction("to_upper",n=>String(n).toUpperCase(),1,{description:"Converts string to uppercase",returnType:"string"}),this.registerComputedFunction("upper",n=>String(n).toUpperCase(),1,{description:"Converts string to uppercase",returnType:"string"}),this.registerComputedFunction("to_lower",n=>String(n).toLowerCase(),1,{description:"Converts string to lowercase",returnType:"string"}),this.registerComputedFunction("lower",n=>String(n).toLowerCase(),1,{description:"Converts string to lowercase",returnType:"string"}),this.registerComputedFunction("upper_first",n=>{let r=String(n);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,{description:"Capitalizes first letter",returnType:"string"}),this.registerComputedFunction("title_case",n=>String(n).replace(/\b\w/g,r=>r.toUpperCase()),1,{description:"Converts string to Title Case",returnType:"string"}),this.registerComputedFunction("contains",(n,r)=>Array.isArray(n)?n.includes(r):String(n).includes(String(r)),2,{description:"Checks if string or array contains item",returnType:"boolean"}),this.registerComputedFunction("includes",(n,r)=>Array.isArray(n)?n.includes(r):String(n).includes(String(r)),2,{description:"Checks if string or array contains item",returnType:"boolean"}),this.registerComputedFunction("starts_with",(n,r)=>String(n).startsWith(r),2,{description:"Checks if string starts with prefix",returnType:"boolean"}),this.registerComputedFunction("startswith",(n,r)=>String(n).startsWith(r),2,{description:"Checks if string starts with prefix (alias for starts_with)",returnType:"boolean"}),this.registerComputedFunction("ends_with",(n,r)=>String(n).endsWith(r),2,{description:"Checks if string ends with suffix",returnType:"boolean"}),this.registerComputedFunction("endswith",(n,r)=>String(n).endsWith(r),2,{description:"Checks if string ends with suffix (alias for ends_with)",returnType:"boolean"}),this.registerComputedFunction("index_of",(n,r,s)=>Array.isArray(n)?n.indexOf(r,s):String(n).indexOf(r,s),{min:2,max:3},{description:"Finds substring or strictly equal array element index; -1 if absent",returnType:"number"}),this.registerComputedFunction("last_index_of",(n,r)=>Array.isArray(n)?n.lastIndexOf(r):String(n).lastIndexOf(r),2,{description:"Finds last substring or strictly equal array element index; -1 if absent",returnType:"number"}),this.registerComputedFunction("count_matches",(n,r)=>r?String(n).split(r).length-1:0,2,{description:"Counts occurrences of substring",returnType:"number"}),this.registerComputedFunction("substr",(n,r,s)=>{let i=String(n),o=Math.trunc(Number(r))||0,a=o<0?Math.max(0,i.length+o):Math.min(i.length,o);if(s===void 0)return i.slice(a);let l=Math.max(0,Math.trunc(Number(s))||0);return i.slice(a,a+l)},{min:2,max:3},{description:"Returns substring by end-relative start and optional length",returnType:"string"}),this.registerComputedFunction("substring",(n,r,s)=>String(n).substring(r,s),{min:2,max:3},{description:"Returns substring between indices",returnType:"string"}),this.registerComputedFunction("slice",(n,r,s)=>n!=null?n.slice(r,s):"",{min:2,max:3},"Slices string or array"),this.registerComputedFunction("char_at",(n,r)=>String(n).charAt(r),2,{description:"Returns character at index",returnType:"string"}),this.registerComputedFunction("char_code",(n,r=0)=>String(n).charCodeAt(r),{min:1,max:2},{description:"Returns character code at index",returnType:"number"}),this.registerComputedFunction("from_char_code",(...n)=>String.fromCharCode(...n),{min:0},{description:"Returns string from character codes",returnType:"string"}),this.registerComputedFunction("replace",(n,r,s)=>String(n).replace(r,s),3,{description:"Replaces first occurrence",returnType:"string"}),this.registerComputedFunction("replace_all",(n,r,s)=>String(n).replaceAll(r,s),3,{description:"Replaces all occurrences",returnType:"string"}),this.registerComputedFunction("repeat",(n,r)=>String(n).repeat(r),2,{description:"Repeats string count times",returnType:"string"}),this.registerComputedFunction("pad_start",(n,r,s=" ")=>String(n).padStart(r,s),{min:2,max:3},{description:"Left-pads string",returnType:"string"}),this.registerComputedFunction("pad_end",(n,r,s=" ")=>String(n).padEnd(r,s),{min:2,max:3},{description:"Right-pads string",returnType:"string"}),this.registerComputedFunction("reverse_str",n=>String(n).split("").reverse().join(""),1,{description:"Reverses string",returnType:"string"}),this.registerComputedFunction("is_empty",n=>{if(sn(n))throw Error("lmcode builder is opaque");return n==null?!0:typeof n=="string"||Array.isArray(n)?n.length===0:typeof n=="object"?Object.keys(n).length===0:!1},1,{description:"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace.",returnType:"boolean"}),this.registerComputedFunction("is_digit",n=>/^\d+$/.test(String(n)),1,{description:"Checks if string contains only digits",returnType:"boolean"}),this.registerComputedFunction("is_alpha",n=>/^[a-zA-Z]+$/.test(String(n)),1,{description:"Checks if string contains only letters",returnType:"boolean"}),this.registerComputedFunction("is_alnum",n=>/^[a-zA-Z0-9]+$/.test(String(n)),1,{description:"Checks if string contains only letters and digits",returnType:"boolean"}),this.registerComputedFunction("is_array",n=>Array.isArray(n),1,{description:"Checks if value is an array",returnType:"boolean"}),this.registerComputedFunction("is_string",n=>typeof n=="string",1,{description:"Checks if value is a string",returnType:"boolean"}),this.registerComputedFunction("is_number",n=>typeof n=="number",1,{description:"Checks if value is a number",returnType:"boolean"}),this.registerComputedFunction("is_map",n=>n!==null&&typeof n=="object"&&!Array.isArray(n)&&!sn(n),1,{description:"Checks if value is a map/object",returnType:"boolean"}),this.registerComputedFunction("is_function",n=>n instanceof Qi,1,{description:"Checks if value is a first-class function reference",returnType:"boolean"}),this.registerComputedFunction("cmd_render",(n,r)=>h1(n,r),{min:1,max:2},{description:"Renders argv as posix, windows or powershell text; execution never uses rendered text",returnType:"string",isDefault:!0,params:[{name:"argv",type:"array"},{name:"dialect",type:"string",optional:!0}]},!0),this.registerComputedFunction("sprintf",(n,...r)=>Mk(n,r),{min:1},{description:"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax",returnType:"string"}),this.registerFunction("printf",(n,...r)=>Mk(n,r,"printf"),{min:1},{description:"Formats %s, %d, %f and %% with the sprintf rules and writes exactly that text to stdout (no newline added)",returnType:"string",isDefault:!0,params:[{name:"format",type:"string"},{name:"values",type:"any",rest:!0}]},!0),this.registerComputedFunction("format",(n,...r)=>{let s=String(n),i=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,o=0,a="",l=c=>typeof c=="object"&&c!==null?JSON.stringify(c):String(c);for(let c=0;c<s.length;){let u=s[c];if(u==="{"&&s[c+1]==="{"){a+="{",c+=2;continue}if(u==="}"&&s[c+1]==="}"){a+="}",c+=2;continue}if(u!=="{"){a+=u,c+=1;continue}let d=s.indexOf("}",c+1);if(d<0){a+=u,c+=1;continue}let p=s.slice(c+1,d);if(p==="")a+=o<r.length?l(r[o++]):"{}";else if(/^\d+$/.test(p)){let f=Number(p);a+=f<r.length?l(r[f]):`{${p}}`}else i&&/^[a-zA-Z0-9_]+$/.test(p)&&Object.hasOwn(i,p)?a+=l(i[p]):a+=`{${p}}`;c=d+1}return a},{min:1},{description:"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution",returnType:"string"});let e=$oe();this.registerComputedFunction("regex_test",(n,r,s="")=>Tf(r,s).test(String(n)),{min:2,max:3},{description:"Tests a JavaScript regular expression against text",returnType:"boolean"}),this.registerComputedFunction("regex_find",yHe,{min:2,max:3},{description:"Returns first matched substring or null; g retains first-match shape, y is rejected",returnType:"string|null"}),this.registerComputedFunction("regex_matches",_He,{min:2,max:3},{description:"Returns flat array of matched substrings with Unicode-aware zero-width progress; y is rejected",returnType:"array"}),this.registerComputedFunction("regex_match",Moe,{min:2,max:3},{description:"Returns first full match and captures; g retains first-match shape, y is rejected",returnType:"array"}),this.registerComputedFunction("regex_find_all",Doe,{min:2,max:3},{description:"Returns capture arrays with Unicode-aware zero-width progress; y is rejected",returnType:"array"}),this.registerComputedFunction("pos",(...n)=>Gie(e,...n),{min:0,max:2},{description:"Reads or sets the Perl-like stateful regex match offset (0-based UTF-16 units, isolated per run and parallel task)",returnType:"number"}),this.registerComputedFunction("set_pos",(...n)=>Vie(e,...n),{min:1,max:2},{description:"Sets or resets the stateful regex match offset and returns the new offset",returnType:"number"}),this.registerComputedFunction("regex_match_pos",(n,r,s="")=>Xk(e,n,r,s),{min:2,max:3},{description:"Matches at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) after non-empty matches and leaving pos(s) unchanged on failure. An empty match consumes no input and leaves pos(s) at the match offset and a second empty match at that offset is refused (null/false; g resumes one unit or u/v code point later); Unicode matches never rewind the cursor",returnType:"array"}),this.registerComputedFunction("regex_find_pos",(n,r,s="")=>Jie(e,n,r,s),{min:2,max:3},{description:"Matches substring at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) after non-empty matches and leaving pos(s) unchanged on failure. An empty match consumes no input and leaves pos(s) at the match offset and a second empty match at that offset is refused (null/false; g resumes one unit or u/v code point later); Unicode matches never rewind the cursor",returnType:"string|null"}),this.registerComputedFunction("regex_test_pos",(n,r,s="")=>Kie(e,n,r,s),{min:2,max:3},{description:"Tests pattern at pos(s) (sticky by default, or from pos(s) with g), advancing pos(s) after non-empty matches and leaving pos(s) unchanged on failure. An empty match consumes no input and leaves pos(s) at the match offset and a second empty match at that offset is refused (null/false; g resumes one unit or u/v code point later); Unicode matches never rewind the cursor",returnType:"boolean"}),this.registerComputedFunction("regex_replace",(n,r,s,i="")=>String(n).replace(Tf(r,i),s),{min:3,max:4},{description:"Replaces matches using JavaScript regex replacement semantics",returnType:"string"}),this.registerComputedFunction("split_regex",(n,r,s="")=>String(n).split(Tf(r,s)),{min:2,max:3},{description:"Splits text at regular expression matches",returnType:"array"}),this.registerComputedFunction("len",n=>{if(sn(n))throw Error("lmcode builder is opaque");return typeof n=="string"||Array.isArray(n)?n.length:n&&typeof n=="object"?Object.keys(n).length:0},1,{description:"Returns length of string, array, or object",returnType:"number"}),this.registerComputedFunction("range",(n,r,s=1)=>{let i=r===void 0?0:n,o=r===void 0?n:r,a=[];if(s>0)for(let l=i;l<o;l+=s)a.push(l);else if(s<0)for(let l=i;l>o;l+=s)a.push(l);return a},{min:1,max:3},{description:"Generates an array of numbers",returnType:"array"}),this.registerComputedFunction("abs",n=>Math.abs(n),1,{description:"Absolute value",returnType:"number"}),this.registerComputedFunction("min",(...n)=>{let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return Math.min(...r)},{min:0},{description:"Minimum value",returnType:"number"}),this.registerComputedFunction("max",(...n)=>{let r=n.length===1&&Array.isArray(n[0])?n[0]:n;return Math.max(...r)},{min:0},{description:"Maximum value",returnType:"number"}),this.registerComputedFunction("floor",n=>Math.floor(n),1,{description:"Floor value",returnType:"number"}),this.registerComputedFunction("ceil",n=>Math.ceil(n),1,{description:"Ceil value",returnType:"number"}),this.registerComputedFunction("round",n=>Math.round(n),1,{description:"Round value",returnType:"number"}),this.registerComputedFunction("sqrt",n=>Math.sqrt(n),1,{description:"Square root",returnType:"number"}),this.registerComputedFunction("pow",(n,r)=>Math.pow(n,r),2,{description:"Power calculation",returnType:"number"}),this.registerFunction("random",()=>Math.random(),0,{description:"Random float between 0 and 1",returnType:"number"}),this.registerComputedFunction("sha256",n=>{if(typeof n!="string")throw new Error("sha256: expected a string");return u1("sha256").update(n,"utf8").digest("hex")},1,{description:"Returns lowercase SHA-256 of UTF-8 text; strings only",returnType:"string"}),this.registerFunction("now",()=>Date.now(),0,{description:"Returns current epoch in ms",returnType:"number"}),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,{description:"Returns current Unix epoch in whole seconds",returnType:"number"}),this.registerFunction("date",n=>new Date(n??Date.now()).toISOString(),{min:0,max:1},{description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp",returnType:"string"}),this.registerComputedFunction("strftime",(n,r)=>jHe(n,r),2,{description:"Formats local time: epoch milliseconds first, format string second",returnType:"string"}),this.registerComputedFunction("coalesce",(...n)=>{for(let r of n)if(r!=null)return r;return null},{min:0},"Returns the first non-null/non-undefined argument, else null"),this.registerComputedFunction("if_null",(n,r)=>n??r,2,"Returns fallback if value is null/undefined, else value"),this.registerComputedFunction("if_else",(n,r,s)=>n?r:s,3,"Eager compatibility helper: arguments evaluate eagerly; use condition ? thenValue : elseValue for lazy selection"),this.registerComputedFunction("str",n=>LU(n),1,{description:"Converts lists and maps to compact JSON; scalars to normal text",returnType:"string"}),this.registerComputedFunction("num",n=>Number(n),1,{description:"Converts value to number",returnType:"number"}),this.registerComputedFunction("type",n=>n===null?"null":Array.isArray(n)?"array":n instanceof Qi?"function":ya(n)?"Data":fo(n)?"Data source":io(n)?"lmcode":sn(n)?"lmcode_builder":typeof n,1,{description:"Returns runtime type of value",returnType:"string"}),this.registerComputedFunction("assert",(n,r="Assertion failed")=>{if(!n)throw new Error(r);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,n,r,s,i=!1,o=!1){if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is reserved; rename this function");let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=PU(typeof s=="object"?s.doc:void 0),d=typeof s=="object"?!!s.allowOverwrite:!1,p=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,f=this.functionOriginModule.get(e);if(f&&f!==p&&!d)throw new Error(`Cannot register function '${e}' from module '${p}': already registered by module '${f}'`);let m=typeof s=="object"?{returnsResource:s.returnsResource===!0||void 0,usesResource:s.usesResource===!0||void 0,closesResource:s.closesResource===!0||void 0}:{},g=typeof s=="object"?s.params?.map(s1):void 0,h=typeof s=="object"?s.returnType:void 0,y=go(e,r,g,h,u);this.functionOriginModule.set(e,p);let v=Ik(typeof s=="object"?s.dryRun:void 0),_=typeof s=="object"&&typeof s.dryArgs=="function"?s.dryArgs:void 0;if(this.hostFunctions.set(e,{fn:n,arity:y.nativeArity,description:a,isDefault:l,isContainerMutation:c,doc:u,params:y.nativeParams,returnType:h,dryRun:v,..._?{dryArgs:_}:{},signature:y,...m}),u)this.functionDocs.set(e,{...u,module:u.module??p});else{let b=y.publicArity,w=typeof b=="number"?b:b?.min??0,T=typeof b=="number"?b:b?.max,k=y.publicParams.length?y.publicParams.map(x=>x.optional?`[${x.name}]`:x.rest?`...${x.name}`:x.name):Array.from({length:T??w},(x,N)=>(N>=w?"[":"")+"arg"+(N+1)+(N>=w?"]":""));T===void 0&&!y.publicParams.some(x=>x.rest)&&k.push("...args"),this.functionDocs.set(e,{name:e,module:p,category:"Uncategorized",signature:e+"("+k.join(", ")+")",description:a??"Host function "+e})}return this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,n){if(e==="PROPS")throw Error("PROPS is a reserved read-only map binding");if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is a reserved read-only binding: the running resumepoint path or null");return this.initialGlobals.set(e,n),this}getGlobal(e){return this.initialGlobals.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}createChildEngine(e={}){let n=new t;n.reservedFunctionPrefixes=this.reservedFunctionPrefixes,n.builtinProviderNames=this.builtinProviderNames;for(let[s,i]of this.hostFunctions)n.hasFunction(s)?i.isDefault||n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,dryRun:i.dryRun,dryArgs:i.dryArgs,doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...Su(i)},!1,i.isContainerMutation):n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,dryRun:i.dryRun,dryArgs:i.dryArgs,doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...Su(i)});let r=new Set(e.excludeBuiltins??[]);for(let s of this.builtinProviders.values())r.has(s.name)||n.registerBuiltinProvider(s);return e.args&&(n.setGlobal("args",[...e.args]),n.setGlobal("ARGV",[...e.args])),n}async scanAndCheckAsync(e,n={}){return this.scanAndCheckAsyncIsolated(e,n)}async scanAndCheckAsyncIsolated(e,n){try{n.reservedFunctionPrefixes&&(this.reservedFunctionPrefixes=n.reservedFunctionPrefixes),n.builtinProviderNames&&(this.builtinProviderNames=n.builtinProviderNames);let r=n.compiledSource??await IHe(e,{...n,reservedFunctionPrefixes:n.reservedFunctionPrefixes??this.reservedFunctionPrefixes,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??this.builtinProviderNames??[]]});return{...this.scanAndCheck(e,{...n,compiledSource:r}),compiledSource:r}}catch(r){return{ast:null,hasConcurrency:!1,diagnostics:Die(r,n.file)}}}scanAndCheck(e,n={}){return this.scanAndCheckIsolated(e,n)}scanAndCheckIsolated(e,n){let r=[],s;try{n.reservedFunctionPrefixes&&(this.reservedFunctionPrefixes=n.reservedFunctionPrefixes),n.builtinProviderNames&&(this.builtinProviderNames=n.builtinProviderNames);let i=n.compiledSource??xHe(e,{...n,reservedFunctionPrefixes:n.reservedFunctionPrefixes??this.reservedFunctionPrefixes,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??this.builtinProviderNames??[]]}),{program:o,packages:a}=i;r=i.diagnostics,s=i.diagnosticPaths;let l=new Map(this.hostFunctions),c=[],u=new Map,d=new Map,p=new Set,f=[],m={known:[],closedTables:[],removedGlobals:{}};for(let _ of[...this.builtinProviders.keys()].map(b=>({name:b,line:1,column:1,file:n.file}))){if(c.some(T=>T.name===_.name))continue;let b=this.builtinProviders.get(_.name),w;try{let T=b.declarations,k=T?.functions,x=T?.globals;Array.isArray(k)&&Array.isArray(x)&&(w={functions:k.map(N=>Object.freeze({...N,arity:r1(N.arity),params:N.params?Object.freeze(N.params.map(s1)):void 0,doc:PU(N.doc)})),globals:x.map(N=>({...N})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(b.name!==_.name||!w||typeof b.activate!="function")throw new B(`Invalid declarations for module '${_.name}'`,_.line,_.column,"CHECKER",_.file);for(let T of w.functions){let k=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Wk,T.name)&&T.name!=="system"||T.name==="RESUMEPOINT"||!k||!Number.isSafeInteger(k.min)||k.min<0||k.max!==void 0&&(!Number.isSafeInteger(k.max)||k.max<k.min))throw new B(`Invalid function declaration in module '${_.name}'`,_.line,_.column,"CHECKER",_.file);let x=d.get(T.name);if(T.override===!0&&l.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new B(`Module '${_.name}' cannot override ${x===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${x}'`}; permitted overrides: prompt_human, run_script`,_.line,_.column,"CHECKER",_.file);if(l.has(T.name)&&!(T.override===!0&&l.get(T.name)?.isDefault))throw new B(`Module function collision: '${T.name}' in module '${_.name}'${x===void 0?"":` is already declared by module '${x}'`}`,_.line,_.column,"CHECKER",_.file);let N=go(T.name,T.arity,T.params,T.returnType,T.doc);l.set(T.name,{arity:N.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:N.nativeParams,returnType:N.returnType??void 0,dryRun:Ik(T.dryRun),...typeof T.dryArgs=="function"?{dryArgs:T.dryArgs}:{},signature:N,...Su(T)}),d.set(T.name,_.name)}for(let T of w.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(Wk,T.name)||p.has(T.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(T.name)||this.initialGlobals.has(T.name)||n.globals?.includes(T.name))throw new B(`Module global collision or invalid name: '${T.name}'`,_.line,_.column,"CHECKER",_.file);p.add(T.name),this.builtinProviders.has(_.name)&&f.push(T.name)}w.properties&&(m.known=[...m.known,...w.properties.known],m.closedTables=[...m.closedTables??[],...w.properties.closedTables??[]],m.removedGlobals={...m.removedGlobals,...w.properties.removedGlobals}),c.push(b),u.set(b,w)}let g=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],h=new QU(l,{...n,globals:g,builtinGlobals:f,propertyDeclarations:m,sourcePackages:a}),y=[...r,...h.check(o)],v={lmcodeSchemas:h.lmcodeSchemas,ast:o,diagnosticPaths:s,diagnostics:y,hasConcurrency:h.hasConcurrency,hostModules:c,hostDeclarations:u,usedGlobals:[...h.usedGlobals],usedProperties:h.usedProperties,recoverLabels:[...h.recoverLabels],hasRecover:h.hasRecover,recoverScopedReads:h.recoverScopedReads,recoverScopedWrites:h.recoverScopedWrites};return vu(v,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:Die(i,n.file,r,s)}}}installBuiltinStubs(e,n,r,s,i){let o=n.hostDeclarations.get(e);for(let a of o.globals)r.globals.set(a.name,new Wy(()=>i(a.name)));for(let a of o.functions){let l=go(a.name,a.arity,a.params,a.returnType,a.doc);r.functions.set(a.name,{fn:s(a.name),arity:l.nativeArity,doc:a.doc,params:l.nativeParams,returnType:l.returnType??void 0,dryRun:Ik(a.dryRun),...typeof a.dryArgs=="function"?{dryArgs:a.dryArgs}:{},signature:l,...Su(a)})}}installPassiveProperties(e,n,r,s,i){let o=Re(s),a=n.hostDeclarations?.get(e)?.properties;if(!o||!a||!e.loadDryProperties)return;let l,c,u=()=>{if(l)return;if(c)return c;let d=e.loadDryProperties(Pk(o,s,o.lastSite));if(Rn(d)){if(!i)throw Promise.resolve(d).catch(()=>{}),Error("Async property loader requires dryRunAsync");return c=Promise.resolve(d).then(p=>{l=p})}l=d};o.propertyLoads.push(u),r.addProviderSource(e.name,()=>{if(!l){let d=u();if(Rn(d))throw Error("Passive property snapshot is not ready")}return l},a.known)}activationContext(e,n,r,s,i=!1,o){let a=(l,c=0)=>{In(n.signal);let u={cwd:n.hostContext?.cwd??process.cwd(),env:n.childEnv??n.hostContext?.env??process.env};return i?Aoe([...l],c,n.hostContext?.platform??process.platform,n.signal,u):Roe([...l],c,n.hostContext?.platform??process.platform,u)};return{executionOrigin:n.executionOrigin,runProgram:a,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:l=>{let c=Re(n);if(c){c.recordError(l);return}Lk(s,l)},cwd:n.hostContext?.cwd??process.cwd(),env:n.childEnv&&!Re(n)?pHe(n.childEnv):Object.freeze({...n.hostContext?.env??process.env}),signal:n.signal,propertyStore:n.propertyStore,usedGlobals:(e.usedGlobals??[]).filter(l=>(e.hostDeclarations?.get(r)??r.declarations).globals.some(c=>c.name===l)),builtinProviders:[...this.builtinProviders.values()],reservedFunctionPrefixes:n.reservedFunctionPrefixes,builtinProviderNames:n.builtinProviderNames??[...this.builtinProviders.keys()],createChildEngine:l=>this.createChildEngine(l),tracer:o}}bindModule(e,n,r,s){if(!n||typeof n.dispose!="function")throw new Error(`Module '${e.name}' did not return a disposable`);let i=r.hostDeclarations?.get(e)??e.declarations;if(i.properties){if(!n.loadProperties)throw Error(`Provider '${e.name}' did not supply properties`);s.properties?.addProviderSource(e.name,()=>n.loadProperties(),i.properties.known)}for(let o of i.functions){if(typeof n.functions?.[o.name]!="function")throw new Error(`Module '${e.name}' did not bind '${o.name}'`);let a=go(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:n.functions[o.name],arity:a.nativeArity,doc:o.doc,params:a.nativeParams,returnType:a.returnType??void 0,dryRun:Ik(o.dryRun),...typeof o.dryArgs=="function"?{dryArgs:o.dryArgs}:{},signature:a,...Su(o)})}for(let o of i.globals)if(Object.hasOwn(n.globals??{},o.name))s.globals.set(o.name,n.globals[o.name]);else if(r.usedGlobals?.includes(o.name))throw new Error(`Module '${e.name}' did not provide global '${o.name}'`)}moduleFailure(e,n,r){return{success:!1,output:[],diagnostics:[...n.diagnostics,{severity:"error",message:e instanceof Error?e.message:String(e),line:1,column:1,file:r.file}]}}collectModuleErrors(e,n,r=!1){for(let s of e)try{let i=s.getRecordedErrors;if(i===void 0)continue;let o=i.call(s);if(!Array.isArray(o))throw new Error("getRecordedErrors must return an array");r&&o.length&&n.diagnostics.push({severity:"warning",message:"Provider collector errors have no recovery attribution; use reportRecordedError for live events",line:1,column:1}),n.errors=[...n.errors??[],...o.map(a=>typeof a=="string"?a:JSON.stringify(a)??String(a))]}catch(i){n.diagnostics.push({severity:"warning",message:`Host module error collection failed: ${i instanceof Error?i.message:String(i)}`,line:1,column:1})}}cleanupWarning(e,n){n.diagnostics.push({severity:"warning",message:`Host module cleanup failed: ${e instanceof Error?e.message:String(e)}`,line:1,column:1})}dryRun(e,n={}){return this.dryRunIsolated(e,n)}dryRunIsolated(e,n){n=xk({...n,lmcodeDiscovery:void 0}),wu(n.recoveryProbe);let r=new Qk(n);try{let s=this.runPhase(e,{...n,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?vu(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[n1]:r});return s.diagnostics.some(i=>i.severity==="error")||r.check(),r.report(s)}catch(s){return r.report({success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]})}}async dryRunAsync(e,n={}){return this.dryRunAsyncIsolated(e,n)}async dryRunAsyncIsolated(e,n){n=xk({...n,lmcodeDiscovery:void 0}),wu(n.recoveryProbe);let r=new Qk(n);try{return r.report(await r.wait(this.runPhaseAsync(e,{...n,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?vu(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[n1]:r})))}catch(s){return r.report({success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]})}}run(e,n={}){return this.runIsolated(e,n)}runIsolated(e,n){if(n.dryLoopLimit!==void 0)throw Error("dryLoopLimit requires dryRun or dryRunAsync");if(n=xk({...n,lmcodeSync:!0,lmcodeDiscovery:"real"}),n.propertyOverlay)try{n={...n,propertyOverlay:qu(n.propertyOverlay)}}catch(s){return{success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]}}this.outputLogs=[],this.lastRecordedErrors=[],wu(n.recoveryProbe);let r=n.preparedCheck?vu(n.preparedCheck,n):this.scanAndCheck(e,n);return!r.ast||r.diagnostics.some(s=>s.severity==="error")?{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]}:this.runPhase(e,{...n,preparedCheck:r})}async runAsync(e,n={}){return this.runAsyncIsolated(e,n)}async runAsyncIsolated(e,n){if(n.dryLoopLimit!==void 0)throw Error("dryLoopLimit requires dryRun or dryRunAsync");if(n=xk({...n,lmcodeDiscovery:"real"}),n.propertyOverlay)try{n={...n,propertyOverlay:qu(n.propertyOverlay)}}catch(s){return{success:!1,output:[],diagnostics:[{severity:"error",message:s instanceof Error?s.message:String(s),line:1,column:1,file:n.file}]}}this.outputLogs=[],this.lastRecordedErrors=[],wu(n.recoveryProbe);let r=n.preparedCheck?vu(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);return!r.ast||r.diagnostics.some(s=>s.severity==="error")?{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]}:this.runPhaseAsync(e,{...n,preparedCheck:r})}runPhase(e,n={}){wu(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?vu(n.preparedCheck,n):this.scanAndCheck(e,n);if(n={...n,preparedCheck:r},Re(n)&&(!r.ast||r.diagnostics.some(p=>p.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};n={...n,propertyStore:n.propertyStore??new Jk(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let s=n.propertyStore;n.propertyOverlay&&s.setOverlay(n.propertyOverlay);let i=n.trace&&!Re(n)?new Jl(n.trace):void 0,o={functions:new Map(this.hostFunctions),globals:Re(n)?new Map(Sf([...this.initialGlobals])):new Map(this.initialGlobals),properties:s,tracer:i};n={...n,childEnv:this.prepareChildEnv(o,n)},o.functions.get("which")?.isDefault&&o.functions.set("which",{...o.functions.get("which"),fn:p=>Tk(p,n.hostContext?.cwd??process.cwd(),Re(n)?.environment??n.childEnv??n.hostContext?.env??process.env,n.hostContext?.platform??n.platform??process.platform)}),o.globals.set("PROPS",s.view()),o.globals.set("Directory",s.get("Directory")),o.globals.set("NonInteractive",s.get("NonInteractive"));let a=Re(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new Wy(()=>{let p=a.prepareProperties();return Rn(p)?p.then(()=>a.propertyView):a.propertyView}))),o.globals.set("RESUMEPOINT",null);let c={expand:(p,f={})=>{if(!f||typeof f!="object"||Array.isArray(f)||![Object.prototype,null].includes(Object.getPrototypeOf(f)))throw Error("expand: vars must be a map");let m=o.globals.get("ARGV")??[];return U_(p,g=>g.kind==="property"?s.get(g.key):g.kind==="argument"?Array.isArray(m)&&Object.hasOwn(m,g.index)?m[g.index]:void 0:Object.hasOwn(f,g.name)?Ur(f,g.name):void 0,LU)},get_property:(p,...f)=>s.get(p,...f),has_property:p=>s.has(p),get_properties:p=>s.copy(p),set_property:(p,f)=>s.set(p,f)};for(let[p,f]of Object.entries(c))o.functions.set(p,{...o.functions.get(p),fn:Re(n)&&p!=="set_property"?(...m)=>{let h=p!=="expand"||typeof m[0]=="string"&&ec(m[0]).some(y=>typeof y!="string"&&y.kind==="property")?Re(n).prepareProperties(p==="expand"?void 0:m[0]):void 0;return Rn(h)?h.then(()=>f(...m)):f(...m)}:f,dryRun:p==="set_property"?void 0:di(m=>{let h=p!=="expand"||typeof m[0]=="string"&&ec(m[0]).some(y=>typeof y!="string"&&y.kind==="property")?Re(n)?.prepareProperties(p==="expand"?void 0:m[0]):void 0;return Rn(h)?h.then(()=>f(...m)):f(...m)})});if(!r.ast||r.diagnostics.some(p=>p.severity==="error")||r.hasConcurrency)return this.executeSync(e,n,r,o);let u=jy(n.resumepoint,n.recoveryProbe),d=eoe(u,n.signal);try{let p=[],f;try{In(n.signal);for(let g of r.hostModules??[]){let h,y=()=>{if(h)return h;In(n.signal);let v=g.activate(this.activationContext(r,n,g,u,!1,o.tracer));if(Rn(v))throw v.then(_=>_.dispose()).catch(()=>{}),new Error(`Module '${g.name}' requires runAsync for activation`);if(!v||typeof v.dispose!="function")throw new Error(`Module '${g.name}' did not return a disposable`);return h=v,p.push(h),Re(n)?.own(h),this.bindModule(g,h,r,o),h};this.installBuiltinStubs(g,r,o,v=>(..._)=>(y(),o.functions.get(v).fn(..._)),v=>{let _=Re(n);if(_){if(!g.loadDryGlobals)throw Error("No passive dry loader for global "+v);let b=_.loadGlobals(g,Pk(_,n,_.lastSite));if(Rn(b))throw Promise.resolve(b).catch(()=>{}),Error("Async global requires dryRunAsync");return b[v]}return y(),o.globals.get(v)}),this.installPassiveProperties(g,r,s,n,!1),Re(n)||r.usedProperties&&r.hostDeclarations?.get(g)?.properties&&y()}f=this.executeSync(e,n,r,o,u),n.signal?.aborted&&(f={...f,success:!1,diagnostics:f.diagnostics.some(g=>g.severity==="error"&&g.message==="Execution aborted")?f.diagnostics:[...f.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(g){$s(u,g),f={...this.moduleFailure(g,r,n),errors:[...u.errors]}}Re(n)?.capture(f);let m=u.errors.length;this.collectModuleErrors(p,f,n.recoveryProbe!==void 0),Re(n)?.capture(f);for(let g of p.reverse())try{let h=Re(n)?Re(n).dispose(g):g.dispose();if(Rn(h))throw h.catch(()=>{}),new Error("Async disposal requires runAsync");Re(n)?.check()}catch(h){let y=Re(n);y&&(y.failure??={site:y.lastSite,message:h instanceof Error?h.message:String(h),untrusted:y.tainted}),this.cleanupWarning(h,f)}return f.errors=[...f.errors??[],...u.errors.slice(m)],this.lastRecordedErrors=[...f.errors],this.finishTrace(o,f),f}finally{u.finished=!0,d()}}async runPhaseAsync(e,n={}){wu(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?vu(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(n={...n,preparedCheck:s},Re(n)&&(!s.ast||s.diagnostics.some(f=>f.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};n={...n,propertyStore:n.propertyStore??new Jk(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let i=n.propertyStore;n.propertyOverlay&&i.setOverlay(n.propertyOverlay);let o=n.trace&&!Re(n)?new Jl(n.trace):void 0,a={functions:new Map(this.hostFunctions),globals:Re(n)?new Map(Sf([...this.initialGlobals])):new Map(this.initialGlobals),properties:i,tracer:o};n={...n,childEnv:this.prepareChildEnv(a,n)},a.functions.get("which")?.isDefault&&a.functions.set("which",{...a.functions.get("which"),fn:f=>Tk(f,n.hostContext?.cwd??process.cwd(),Re(n)?.environment??n.childEnv??n.hostContext?.env??process.env,n.hostContext?.platform??n.platform??process.platform)}),a.globals.set("PROPS",i.view()),a.globals.set("Directory",i.get("Directory")),a.globals.set("NonInteractive",i.get("NonInteractive"));let l=Re(n);l&&(l.propertyView=a.globals.get("PROPS"),a.globals.set("PROPS",new Wy(()=>{let f=l.prepareProperties();return Rn(f)?f.then(()=>l.propertyView):l.propertyView}))),a.globals.set("RESUMEPOINT",null);let u={expand:(f,m={})=>{if(!m||typeof m!="object"||Array.isArray(m)||![Object.prototype,null].includes(Object.getPrototypeOf(m)))throw Error("expand: vars must be a map");let g=a.globals.get("ARGV")??[];return U_(f,h=>h.kind==="property"?i.get(h.key):h.kind==="argument"?Array.isArray(g)&&Object.hasOwn(g,h.index)?g[h.index]:void 0:Object.hasOwn(m,h.name)?Ur(m,h.name):void 0,LU)},get_property:(f,...m)=>i.get(f,...m),has_property:f=>i.has(f),get_properties:f=>i.copy(f),set_property:(f,m)=>i.set(f,m)};for(let[f,m]of Object.entries(u))a.functions.set(f,{...a.functions.get(f),fn:Re(n)&&f!=="set_property"?(...g)=>{let y=f!=="expand"||typeof g[0]=="string"&&ec(g[0]).some(v=>typeof v!="string"&&v.kind==="property")?Re(n).prepareProperties(f==="expand"?void 0:g[0]):void 0;return Rn(y)?y.then(()=>m(...g)):m(...g)}:m,dryRun:f==="set_property"?void 0:di(g=>{let y=f!=="expand"||typeof g[0]=="string"&&ec(g[0]).some(v=>typeof v!="string"&&v.kind==="property")?Re(n)?.prepareProperties(f==="expand"?void 0:g[0]):void 0;return Rn(y)?y.then(()=>m(...g)):m(...g)})});if(!s.ast||s.diagnostics.some(f=>f.severity==="error"))return this.executeAsync(e,n,s,a);let d=jy(n.resumepoint,n.recoveryProbe),p=eoe(d,n.signal);try{let f=[],m;try{In(n.signal);for(let h of s.hostModules??[]){let y,v,_=()=>y??=Promise.resolve().then(async()=>{In(n.signal);let b=await h.activate(this.activationContext(s,n,h,d,!0,a.tracer));if(!b||typeof b.dispose!="function")throw new Error(`Module '${h.name}' did not return a disposable`);if(Re(n)?.sealed){try{await b.dispose()}catch{}throw new Fr("Dry pass finished")}return v=b,f.push(b),Re(n)?.own(b),this.bindModule(h,b,s,a),In(n.signal),b});this.installBuiltinStubs(h,s,a,b=>async(...w)=>{let T=await _();return Re(n)?.check(),a.functions.get(b).fn(...w)},async b=>{let w=Re(n);if(w){if(!h.loadDryGlobals)throw Error("No passive dry loader for global "+b);return(await w.loadGlobals(h,Pk(w,n,w.lastSite)))[b]}return await _(),a.globals.get(b)}),this.installPassiveProperties(h,s,i,n,!0),Re(n)||s.usedProperties&&s.hostDeclarations?.get(h)?.properties&&await _()}m=await this.executeAsync(e,n,s,a,d),n.signal?.aborted&&(m={...m,success:!1,diagnostics:m.diagnostics.some(h=>h.severity==="error"&&h.message==="Execution aborted")?m.diagnostics:[...m.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(h){$s(d,h),m={...this.moduleFailure(h,s,n),errors:[...d.errors]}}Re(n)?.capture(m);let g=d.errors.length;this.collectModuleErrors(f,m,n.recoveryProbe!==void 0),Re(n)?.capture(m);for(let h of f.reverse())try{let y=Re(n)?Re(n).dispose(h):h.dispose();Re(n)?await Re(n).wait(y):await y}catch(y){let v=Re(n);v&&(v.failure??={site:v.lastSite,message:y instanceof Error?y.message:String(y),untrusted:v.tainted}),this.cleanupWarning(y,m)}return m.errors=[...m.errors??[],...d.errors.slice(g)],this.lastRecordedErrors=[...m.errors],this.finishTrace(a,m),m}finally{d.finished=!0,p()}}finishTrace(e,n){if(e.tracer)try{for(let r of n.errors??[])e.tracer.error(r);e.tracer.end(n.exitCode??(n.success&&!n.errors?.length?0:1))}catch(r){n.success=!1,n.exitCode=1,n.diagnostics.push({severity:"error",message:"Trace write failed: "+String(r),line:1,column:1})}}executeSync(e,n,r,s,i){let o=[],a="",{ast:l,diagnostics:c,hasConcurrency:u}=r;if(c.filter(h=>h.severity==="error").length>0||!l)return this.outputLogs=o,{success:!1,diagnostics:c,output:o};if(u)return this.outputLogs=o,{success:!1,diagnostics:[...c,{message:"Concurrency constructs ('parallel', 'parallel_map', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:n.file}],output:o};let p=i??jy(n.resumepoint,n.recoveryProbe),f,m,g=s.tracer??(n.trace&&!Re(n)?new Jl(n.trace):void 0);s.tracer=g;try{f=new tx(s.functions,(v,_)=>{o.push(v);let b=_?v:v+`
|
|
4835
4835
|
`;a+=b,g?.output(b),n.stdout?.(v,_)},!1,s.globals,n.stderr,this.promptHumanConfig,p,n.hostContext?.platform??n.platform??process.platform,Re(n)),f.childEngineFactory=v=>this.createChildEngine(v),f.compileOptions=n,f.lmcodeOwner.bindSignal(n.signal),f.executionOrigin=n.executionOrigin,f.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.childEnv},f.warningDiagnostics=c,f.abortSignal=n.signal,f.recoverScopedReads=r.recoverScopedReads??new WeakMap,f.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,m=this.trackResourceRun(f.resources),g&&(Qie(l)&&g.hideContent(),f.tracer=g,g.begin(n.file??"<main>",e,s.globals));let h;try{h=f.evaluateProgram(l)}catch(v){throw g&&!v?.isControlFlow&&v?.name!=="LMScriptExit"&&g.error(v),v}f.lmcodeOwner.close();let y=f.getRecordedErrors();return this.outputLogs=[...o],this.lastRecordedErrors=y,{success:!0,value:h,diagnostics:c,output:o,errors:y,resourceRun:m,stdout:a}}catch(h){try{f?.lmcodeOwner.close()}catch(w){c.push({severity:"warning",message:"lmcode cleanup: "+String(w),line:1,column:1})}$s(p,h);let y=[...p.errors];if(this.lastRecordedErrors=y,h instanceof rs||h?.name==="LMScriptExit"||h?.isControlFlow){this.outputLogs=[...o];let w=typeof h.exitCode=="number"?h.exitCode:0;return{success:w===0,value:w,exitCode:w,diagnostics:c,output:o,errors:y,resourceRun:m,stdout:a}}let v=h instanceof B?h.line:1,_=h instanceof B?h.column:1,b=h instanceof B&&h.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...c,{message:h?.message||String(h),line:v,column:_,severity:"error",file:b}],output:o,errors:y,resourceRun:m,stdout:a}}}async executeAsync(e,n,r,s,i){let o=[],a="",{ast:l}=r,c=[...r.diagnostics];if(c.filter(g=>g.severity==="error").length>0||!l)return this.outputLogs=o,this.lastRecordedErrors=[],{success:!1,diagnostics:c,output:o,errors:[]};let d=i??jy(n.resumepoint,n.recoveryProbe),p,f,m=s.tracer??(n.trace&&!Re(n)?new Jl(n.trace):void 0);s.tracer=m;try{p=new tx(s.functions,(y,v)=>{o.push(y);let _=v?y:y+`
|
|
4836
4836
|
`;a+=_,m?.output(_),n.stdout?.(y,v)},!0,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,Re(n)),p.childEngineFactory=y=>this.createChildEngine(y),p.compileOptions=n,p.lmcodeOwner.bindSignal(n.signal),p.executionOrigin=n.executionOrigin,p.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.childEnv},p.warningDiagnostics=c,p.abortSignal=n.signal,p.recoverScopedReads=r.recoverScopedReads??new WeakMap,p.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,f=this.trackResourceRun(p.resources),m&&(Qie(l)&&m.hideContent(),p.tracer=m,m.begin(n.file??"<main>",e,s.globals));let g;try{g=await p.evaluateProgramAsync(l)}catch(y){throw m&&!y?.isControlFlow&&y?.name!=="LMScriptExit"&&m.error(y),y}p.lmcodeOwner.close();let h=p.getRecordedErrors();return this.outputLogs=[...o],this.lastRecordedErrors=h,{success:!0,value:g,diagnostics:c,output:o,errors:h,resourceRun:f,stdout:a}}catch(g){try{p?.lmcodeOwner.close()}catch(b){c.push({severity:"warning",message:"lmcode cleanup: "+String(b),line:1,column:1})}$s(d,g);let h=[...d.errors];if(this.lastRecordedErrors=h,g instanceof rs||g?.name==="LMScriptExit"||g?.isControlFlow){this.outputLogs=[...o];let b=typeof g.exitCode=="number"?g.exitCode:0;return{success:b===0,value:b,exitCode:b,diagnostics:c,output:o,errors:h,resourceRun:f,stdout:a}}let y=g instanceof B?g.line:1,v=g instanceof B?g.column:1,_=g instanceof B&&g.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...c,{message:g?.message||String(g),line:y,column:v,severity:"error",file:_}],output:o,errors:h,resourceRun:f,stdout:a}}}lastRecordedErrors=[];resourceRuns=new Map;trackResourceRun(e){for(this.resourceRuns.set(e.token,e);this.resourceRuns.size>64;)this.resourceRuns.delete(this.resourceRuns.keys().next().value);return e.token}terminateResourceRuns(){for(let e of this.resourceRuns.values())e.terminate()}inspectResources(e){return this.resourceRuns.get(e)?.snapshot()??[]}getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getFunctionMetadata(e){let n=this.hostFunctions.get(e);return n?Object.freeze({arity:n.arity,publicArity:n.signature?.publicArity,description:n.description,params:n.signature?.nativeParams??n.params,publicParams:n.signature?.publicParams??n.params,returnType:n.signature?.returnType??w1(n.returnType),dryRun:n.dryRun,signature:n.signature}):void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};DU=le.basename(d1(import.meta.url));(DU==="lmscript.ts"||DU==="lmscript.js"||DU==="lmscript")&&process.argv[1]&&q.existsSync(process.argv[1])&&q.realpathSync(d1(import.meta.url))===q.realpathSync(le.resolve(process.argv[1]))&&FHe()});Pf();ho();export{fa as CompiledDsl,ta as LMScript};
|