@lmctl-ai/lmctl 0.2.252 → 0.2.254
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build-info.json +1 -1
- package/dist/cli/lmscript.js +2 -2
- package/dist/lmbee.js +1 -1
- package/package.json +1 -1
package/build-info.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"sha": "
|
|
1
|
+
{"sha": "996d91fdf73770efa445773fcea5e44a67393629", "dirty": false, "builtAt": "2026-10-12T23:56:41.000Z"}
|
package/dist/cli/lmscript.js
CHANGED
|
@@ -413,8 +413,8 @@ fn clamp(val, low, high) {
|
|
|
413
413
|
`)+(l.output.length>0?`
|
|
414
414
|
`:""),u=l.exitCode!==void 0?l.exitCode:l.success&&!l.errors?.length?0:1;return{success:l.success&&u===0,stdout:c,output:[...l.output],value:l.value,exit_code:u,code:u,errors:l.errors??[]}}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${n}
|
|
415
415
|
`):console.error(`error: ${n}`),n},{min:1},"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("http_get",e=>o_(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep_ms",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");let n=Date.now()+e;for(;Date.now()<n;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human_config",(e,n)=>{if(e===void 0)return{mode:this.promptHumanConfig.mode??"interactive",dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200};if(typeof e=="string")e==="interactive"?this.promptHumanConfig.mode="interactive":e==="file"?(this.promptHumanConfig.mode="file",n&&(this.promptHumanConfig.dir=String(n))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=e);else if(e&&typeof e=="object"){let r=e.mode?String(e.mode):e.dir?"file":this.promptHumanConfig.mode??"interactive",s=e.dir!==void 0?String(e.dir):this.promptHumanConfig.dir,i=e.timeout_ms!==void 0?Number(e.timeout_ms):e.timeoutMs!==void 0?Number(e.timeoutMs):this.promptHumanConfig.timeoutMs,o=e.poll_ms!==void 0?Number(e.poll_ms):e.pollIntervalMs!==void 0?Number(e.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=r==="file"?"file":"interactive",this.promptHumanConfig.dir=s,this.promptHumanConfig.timeoutMs=typeof i=="number"&&Number.isFinite(i)?i:void 0,this.promptHumanConfig.pollIntervalMs=typeof o=="number"&&Number.isFinite(o)&&o>0?o:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},{min:0,max:2},"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",!0),this.registerFunction("prompt_human",(e,n)=>{if((n?.mode??(n?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let s=n?.dir??this.promptHumanConfig.dir;if(!s)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsyncMode)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return p_(e,{dir:s,sessionId:n?.sessionId??n?.sessionid??n?.id,timeoutMs:n?.timeout_ms??n?.timeoutMs??this.promptHumanConfig.timeoutMs,pollIntervalMs:n?.poll_ms??n?.pollIntervalMs??this.promptHumanConfig.pollIntervalMs})}return this.isAsyncMode?al(e):m_(e)},{min:0,max:2},"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",!0),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(n){throw new Error(`JSON parse error: ${n.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,n=null)=>IN(e,n),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,n)=>JSON.stringify(e,null,n),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(Qr(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(Qr(e)):[],1,"Returns array of [key, value] pairs"),this.registerFunction("has_key",(e,n)=>e&&typeof e=="object"?Object.hasOwn(e,n):!1,2,"Checks if object has key"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(Qr(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=Vi(e,n);return s!==void 0?s:r},{min:2,max:3},"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,n,r="")=>{let s=Vi(e,n);return s==null?r:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,n,r=0)=>{let s=Vi(e,n);return s==null?r:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,n,r=!1)=>{let s=Vi(e,n);if(s==null)return r;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,n,r=[])=>{let s=Vi(e,n);return Array.isArray(s)?s:r},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",Vd,2,"Requires a present value; injected diagnostic/captured error and exit 1 on missing",!0),this.registerFunction("set",(e,n,r)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(n)?n:String(n).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(wt(i,a)==null||typeof wt(i,a)!="object")&&st(i,a,{}),i=wt(i,a)}return s.length>0&&st(i,s[s.length-1],r),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,n)=>Array.isArray(e)?e.map(r=>wt(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&wt(s,n)===r):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,n,r)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&wt(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...Qr(e),...Qr(n)}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,n)=>(e&&typeof e=="object"&&delete e[n],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints line to output log",!0),this.registerFunction("split",(e,n)=>String(e).split(n),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let n=e.split(/\r?\n/);for(let r=n.length-1;r>=0;r--){let s=n[r].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("parse_file_blocks",e=>mN(e),1,"Parses === FILE: path === ... === END === blocks into [{path, content}]"),this.registerFunction("format_file_blocks",e=>pN(e),1,"Formats [{path, content}] as file blocks; inverse of parse_file_blocks"),this.registerFunction("write_files",(e,n,r)=>_N(e,n,r===!0),{min:2,max:3},{description:"Writes [{path, content}] under dir atomically, rejecting unsafe paths; returns {written, rejected}",params:[{name:"dir",type:"string"},{name:"files",type:"array"},{name:"dryrun",type:"boolean",optional:!0}],returnType:"map"}),this.registerFunction("read_tree",(e,n)=>EN(e,n),{min:1,max:2},"Reads text files under dir as sorted [{path, content}] with default ignores"),this.registerFunction("kv_from_last_paragraph",e=>kN(e),1,"Parses key: value lines of the last paragraph into a map"),this.registerFunction("split_command",e=>RN(e),1,"Splits one command line into argv with POSIX quoting; shell syntax is an error"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,n=", ")=>Array.isArray(e)?e.join(n):String(e),{min:1,max:2},"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("upper_first",e=>{let n=String(e);return n.length===0?"":n.charAt(0).toUpperCase()+n.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,n=>n.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,n)=>Array.isArray(e)?e.includes(n):String(e).includes(String(n)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,n)=>Array.isArray(e)?e.includes(n):String(e).includes(String(n)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,n)=>String(e).startsWith(n),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,n)=>String(e).startsWith(n),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,n)=>String(e).endsWith(n),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,n)=>String(e).endsWith(n),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,n,r)=>Array.isArray(e)?e.indexOf(n,r):String(e).indexOf(n,r),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent"),this.registerFunction("last_index_of",(e,n)=>Array.isArray(e)?e.lastIndexOf(n):String(e).lastIndexOf(n),2,"Finds last substring or strictly equal array element index; -1 if absent"),this.registerFunction("count_matches",(e,n)=>n?String(e).split(n).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,n,r)=>{let s=String(e),i=Math.trunc(Number(n))||0,o=i<0?Math.max(0,s.length+i):Math.min(s.length,i);if(r===void 0)return s.slice(o);let a=Math.max(0,Math.trunc(Number(r))||0);return s.slice(o,o+a)},{min:2,max:3},"Returns substring by end-relative start and optional length"),this.registerFunction("substring",(e,n,r)=>String(e).substring(n,r),{min:2,max:3},"Returns substring between indices"),this.registerFunction("slice",(e,n,r)=>e!=null?e.slice(n,r):"",{min:2,max:3},"Slices string or array"),this.registerFunction("char_at",(e,n)=>String(e).charAt(n),2,"Returns character at index"),this.registerFunction("char_code",(e,n=0)=>String(e).charCodeAt(n),{min:1,max:2},"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),{min:0},"Returns string from character codes"),this.registerFunction("replace",(e,n,r)=>String(e).replace(n,r),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,n,r)=>String(e).replaceAll(n,r),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,n)=>String(e).repeat(n),2,"Repeats string count times"),this.registerFunction("pad_start",(e,n,r=" ")=>String(e).padStart(n,r),{min:2,max:3},"Left-pads string"),this.registerFunction("pad_end",(e,n,r=" ")=>String(e).padEnd(n,r),{min:2,max:3},"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Literal emptiness: null, empty string, empty array or empty map; whitespace-only strings are not empty. Use is_blank for whitespace."),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof ur,1,"Checks if value is a first-class function reference"),this.registerFunction("cmd_render",(e,n)=>zd(e,n),{min:1,max:2},"Renders argv as posix, windows or powershell text; execution never uses rendered text",!0),this.registerFunction("sprintf",(e,...n)=>Ja(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>Ja(e,n,"printf"),{min:1},"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules",!0),this.registerFunction("format",(e,...n)=>{let r=String(e),s=n.length===1&&typeof n[0]=="object"&&n[0]!==null&&!Array.isArray(n[0])?n[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<r.length;){let c=r[l];if(c==="{"&&r[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&r[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=r.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=r.slice(l+1,u);if(d==="")o+=i<n.length?a(n[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<n.length?a(n[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("regex_test",(e,n,r="")=>Qi(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",AN,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",CN,{min:2,max:3},"Returns capture arrays with Unicode-aware zero-width progress; y is rejected"),this.registerFunction("regex_replace",(e,n,r,s="")=>String(e).replace(Qi(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(Qi(n,r)),{min:2,max:3},"Splits text at regular expression matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("range",(e,n,r=1)=>{let s=n===void 0?0:e,i=n===void 0?e:n,o=[];if(r>0)for(let a=s;a<i;a+=r)o.push(a);else if(r<0)for(let a=s;a>i;a+=r)o.push(a);return o},{min:1,max:3},"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...n)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...n)},{min:0},"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,n)=>Math.pow(e,n),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("sha256",e=>{if(typeof e!="string")throw new Error("sha256: expected a string");return aN("sha256").update(e,"utf8").digest("hex")},1,"Returns lowercase SHA-256 of UTF-8 text; strings only"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,n)=>eO(e,n),2,"Formats local time: epoch milliseconds first, format string second"),this.registerFunction("coalesce",(...e)=>{for(let n of e)if(n!=null)return n;return null},{min:0},"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,n)=>e??n,2,"Returns fallback if value is null/undefined, else value"),this.registerFunction("if_else",(e,n,r)=>e?n:r,3,"Eager compatibility helper: arguments evaluate eagerly; use condition ? thenValue : elseValue for lazy selection"),this.registerFunction("str",e=>kd(e),1,"Converts lists and maps to compact JSON; scalars to normal text"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof ur?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,n="Assertion failed")=>{if(!e)throw new Error(n);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,n,r,s,i=!1,o=!1){if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is reserved; rename this function");let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=Rd(typeof s=="object"?s.doc:void 0),d=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==m&&!d)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${p}'`);let f=typeof s=="object"?{returnsResource:s.returnsResource===!0||void 0,usesResource:s.usesResource===!0||void 0,closesResource:s.closesResource===!0||void 0}:{},h=typeof s=="object"?s.params?.map(Wd):void 0,g=typeof s=="object"?s.returnType:void 0,y=en(e,r,h,g,u);zy(e,typeof s=="object"?s.readonly:void 0,y),this.functionOriginModule.set(e,m);let b=typeof s=="object"&&s.readonly===!0||void 0;if(this.hostFunctions.set(e,{fn:n,arity:y.nativeArity,description:a,isDefault:l,isContainerMutation:c,doc:u,params:y.nativeParams,returnType:g,readonly:b,...typeof s=="object"&&s[Be]?{[Be]:s[Be]}:{},dryControl:Wa(e,typeof s=="object"?s.dryControl:void 0,y),signature:y,...f}),u)this.functionDocs.set(e,{...u,module:u.module??m});else{let _=y.publicArity,v=typeof _=="number"?_:_?.min??0,E=typeof _=="number"?_:_?.max,I=y.publicParams.length?y.publicParams.map(T=>T.optional?`[${T.name}]`:T.rest?`...${T.name}`:T.name):Array.from({length:E??v},(T,k)=>(k>=v?"[":"")+"arg"+(k+1)+(k>=v?"]":""));E===void 0&&!y.publicParams.some(T=>T.rest)&&I.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+I.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)}schemaFactory;registerSchemaModuleFactory(e){return this.schemaFactory=e,this}getSchemaModuleFactory(){return this.schemaFactory}moduleSpecResolver;registerModuleSpecResolver(e){return this.moduleSpecResolver=e,this}getModuleSpecResolver(){return this.moduleSpecResolver}registerNativeModule(e){if(!e.nativeNamespace||e.name!=="native:"+e.nativeNamespace||!/^[A-Za-z_]\w*$/.test(e.nativeNamespace))throw Error("Invalid native namespace");if(this.nativeCatalog.has(e.name))throw Error("Duplicate native module "+e.name);return this.nativeCatalog.set(e.name,e),this}nativeCompileOptions(){return new Map([...this.nativeCatalog].map(([e,n])=>[e,{namespace:n.nativeNamespace,members:n.declarations.functions.map(r=>r.name)}]))}registerHostModule(e){return this.hostCatalog.set(e.name,e),this}getHostModule(e){return this.hostCatalog.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}getNativeModules(){return[...this.nativeCatalog.values()]}createChildEngine(e={}){let n=new t({resolveHostModule:this.hostResolver});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,readonly:i.readonly,dryControl:i.dryControl,[Be]:i[Be],doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...Zr(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,readonly:i.readonly,dryControl:i.dryControl,[Be]:i[Be],doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...Zr(i)});for(let s of this.nativeCatalog.values())n.registerNativeModule(s);this.schemaFactory&&n.registerSchemaModuleFactory(this.schemaFactory),this.moduleSpecResolver&&n.registerModuleSpecResolver(this.moduleSpecResolver);let r=new Set(e.excludeBuiltins??[]);for(let s of this.builtinProviders.values())r.has(s.name)||n.registerBuiltinProvider(s);for(let s of this.hostCatalog.values())n.registerHostModule(s);return e.args&&(n.setGlobal("args",[...e.args]),n.setGlobal("ARGV",[...e.args])),n}async scanAndCheckAsync(e,n={}){return Dn.run(void 0,()=>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 HN(e,{...n,reservedFunctionPrefixes:n.reservedFunctionPrefixes??this.reservedFunctionPrefixes,nativeModules:this.nativeCompileOptions(),schemaModule:n.schemaModule??this.schemaFactory,resolveModuleSpec:n.resolveModuleSpec??this.moduleSpecResolver,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:Dy(r,n.file)}}}scanAndCheck(e,n={}){return Dn.run(void 0,()=>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??UN(e,{...n,reservedFunctionPrefixes:n.reservedFunctionPrefixes??this.reservedFunctionPrefixes,nativeModules:this.nativeCompileOptions(),schemaModule:n.schemaModule??this.schemaFactory,resolveModuleSpec:n.resolveModuleSpec??this.moduleSpecResolver,builtinProviderNames:[...this.builtinProviders.keys(),...n.builtinProviderNames??this.builtinProviderNames??[]]}),{program:o,hostImports:a,packages:l}=i;r=i.diagnostics,s=i.diagnosticPaths;let c=new Map(this.hostFunctions),u=[],d=new Map,m=new Map,p=new Set,f=[],h={known:[],closedTables:[],removedGlobals:{}};for(let v of[...[...this.builtinProviders.keys(),...this.hostCatalog.keys()].map(E=>({name:E,line:1,column:1,file:n.file})),...a]){if(u.some(T=>T.name===v.name))continue;let E;try{E=i.schemaModules?.get(v.name)??this.nativeCatalog.get(v.name)??this.builtinProviders.get(v.name)??this.hostCatalog.get(v.name)??(n.resolveHostModule??this.hostResolver)?.(v.name)}catch(T){let k=$N(T);throw new D(`Cannot load module '${v.name}': ${k}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!E)throw new D(`Missing host module '${v.name}'. Install with npm install ${v.name} or set LMSCRIPT_MODULES; for a file use './${v.name}.lms'.`,v.line,v.column,"CHECKER",v.file);let I;try{let T=E.declarations,k=T?.functions,O=T?.globals;Array.isArray(k)&&Array.isArray(O)&&(I={readonlyPrograms:MN(T),functions:k.map(N=>Object.freeze({...N,arity:Bd(N.arity),params:N.params?Object.freeze(N.params.map(Wd)):void 0,doc:Rd(N.doc)})),globals:O.map(N=>({...N})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(E.name!==v.name||!I||typeof E.activate!="function")throw new D(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let T of I.functions){let k=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!(E.nativeNamespace?new RegExp("^"+E.nativeNamespace+"\\.[A-Za-z_]\\w*$"):/^[a-zA-Z_]\w*$/).test(T.name)||Object.hasOwn(so,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 D(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let O=m.get(T.name);if(T.override===!0&&c.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new D(`Module '${v.name}' cannot override ${O===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${O}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(c.has(T.name)&&!(T.override===!0&&c.get(T.name)?.isDefault))throw new D(`Module function collision: '${T.name}' in module '${v.name}'${O===void 0?"":` is already declared by module '${O}'`}`,v.line,v.column,"CHECKER",v.file);let N=en(T.name,T.arity,T.params,T.returnType,T.doc);zy(T.name,T.readonly,N),c.set(T.name,{arity:N.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:N.nativeParams,returnType:N.returnType??void 0,readonly:T.readonly===!0||void 0,dryControl:Wa(T.name,T.dryControl,N),signature:N,...Zr(T)}),m.set(T.name,v.name)}for(let T of I.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(so,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 D(`Module global collision or invalid name: '${T.name}'`,v.line,v.column,"CHECKER",v.file);p.add(T.name),this.builtinProviders.has(v.name)&&f.push(T.name)}I.properties&&(h.known=[...h.known,...I.properties.known],h.closedTables=[...h.closedTables??[],...I.properties.closedTables??[]],h.removedGlobals={...h.removedGlobals,...I.properties.removedGlobals}),u.push(E),d.set(E,I)}let g=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],y=new Dd(c,{...n,globals:g,builtinGlobals:f,propertyDeclarations:h,sourcePackages:l}),b=[...r,...y.check(o)];for(let v of b)if(v.message.startsWith("Call to undefined function"))for(let E of this.hostCatalog.values())for(let I of E.declarations.functions)v.message.includes(`'${I.name}'`)&&(v.message+=`; provided by module '${E.name}': add import "${E.name}";`);for(let v of b)for(let E of this.nativeCatalog.values())new RegExp("(?<![\\w.])"+E.nativeNamespace+"\\.").test(v.message)&&!a.some(I=>I.name===E.name)&&(v.message+="; namespace "+E.nativeNamespace+' is not loaded: add import "'+E.name+'" before use');let _={ast:o,diagnosticPaths:s,diagnostics:b,hasConcurrency:y.hasConcurrency,hostModules:u,hostDeclarations:d,usedGlobals:[...y.usedGlobals],usedProperties:y.usedProperties,recoverLabels:[...y.recoverLabels],hasRecover:y.hasRecover,recoverScopedReads:y.recoverScopedReads,recoverScopedWrites:y.recoverScopedWrites};return Kr(_,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:Dy(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 eo(()=>i(a.name)));for(let a of o.functions){let l=en(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,readonly:a.readonly===!0||void 0,dryControl:Wa(a.name,a.dryControl,l),signature:l,...Zr(a)})}}activationContext(e,n,r,s){return{runReadonlyProgram:(o,a=6e4)=>{let l=Dn.getStore();if(!l?.active||!l.readonly||l.module!==r||l.run!==s||s.finished)throw Error("Command requires an active readonly call from its declaring module");let c=tn(o);if(!Array.isArray(c)||Array.from({length:c.length},(g,y)=>!Object.hasOwn(c,y)).some(Boolean)||c.some(g=>typeof g!="string"))throw Error("Readonly argv must contain strings");if(!(e.hostDeclarations?.get(r)?.readonlyPrograms??[]).some(g=>g.length<=c.length&&g.every((y,b)=>y===c[b])))throw Error("Command does not match a readonly grant");if(!Number.isSafeInteger(a)||a<0)throw Error("Readonly command timeout must be a non-negative safe integer");Ke(n.signal);let d=ne(n);d?.check();let m=d?Math.max(1,Math.min(a===0?1/0:a,Math.ceil(d.deadline-performance.now()))):a,p=n.hostContext?.platform??n.platform??process.platform,f={cwd:n.hostContext?.cwd??process.cwd(),env:d?.environment??n.hostContext?.env??process.env};if(l.async)return ol(c,m,p,n.signal,f);let h=l_(c,m,p,f);return d?.check(),h},noPreflight:n.noPreflight,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:o=>{let a=ne(n);if(a){a.recordError(o);return}Xa(s,o)},cwd:n.hostContext?.cwd??process.cwd(),env:Object.freeze({...n.hostContext?.env??process.env}),signal:n.signal,propertyStore:n.propertyStore,usedGlobals:(e.usedGlobals??[]).filter(o=>(e.hostDeclarations?.get(r)??r.declarations).globals.some(a=>a.name===o)),nativeModules:[...this.nativeCatalog.values()],builtinProviders:[...this.builtinProviders.values()],resolveHostModule:n.resolveHostModule??this.hostResolver,reservedFunctionPrefixes:n.reservedFunctionPrefixes,builtinProviderNames:n.builtinProviderNames??[...this.builtinProviders.keys()],createChildEngine:o=>this.createChildEngine(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?.addSource(e.name,()=>n.loadProperties(),i.properties.known)}for(let o of i.functions){if(typeof n.functions?.[o.name]!="function")throw new Error(`Module '${e.name}' did not bind '${o.name}'`);let a=en(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:LN(s.readonlyRun,e,o.readonly===!0,s.async===!0,n.functions[o.name]),arity:a.nativeArity,doc:o.doc,params:a.nativeParams,returnType:a.returnType??void 0,readonly:o.readonly===!0||void 0,dryControl:Wa(o.name,o.dryControl,a),signature:a,...Zr(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 Dn.run(void 0,()=>this.dryRunIsolated(e,n))}dryRunIsolated(e,n){Yr(n.recoveryProbe);let r=new rl(n);try{let s=this.runPhase(e,{...n,signal:n.signal?AbortSignal.any([n.signal,r.controller.signal]):r.controller.signal,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?Kr(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[jd]: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 Dn.run(void 0,()=>this.dryRunAsyncIsolated(e,n))}async dryRunAsyncIsolated(e,n){Yr(n.recoveryProbe);let r=new rl(n);try{return r.report(await r.wait(this.runPhaseAsync(e,{...n,signal:n.signal?AbortSignal.any([n.signal,r.controller.signal]):r.controller.signal,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?Kr(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[jd]: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 Dn.run(void 0,()=>this.runIsolated(e,n))}runIsolated(e,n){if(n.propertyOverlay)try{n={...n,propertyOverlay:Us(n.propertyOverlay)}}catch(a){return{success:!1,output:[],diagnostics:[{severity:"error",message:a instanceof Error?a.message:String(a),line:1,column:1,file:n.file}]}}this.outputLogs=[],this.lastRecordedErrors=[],Yr(n.recoveryProbe);let r=n.preparedCheck?Kr(n.preparedCheck,n):this.scanAndCheck(e,n);if(!r.ast||r.diagnostics.some(a=>a.severity==="error"))return{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]};if(n.noPreflight||n.trace)return this.runPhase(e,{...n,preparedCheck:r});let s=[],i=this.dryRun(e,{...n,[Hd]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[Ud]:n.dryrunTimeoutMs===void 0?16e3:void 0,preparedCheck:r,compiledSource:r.compiledSource});n.onPreflight?.(i);let o=this.preflightStop(i,n,s);return o||{...this.runPhase(e,{...n,preparedCheck:r}),preflight:i}}preflightStop(e,n,r){if(n.signal?.aborted)return{success:!1,exitCode:1,output:[],diagnostics:[{severity:"error",message:"Execution aborted",line:1,column:1}],preflight:e};if(e.exitCode!==0){let s=[];for(let i of r){if(n.signal?.aborted)return{success:!1,exitCode:1,output:s,diagnostics:[{...i.site,severity:"error",message:"Execution aborted"}],preflight:e};s.push(i.text);try{n.stdout?.(i.text)}catch(o){return{success:!1,exitCode:1,output:s,diagnostics:[{...i.site,severity:"error",message:"Error in host function '"+i.name+"': "+(o instanceof Error?o.message:String(o))}],preflight:e}}}return this.outputLogs=[...s],{success:!1,exitCode:1,output:s,diagnostics:e.stop?[e.diagnostics.filter(i=>i.severity==="error"&&i.line===e.stop.line&&i.column===e.stop.column&&(i.message===e.stop.reason||i.message.endsWith(": "+e.stop.reason))).at(-1)??{severity:"error",file:e.stop.file,line:e.stop.line,column:e.stop.column,message:e.stop.reason}]:e.diagnostics.filter(i=>i.severity==="error"),preflight:e}}}async runAsync(e,n={}){return Dn.run(void 0,()=>this.runAsyncIsolated(e,n))}async runAsyncIsolated(e,n){if(n.propertyOverlay)try{n={...n,propertyOverlay:Us(n.propertyOverlay)}}catch(a){return{success:!1,output:[],diagnostics:[{severity:"error",message:a instanceof Error?a.message:String(a),line:1,column:1,file:n.file}]}}this.outputLogs=[],this.lastRecordedErrors=[],Yr(n.recoveryProbe);let r=n.preparedCheck?Kr(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);if(!r.ast||r.diagnostics.some(a=>a.severity==="error"))return{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]};if(n.noPreflight||n.trace)return this.runPhaseAsync(e,{...n,preparedCheck:r});let s=[],i=await this.dryRunAsync(e,{...n,[Hd]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[Ud]:n.dryrunTimeoutMs===void 0?16e3:void 0,preparedCheck:r,compiledSource:r.compiledSource});n.onPreflight?.(i),await new Promise(a=>setImmediate(a));let o=this.preflightStop(i,n,s);return o||{...await this.runPhaseAsync(e,{...n,preparedCheck:r}),preflight:i}}runPhase(e,n={}){Yr(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?Kr(n.preparedCheck,n):this.scanAndCheck(e,n);if(ne(n)&&(!r.ast||r.diagnostics.some(d=>d.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};ne(n)?.start(),n={...n,propertyStore:n.propertyStore??new el(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let s=n.propertyStore;n.propertyOverlay&&s.setOverlay(n.propertyOverlay);let i={functions:new Map(this.hostFunctions),globals:ne(n)?new Map(tn([...this.initialGlobals])):new Map(this.initialGlobals),properties:s};i.functions.get("which")?.[Be]&&i.functions.set("which",{...i.functions.get("which"),fn:d=>Td(d,n.hostContext?.cwd??process.cwd(),ne(n)?.environment??n.hostContext?.env??process.env,n.hostContext?.platform??n.platform??process.platform)}),i.globals.set("PROPS",s.view()),i.globals.set("Directory",s.get("Directory")),i.globals.set("NonInteractive",s.get("NonInteractive"));let o=ne(n);o&&(o.propertyView=i.globals.get("PROPS"),i.globals.set("PROPS",new eo(()=>{let d=o.prepareProperties();return rt(d)?d.then(()=>o.propertyView):o.propertyView}))),i.globals.set("RESUMEPOINT",null);let l={expand:(d,m={})=>{if(!m||typeof m!="object"||Array.isArray(m)||![Object.prototype,null].includes(Object.getPrototypeOf(m)))throw Error("expand: vars must be a map");let p=i.globals.get("ARGV")??[];return Ua(d,f=>f.kind==="property"?s.get(f.key):f.kind==="argument"?Array.isArray(p)&&Object.hasOwn(p,f.index)?p[f.index]:void 0:Object.hasOwn(m,f.name)?wt(m,f.name):void 0,kd)},get_property:(d,...m)=>s.get(d,...m),has_property:d=>s.has(d),get_properties:d=>s.copy(d),set_property:(d,m)=>s.set(d,m)};for(let[d,m]of Object.entries(l))i.functions.set(d,{...i.functions.get(d),fn:ne(n)&&d!=="set_property"?(...p)=>{let h=d!=="expand"||typeof p[0]=="string"&&Ji(p[0]).some(g=>typeof g!="string"&&g.kind==="property")?ne(n).prepareProperties(d==="expand"?void 0:p[0]):void 0;return rt(h)?h.then(()=>m(...p)):m(...p)}:m});if(!r.ast||r.diagnostics.some(d=>d.severity==="error")||r.hasConcurrency)return this.executeSync(e,n,r,i);let c=Ki(n.resumepoint,n.recoveryProbe);i.readonlyRun=c;let u=Jy(c,n.signal);try{let d=[],m;try{Ke(n.signal);for(let f of r.hostModules??[]){if(this.builtinProviders.has(f.name)||f.nativeNamespace||ne(n)){let g,y=()=>{if(g)return g;Ke(n.signal);let b=f.activate(this.activationContext(r,n,f,c));if(rt(b))throw b.then(_=>_.dispose()).catch(()=>{}),new Error(`Module '${f.name}' requires runAsync for activation`);if(!b||typeof b.dispose!="function")throw new Error(`Module '${f.name}' did not return a disposable`);return g=b,d.push(g),ne(n)?.own(g),this.bindModule(f,g,r,i),g};f.nativeNamespace&&(i.nativeImports??=new Map,i.nativeImports.set(f.name,y)),this.installBuiltinStubs(f,r,i,b=>(..._)=>(y(),i.functions.get(b).fn(..._)),b=>(y(),i.globals.get(b))),ne(n)&&r.hostDeclarations?.get(f)?.properties&&(ne(n).propertyLoads.push(y),s.addSource(f.name,()=>{let b=y();if(!b.loadProperties)throw Error("Provider properties unavailable");return b.loadProperties()},r.hostDeclarations.get(f).properties.known)),ne(n)||r.usedProperties&&r.hostDeclarations?.get(f)?.properties&&y();continue}let h=f.activate(this.activationContext(r,n,f,c));if(rt(h))throw h.then(g=>g.dispose()).catch(()=>{}),new Error(`Module '${f.name}' requires runAsync for activation`);d.push(h),this.bindModule(f,h,r,i),Ke(n.signal)}m=this.executeSync(e,n,r,i,c),n.signal?.aborted&&(m={...m,success:!1,diagnostics:m.diagnostics.some(f=>f.severity==="error"&&f.message==="Execution aborted")?m.diagnostics:[...m.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(f){Mt(c,f),m={...this.moduleFailure(f,r,n),errors:[...c.errors]}}ne(n)?.capture(m);let p=c.errors.length;this.collectModuleErrors(d,m,n.recoveryProbe!==void 0),ne(n)?.capture(m);for(let f of d.reverse())try{let h=ne(n)?ne(n).dispose(f):f.dispose();if(rt(h))throw h.catch(()=>{}),new Error("Async disposal requires runAsync");ne(n)?.check()}catch(h){let g=ne(n);g&&!g.truncation&&(g.failure??={site:g.lastSite,message:h instanceof Error?h.message:String(h),untrusted:g.tainted}),this.cleanupWarning(h,m)}return m.errors=[...m.errors??[],...c.errors.slice(p)],this.lastRecordedErrors=[...m.errors],m}finally{c.finished=!0,u()}}async runPhaseAsync(e,n={}){Yr(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?Kr(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(ne(n)&&(!s.ast||s.diagnostics.some(m=>m.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};ne(n)?.start(),n={...n,propertyStore:n.propertyStore??new el(n.hostContext?.cwd??process.cwd(),n.hostContext?.env??process.env)};let i=n.propertyStore;n.propertyOverlay&&i.setOverlay(n.propertyOverlay);let o={async:!0,functions:new Map(this.hostFunctions),globals:ne(n)?new Map(tn([...this.initialGlobals])):new Map(this.initialGlobals),properties:i};o.functions.get("which")?.[Be]&&o.functions.set("which",{...o.functions.get("which"),fn:m=>Td(m,n.hostContext?.cwd??process.cwd(),ne(n)?.environment??n.hostContext?.env??process.env,n.hostContext?.platform??n.platform??process.platform)}),o.globals.set("PROPS",i.view()),o.globals.set("Directory",i.get("Directory")),o.globals.set("NonInteractive",i.get("NonInteractive"));let a=ne(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new eo(()=>{let m=a.prepareProperties();return rt(m)?m.then(()=>a.propertyView):a.propertyView}))),o.globals.set("RESUMEPOINT",null);let c={expand:(m,p={})=>{if(!p||typeof p!="object"||Array.isArray(p)||![Object.prototype,null].includes(Object.getPrototypeOf(p)))throw Error("expand: vars must be a map");let f=o.globals.get("ARGV")??[];return Ua(m,h=>h.kind==="property"?i.get(h.key):h.kind==="argument"?Array.isArray(f)&&Object.hasOwn(f,h.index)?f[h.index]:void 0:Object.hasOwn(p,h.name)?wt(p,h.name):void 0,kd)},get_property:(m,...p)=>i.get(m,...p),has_property:m=>i.has(m),get_properties:m=>i.copy(m),set_property:(m,p)=>i.set(m,p)};for(let[m,p]of Object.entries(c))o.functions.set(m,{...o.functions.get(m),fn:ne(n)&&m!=="set_property"?(...f)=>{let g=m!=="expand"||typeof f[0]=="string"&&Ji(f[0]).some(y=>typeof y!="string"&&y.kind==="property")?ne(n).prepareProperties(m==="expand"?void 0:f[0]):void 0;return rt(g)?g.then(()=>p(...f)):p(...f)}:p});if(!s.ast||s.diagnostics.some(m=>m.severity==="error"))return this.executeAsync(e,n,s,o);let u=Ki(n.resumepoint,n.recoveryProbe);o.readonlyRun=u;let d=Jy(u,n.signal);try{let m=[],p;try{Ke(n.signal);for(let h of s.hostModules??[]){if(this.builtinProviders.has(h.name)||h.nativeNamespace||ne(n)){let y,b,_=()=>y??=Promise.resolve().then(async()=>{Ke(n.signal);let v=await h.activate(this.activationContext(s,n,h,u));if(!v||typeof v.dispose!="function")throw new Error(`Module '${h.name}' did not return a disposable`);if(ne(n)?.sealed){try{await v.dispose()}catch{}throw new Jt("Dry pass finished")}return b=v,m.push(v),ne(n)?.own(v),this.bindModule(h,v,s,o),Ke(n.signal),v});h.nativeNamespace&&(o.nativeImports??=new Map,o.nativeImports.set(h.name,_)),this.installBuiltinStubs(h,s,o,v=>async(...E)=>{let I=await _();return ne(n)?.check(),o.functions.get(v).fn(...E)},async v=>(await _(),o.globals.get(v))),ne(n)&&s.hostDeclarations?.get(h)?.properties&&(ne(n).propertyLoads.push(_),i.addSource(h.name,()=>{if(!b?.loadProperties)throw Error("Provider properties unavailable");return b.loadProperties()},s.hostDeclarations.get(h).properties.known)),ne(n)||s.usedProperties&&s.hostDeclarations?.get(h)?.properties&&await _();continue}let g=await h.activate(this.activationContext(s,n,h,u));m.push(g),this.bindModule(h,g,s,o),Ke(n.signal)}p=await this.executeAsync(e,n,s,o,u),n.signal?.aborted&&(p={...p,success:!1,diagnostics:p.diagnostics.some(h=>h.severity==="error"&&h.message==="Execution aborted")?p.diagnostics:[...p.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(h){Mt(u,h),p={...this.moduleFailure(h,s,n),errors:[...u.errors]}}ne(n)?.capture(p);let f=u.errors.length;this.collectModuleErrors(m,p,n.recoveryProbe!==void 0),ne(n)?.capture(p);for(let h of m.reverse())try{let g=ne(n)?ne(n).dispose(h):h.dispose();ne(n)?await ne(n).wait(g):await g}catch(g){let y=ne(n);y&&!y.truncation&&(y.failure??={site:y.lastSite,message:g instanceof Error?g.message:String(g),untrusted:y.tainted}),this.cleanupWarning(g,p)}return p.errors=[...p.errors??[],...u.errors.slice(f)],this.lastRecordedErrors=[...p.errors],p}finally{u.finished=!0,d()}}executeSync(e,n,r,s,i){let o=[],{ast:a,diagnostics:l,hasConcurrency:c}=r;if(l.filter(h=>h.severity==="error").length>0||!a)return this.outputLogs=o,{success:!1,diagnostics:l,output:o};if(c)return this.outputLogs=o,{success:!1,diagnostics:[...l,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:n.file}],output:o};let d=i??Ki(n.resumepoint,n.recoveryProbe),m,p,f=n.trace&&!ne(n)?new Gi(n.trace):void 0;try{m=new sl(s.functions,y=>{o.push(y),f?.output(y+`
|
|
416
|
-
`),n.stdout?.(y)},!1,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,ne(n),n.noPreflight,s.nativeImports),m.childEngineFactory=y=>this.createChildEngine(y),m.compileOptions=n,m.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},m.warningDiagnostics=l,m.abortSignal=n.signal,m.recoverScopedReads=r.recoverScopedReads??new WeakMap,m.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,p=this.trackResourceRun(m.resources),f&&(m.tracer=f,f.begin(n.file??"<main>",e,s.globals));let h;try{h=m.evaluateProgram(a)}catch(y){throw f&&(!y?.isControlFlow&&y?.name!=="LMScriptExit"&&f.error(y),f.end(y instanceof dt||y?.name==="LMScriptExit"?y.exitCode??0:1)),y}f?.end(0),this.outputLogs=[...o]
|
|
417
|
-
`),n.stdout?.(g)},!0,s.globals,n.stderr,this.promptHumanConfig,u,n.hostContext?.platform??n.platform??process.platform,ne(n),n.noPreflight,s.nativeImports),d.childEngineFactory=g=>this.createChildEngine(g),d.compileOptions=n,d.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},d.warningDiagnostics=l,d.abortSignal=n.signal,d.recoverScopedReads=r.recoverScopedReads??new WeakMap,d.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,m=this.trackResourceRun(d.resources),p&&(d.tracer=p,p.begin(n.file??"<main>",e,s.globals));let f;try{f=await d.evaluateProgramAsync(a)}catch(g){throw p&&(!g?.isControlFlow&&g?.name!=="LMScriptExit"&&p.error(g),p.end(g instanceof dt||g?.name==="LMScriptExit"?g.exitCode??0:1)),g}p?.end(0),this.outputLogs=[...o]
|
|
416
|
+
`),n.stdout?.(y)},!1,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,ne(n),n.noPreflight,s.nativeImports),m.childEngineFactory=y=>this.createChildEngine(y),m.compileOptions=n,m.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},m.warningDiagnostics=l,m.abortSignal=n.signal,m.recoverScopedReads=r.recoverScopedReads??new WeakMap,m.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,p=this.trackResourceRun(m.resources),f&&(m.tracer=f,f.begin(n.file??"<main>",e,s.globals));let h;try{h=m.evaluateProgram(a)}catch(y){throw f&&(!y?.isControlFlow&&y?.name!=="LMScriptExit"&&f.error(y),f.end(y instanceof dt||y?.name==="LMScriptExit"?y.exitCode??0:1)),y}let g=m.getRecordedErrors();return f?.end(g.length?1:0),this.outputLogs=[...o],this.lastRecordedErrors=g,{success:!0,value:h,diagnostics:l,output:o,errors:g,resourceRun:p}}catch(h){Mt(d,h);let g=[...d.errors];if(this.lastRecordedErrors=g,h instanceof dt||h?.name==="LMScriptExit"||h?.isControlFlow){this.outputLogs=[...o];let v=typeof h.exitCode=="number"?h.exitCode:0;return{success:v===0,value:v,exitCode:v,diagnostics:l,output:o,errors:g,resourceRun:p}}let y=h instanceof D?h.line:1,b=h instanceof D?h.column:1,_=h instanceof D&&h.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...l,{message:h?.message||String(h),line:y,column:b,severity:"error",file:_}],output:o,errors:g,resourceRun:p}}}async executeAsync(e,n,r,s,i){let o=[],{ast:a}=r,l=[...r.diagnostics];if(l.filter(f=>f.severity==="error").length>0||!a)return this.outputLogs=o,this.lastRecordedErrors=[],{success:!1,diagnostics:l,output:o,errors:[]};let u=i??Ki(n.resumepoint,n.recoveryProbe),d,m,p=n.trace&&!ne(n)?new Gi(n.trace):void 0;try{d=new sl(s.functions,g=>{o.push(g),p?.output(g+`
|
|
417
|
+
`),n.stdout?.(g)},!0,s.globals,n.stderr,this.promptHumanConfig,u,n.hostContext?.platform??n.platform??process.platform,ne(n),n.noPreflight,s.nativeImports),d.childEngineFactory=g=>this.createChildEngine(g),d.compileOptions=n,d.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},d.warningDiagnostics=l,d.abortSignal=n.signal,d.recoverScopedReads=r.recoverScopedReads??new WeakMap,d.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,m=this.trackResourceRun(d.resources),p&&(d.tracer=p,p.begin(n.file??"<main>",e,s.globals));let f;try{f=await d.evaluateProgramAsync(a)}catch(g){throw p&&(!g?.isControlFlow&&g?.name!=="LMScriptExit"&&p.error(g),p.end(g instanceof dt||g?.name==="LMScriptExit"?g.exitCode??0:1)),g}let h=d.getRecordedErrors();return p?.end(h.length?1:0),this.outputLogs=[...o],this.lastRecordedErrors=h,{success:!0,value:f,diagnostics:l,output:o,errors:h,resourceRun:m}}catch(f){Mt(u,f);let h=[...u.errors];if(this.lastRecordedErrors=h,f instanceof dt||f?.name==="LMScriptExit"||f?.isControlFlow){this.outputLogs=[...o];let _=typeof f.exitCode=="number"?f.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:l,output:o,errors:h,resourceRun:m}}let g=f instanceof D?f.line:1,y=f instanceof D?f.column:1,b=f instanceof D&&f.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...l,{message:f?.message||String(f),line:g,column:y,severity:"error",file:b}],output:o,errors:h,resourceRun:m}}}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??b_(n.returnType),readonly:n.readonly,dryControl:n.dryControl,signature:n.signature}):void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};Ad=ie.basename(Jd(import.meta.url));(Ad==="lmscript.ts"||Ad==="lmscript.js"||Ad==="lmscript")&&process.argv[1]&&U.existsSync(process.argv[1])&&U.realpathSync(Jd(import.meta.url))===U.realpathSync(ie.resolve(process.argv[1]))&&nO()});function rO(t,e,n){let r=en(t,n,e);if(!r.publicParams.length)return r.publicArity===void 0?void 0:t+"()";let s=r.publicParams.map(i=>i.rest?"..."+i.name:i.optional?"["+i.name+"]":i.name);return t+"("+s.join(", ")+")"}function sO(t,e,n){return e===n?"[dryrun: boolean"+(t.default===!0?" = true":"")+"] (injected/reserved)":t.rest?"..."+t.name:t.optional?"["+t.name+(t.default===!0?" = true":t.default===!1?" = false":"")+"]":t.name}function nm(t){let e=en(t.name,t.arity,t.params,t.returnType,t.doc),n=e.dryrunIndex===void 0&&t.doc?.signature?t.doc.signature:rO(t.name,t.params,t.arity),r=e.returnType,s=t.doc?.parameters?.filter(i=>i.name!=="dryrun");return{...t.doc??{name:t.name,module:"core",category:"Host Functions",description:"Declared host function"},signature:n??t.name+"(...)",...s?{parameters:s}:{},...r&&!t.doc?.returns?{returns:{type:r,description:"Declared result type"}}:r&&t.doc?.returns?{returns:{...t.doc.returns,type:r}}:{}}}function iO(t,e){let n=t.getFunctionMetadata(e);if(n)return nm({name:e,arity:n.arity,params:n.params,returnType:n.returnType??void 0,doc:t.getFunctionDoc(e)})}function I_(t,e,n){let r=new Set(["core",...t.getBuiltinProviders().map(l=>l.name)]),s=l=>(r.has(l)?"Built-in: ":"Module: ")+l,i=new Map;for(let l of t.getFunctionDocs())(l.category==="Language Constructs"||!t.scanAndCheck(l.name+";").diagnostics.some(c=>c.severity==="error"))&&i.set(l.name,l);for(let l of t.getRegisteredFunctions()){let c=t.getFunctionMetadata(l);i.set(l,iO(t,l)??{name:l,module:"core",category:"Core Functions",description:c.description??"Core function",signature:l+"(...)"})}for(let l of e)for(let c of l.declarations.functions)i.set(c.name,nm({...c,doc:c.doc??{name:c.name,module:l.name,category:"Host Functions",description:"Declared by "+l.name,signature:c.name+"(...)"}}));if(n==="cmd")return`system COMMAND executes argv; cmd COMMAND returns argv. One command per source line; put closing braces on the next line.
|
|
418
418
|
Example (run each statement on its own line):
|
|
419
419
|
args = cmd program a=" " b="adsfa"
|
|
420
420
|
assert(json_stringify(args) == '["program","a= ","b=adsfa"]');
|
package/dist/lmbee.js
CHANGED
|
@@ -190,7 +190,7 @@ ${$}`:""}${d}${g}`,onSent:A}}let I=N.description.trim();return{message:`Continue
|
|
|
190
190
|
|
|
191
191
|
${I}`:""}
|
|
192
192
|
|
|
193
|
-
(${b.length-1} other ready task(s) also available: \`lmauto tasks list --owner-team <path> --owner-alias <alias> --status todo\`.)`+d+g,onSent:A}}var ge={idleThresholdMs:45*6e4,cooldownMs:30*6e4};function tR(e,t){return t.running.some(r=>Cn(e,r.from_identity))}function pn(e,t){return t.dead.some(r=>Cn(e,r.target))&&!He(e,t)}function ml(e){if(e.isCurrentlyActive)return!1;let t=!e.hasInFlightWorker,r=e.timeSinceLastNudgeMs===null||e.timeSinceLastNudgeMs>e.config.cooldownMs;if(e.isDeadReclaimable)return t&&r;let n=!e.isCoordinator&&e.progressStatus==="UNKNOWN"&&(e.progressAgeMs===null||e.progressAgeMs>=e.config.idleThresholdMs),o=!e.heavyLockMayBeHeldByThisTeam&&e.hasStalePersistentInProgressWork;return t&&r&&(e.neverDispatched||n||o)}function fl(e,t,r,n){let o;try{o=Q(t)}catch{return!1}let s=Ne(e,o,t.leadAlias);if(s===null)return!1;let i=new Map(s.entities.map(a=>[a.id,a]));return s.entities.some(a=>(a.kind==="task"||a.kind==="subtask")&&de(a.status)==="in-progress"&&!rr(e,a,i)&&n-Date.parse(a.updated_at)>=r&&!pl(a,n))}function pl(e,t){return e.hold_until!==null&&Date.parse(e.hold_until)>t}function hl(e,t){if(je(e,t.name)!==null||pp(e,t.name))return!1;let r;try{r=Q(t)}catch{return!0}return Ne(e,r,t.leadAlias)===null}function rR(e){return ml({...e,config:{...e.config,idleThresholdMs:0}})}function Cp(e){return`last_nudged:${e}`}function gl(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(Cp(t))?.v??null}function Wo(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Cp(t),r)}function Op(e,t,r,n,o,s,i){if(je(e,t.name)?.status==="BLOCKED")return null;let c=hl(e,t),l=s?.progress_changed_ts==null?null:o-Date.parse(s.progress_changed_ts),u=gl(e,t.name),d=u===null?null:o-Date.parse(u);return{isCurrentlyActive:He(t,r),hasInFlightWorker:tR(t,r),neverDispatched:c,progressStatus:s?.progress_status??null,progressAgeMs:l,isDeadReclaimable:pn(t,r),hasStalePersistentInProgressWork:fl(e,t,n.idleThresholdMs,o),timeSinceLastNudgeMs:d,config:n,isCoordinator:t.coordinator===!0,heavyLockMayBeHeldByThisTeam:i.held&&(i.holder===null||i.holder.holder===t.name)}}function Dp(e,t,r,n,o,s,i){let a=Op(e,t,r,o,s,i,n);return a!==null&&ml(a)}async function _l(e,t,r,n,o=ge,s=Date.now()){let i=await Dc(e,t,t.name,s);return Dp(e,t,r,n,o,s,i)}function wl(e,t,r,n,o=ge,s=Date.now()){return Dp(e,t,r,n,o,s,se(e,t.name))}async function Bn(e,t,r,n,o=ge,s=Date.now(),i={}){let a=[];for(let c of t){if(!c.autoNudge||se(e,c.name)?.confirmed_done_ts)continue;(i.readOnly?wl(e,c,r,n,o,s):await _l(e,c,r,n,o,s))&&!se(e,c.name)?.confirmed_done_ts&&a.push(c.name)}return a}async function Mp(e,t,r,n,o=ge,s=Date.now()){let i=[],a=[];for(let c of t){if(!c.autoNudge||se(e,c.name)?.confirmed_done_ts)continue;let l=await Dc(e,c,c.name,s);if(se(e,c.name)?.confirmed_done_ts)continue;let u=Op(e,c,r,o,s,l,n);u!==null&&(ml(u)&&i.push(c.name),rR(u)&&a.push(c.name))}return{stalled:i,continueEligible:a}}import{existsSync as Pp,readFileSync as Up}from"node:fs";import{dirname as El,join as Fp}from"node:path";import{fileURLToPath as qp}from"node:url";var yl={sha:"unknown",dirty:!0,builtAt:"unknown"};function nR(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha=="string"&&typeof t.dirty=="boolean"&&typeof t.builtAt=="string"}function jp(){let e=El(qp(import.meta.url));for(let t=0;t<5;t+=1){let r=Fp(e,"package.json");if(Pp(r))try{let n=JSON.parse(Up(r,"utf8"));if(n&&typeof n=="object"&&typeof n.version=="string")return n.version}catch{}e=El(e)}return"unknown"}function bl(){let e=Fp(El(qp(import.meta.url)),"..","build-info.json");if(!Pp(e))return yl;try{let t=JSON.parse(Up(e,"utf8"));return nR(t)?t:yl}catch{return yl}}var oR="https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod";function Ot(e){return(e.LMCTL_LMMAIL_API_URL?.trim()||e.LMMAIL_API_URL?.trim()||oR).replace(/\/+$/,"")}import{randomUUID as lR}from"node:crypto";import{spawn as aR}from"node:child_process";var Hp={name:"@lmctl-ai/mcp-client",version:"0.1.0",private:!0,type:"module",description:"Stateless HTTP MCP client",bin:{mcp:"./bin/mcp"},files:["bin","src","README.md"],scripts:{build:"node --check src/cli.mjs",test:"node --test --test-concurrency=2 tests/*.test.mjs"},engines:{node:">=24.15.0"},dependencies:{"smol-toml":"1.9.0"},exports:{".":{types:"./src/index.d.mts",import:"./src/index.mjs"}}};function Bp(e,t,r){let n=new TextDecoder("utf-8",{fatal:!0}),o=[],s=!1,i=l=>{s||(s=!0,r(l))},a=l=>{if(!s)try{let u=n.decode(l,{stream:!0}),d=0,m;for(;(m=u.indexOf(`
|
|
193
|
+
(${b.length-1} other ready task(s) also available: \`lmauto tasks list --owner-team <path> --owner-alias <alias> --status todo\`.)`+d+g,onSent:A}}var ge={idleThresholdMs:45*6e4,cooldownMs:30*6e4};function tR(e,t){return t.running.some(r=>Cn(e,r.from_identity))}function pn(e,t){return t.dead.some(r=>Cn(e,r.target))&&!He(e,t)}function ml(e){if(e.isCurrentlyActive)return!1;let t=!e.hasInFlightWorker,r=e.timeSinceLastNudgeMs===null||e.timeSinceLastNudgeMs>e.config.cooldownMs;if(e.isDeadReclaimable)return t&&r;let n=!e.isCoordinator&&e.progressStatus==="UNKNOWN"&&(e.progressAgeMs===null||e.progressAgeMs>=e.config.idleThresholdMs),o=!e.heavyLockMayBeHeldByThisTeam&&e.hasStalePersistentInProgressWork;return t&&r&&(e.neverDispatched||n||o)}function fl(e,t,r,n){let o;try{o=Q(t)}catch{return!1}let s=Ne(e,o,t.leadAlias);if(s===null)return!1;let i=new Map(s.entities.map(a=>[a.id,a]));return s.entities.some(a=>(a.kind==="task"||a.kind==="subtask")&&de(a.status)==="in-progress"&&!rr(e,a,i)&&n-Date.parse(a.updated_at)>=r&&!pl(a,n))}function pl(e,t){return e.hold_until!==null&&Date.parse(e.hold_until)>t}function hl(e,t){if(je(e,t.name)!==null||pp(e,t.name))return!1;let r;try{r=Q(t)}catch{return!0}return Ne(e,r,t.leadAlias)===null}function rR(e){return ml({...e,config:{...e.config,idleThresholdMs:0}})}function Cp(e){return`last_nudged:${e}`}function gl(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(Cp(t))?.v??null}function Wo(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Cp(t),r)}function Op(e,t,r,n,o,s,i){if(je(e,t.name)?.status==="BLOCKED")return null;let c=hl(e,t),l=s?.progress_changed_ts==null?null:o-Date.parse(s.progress_changed_ts),u=gl(e,t.name),d=u===null?null:o-Date.parse(u);return{isCurrentlyActive:He(t,r),hasInFlightWorker:tR(t,r),neverDispatched:c,progressStatus:s?.progress_status??null,progressAgeMs:l,isDeadReclaimable:pn(t,r),hasStalePersistentInProgressWork:fl(e,t,n.idleThresholdMs,o),timeSinceLastNudgeMs:d,config:n,isCoordinator:t.coordinator===!0,heavyLockMayBeHeldByThisTeam:i.held&&(i.holder===null||i.holder.holder===t.name)}}function Dp(e,t,r,n,o,s,i){let a=Op(e,t,r,o,s,i,n);return a!==null&&ml(a)}async function _l(e,t,r,n,o=ge,s=Date.now()){let i=await Dc(e,t,t.name,s);return Dp(e,t,r,n,o,s,i)}function wl(e,t,r,n,o=ge,s=Date.now()){return Dp(e,t,r,n,o,s,se(e,t.name))}async function Bn(e,t,r,n,o=ge,s=Date.now(),i={}){let a=[];for(let c of t){if(!c.autoNudge||se(e,c.name)?.confirmed_done_ts)continue;(i.readOnly?wl(e,c,r,n,o,s):await _l(e,c,r,n,o,s))&&!se(e,c.name)?.confirmed_done_ts&&a.push(c.name)}return a}async function Mp(e,t,r,n,o=ge,s=Date.now()){let i=[],a=[];for(let c of t){if(!c.autoNudge||se(e,c.name)?.confirmed_done_ts)continue;let l=await Dc(e,c,c.name,s);if(se(e,c.name)?.confirmed_done_ts)continue;let u=Op(e,c,r,o,s,l,n);u!==null&&(ml(u)&&i.push(c.name),rR(u)&&a.push(c.name))}return{stalled:i,continueEligible:a}}import{existsSync as Pp,readFileSync as Up}from"node:fs";import{dirname as El,join as Fp}from"node:path";import{fileURLToPath as qp}from"node:url";var yl={sha:"unknown",dirty:!0,builtAt:"unknown"};function nR(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha=="string"&&typeof t.dirty=="boolean"&&typeof t.builtAt=="string"}function jp(){let e=El(qp(import.meta.url));for(let t=0;t<5;t+=1){let r=Fp(e,"package.json");if(Pp(r))try{let n=JSON.parse(Up(r,"utf8"));if(n&&typeof n=="object"&&typeof n.version=="string")return n.version}catch{}e=El(e)}return"unknown"}function bl(){let e=Fp(El(qp(import.meta.url)),"..","build-info.json");if(!Pp(e))return yl;try{let t=JSON.parse(Up(e,"utf8"));return nR(t)?t:yl}catch{return yl}}var oR="https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod";function Ot(e){return(e.LMCTL_LMMAIL_API_URL?.trim()||e.LMMAIL_API_URL?.trim()||oR).replace(/\/+$/,"")}import{randomUUID as lR}from"node:crypto";import{spawn as aR}from"node:child_process";var Hp={name:"@lmctl-ai/mcp-client",version:"0.1.0",private:!0,type:"module",description:"Stateless HTTP MCP client",bin:{mcp:"./bin/mcp"},files:["bin","src","mcp.cli.schema.v1.json","README.md"],scripts:{build:"node --check src/cli.mjs",test:"node --test --test-concurrency=2 tests/*.test.mjs"},engines:{node:">=24.15.0"},dependencies:{"smol-toml":"1.9.0"},exports:{".":{types:"./src/index.d.mts",import:"./src/index.mjs"},"./mcp.cli.schema.v1.json":"./mcp.cli.schema.v1.json"}};function Bp(e,t,r){let n=new TextDecoder("utf-8",{fatal:!0}),o=[],s=!1,i=l=>{s||(s=!0,r(l))},a=l=>{if(!s)try{let u=n.decode(l,{stream:!0}),d=0,m;for(;(m=u.indexOf(`
|
|
194
194
|
`,d))>=0;){let p=o.join("")+u.slice(d,m);o=[],d=m+1,t(JSON.parse(p))}let f=u.slice(d);f&&o.push(f)}catch(u){i(u)}},c=()=>{try{let l=n.decode();l&&o.push(l),o.length&&i(new Error("Incomplete newline JSON frame"))}catch(l){i(l)}};return e.on("data",a),e.on("end",c),e.on("error",i),()=>{e.off("data",a),e.off("end",c),e.off("error",i),s=!0,o=[]}}function Ii(e,t){e.write(JSON.stringify(t)+`
|
|
195
195
|
`)}var iR=new Set(["invalid_argument","not_found","busy","service_unavailable","stopped","transport","protocol","unsupported","tool_error","outcome_unknown","events_lost","internal"]);function Fr(e,t=null,r=null,n=null,o="completed"){return t&&!iR.has(t)&&(t="internal"),{status:t==="busy"?"busy":t?"error":"ok",code:t,error:r,connection:e.connection??null,service_epoch:e.service_epoch??null,connection_epoch:e.connection_epoch??null,connection_state:e.connection_state??null,outcome:o,result:n}}var ct=class extends Error{constructor(t,r,n=null,o="not_sent"){super(r),this.code=t,this.value=n,this.outcome=o}};var cR=Hp.version,Wp="2025-11-25",Li=class{constructor(t,r=()=>{},n=()=>{}){this.config=t,this.onNotification=r,this.onDisconnect=n,this.pending=new Map,this.nextId=0,this.connected=!1}async open(t=()=>{}){let r=this.child=aR(this.config.command,this.config.args,{cwd:this.config.cwd,env:this.config.env,shell:!1,stdio:["pipe","pipe","pipe"]});this.exited=new Promise(o=>r.once("close",()=>{this.disconnect(new Error("MCP server exited")),o()})),r.on("error",o=>this.disconnect(o)),r.stdin.on("error",o=>this.disconnect(o)),r.stderr.resume(),Bp(r.stdout,o=>this.message(o),o=>this.disconnect(o)),r.stdout.once("end",()=>this.disconnect(new Error("MCP stdout ended"))),await new Promise((o,s)=>{r.once("spawn",o),r.once("error",i=>s(new ct("transport",i.message)))}),this.connected=!0,await t(r.pid);let n=await this.request("initialize",{protocolVersion:Wp,capabilities:{},clientInfo:{name:"mcp-client",version:cR}});if(n?.protocolVersion!==Wp||!n.capabilities||typeof n.capabilities!="object"||Array.isArray(n.capabilities)||!n.serverInfo||typeof n.serverInfo.name!="string"||typeof n.serverInfo.version!="string")throw new ct("protocol","MCP server did not negotiate the 2025-11-25 profile",n);return this.capabilities=n.capabilities,Ii(r.stdin,{jsonrpc:"2.0",method:"notifications/initialized"}),n}request(t,r){if(!this.connected)return Promise.reject(new ct("transport","MCP server is disconnected"));let n=++this.nextId;return new Promise((o,s)=>{let i={resolve:o,reject:s,method:t,sent:!1};this.pending.set(n,i);try{i.sent=!0,Ii(this.child.stdin,{jsonrpc:"2.0",id:n,method:t,params:r})}catch(a){this.pending.delete(n),s(new ct(i.sent&&i.method!=="initialize"?"outcome_unknown":"transport",a.message,null,i.sent&&i.method!=="initialize"?"unknown":"not_sent"))}})}message(t){if(!t||typeof t!="object"||t.jsonrpc!=="2.0"){this.disconnect(new Error("Invalid MCP JSON-RPC message"));return}if(typeof t.method=="string"){Object.hasOwn(t,"id")?Ii(this.child.stdin,t.method==="ping"?{jsonrpc:"2.0",id:t.id,result:{}}:{jsonrpc:"2.0",id:t.id,error:{code:-32601,message:"Unsupported server request: "+t.method}}):this.onNotification(t.method,t.params??{});return}let r=this.pending.get(t.id);r&&(this.pending.delete(t.id),Object.hasOwn(t,"error")?r.reject(new ct("protocol",t.error?.message??"MCP JSON-RPC error",{error:t.error},"completed")):Object.hasOwn(t,"result")?r.resolve(t.result):r.reject(new ct("protocol","MCP response has neither result nor error",t,"unknown")))}disconnect(t){if(!(!this.connected&&this.pending.size===0)){this.connected=!1;for(let r of this.pending.values())r.reject(new ct(r.sent&&r.method!=="initialize"?"outcome_unknown":"transport",t.message,null,r.sent&&r.method!=="initialize"?"unknown":"not_sent"));this.pending.clear(),this.onDisconnect(t)}}async close(){this.child&&(this.child.stdin.end(),await this.exited)}};var Ci=class{constructor(t){this.epoch=t,this.events=[]}push(t,r){this.events.push({sequence:this.events.length+1,method:t,params:r})}read(t){let r=0;if(t!==void 0){if(typeof t!="string"||!t.startsWith(this.epoch+":"))throw new ct("events_lost","Event cursor has a different connection epoch");let n=t.slice(this.epoch.length+1);if(r=Number(n),!/^\d+$/.test(n)||!Number.isSafeInteger(r)||r>this.events.length)throw new ct("invalid_argument","Invalid event cursor")}return{events:this.events.slice(r),cursor:this.epoch+":"+this.events.length}}};var uR={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)},dR=new Set(["call","list_tools","status","events","close"]),Go=class{constructor({connections:t={},clock:r=uR}={}){this.connections=Object.fromEntries(Object.entries(t).map(([n,o])=>[n,{...o,args:[...o.args??[]],env:{...process.env,...o.env},idle_ms:o.idle_ms??3e5}])),this.clock=r,this.service_epoch=lR(),this.entries=new Map,this.nextEpoch=0,this.stopping=!1}context(t,r,n){return{connection:t,service_epoch:this.service_epoch,connection_epoch:r?.epoch??null,connection_state:n??null}}async request(t){let{connection:r,operation:n,params:o={}}=t??{},s=()=>this.context(r,this.entries.get(r)),i=(u,d)=>Fr(s(),u,d,null,"not_sent");if(typeof r!="string"||!dR.has(n)||!o||typeof o!="object"||Array.isArray(o))return i("invalid_argument","Expected connection, operation and a params object");let a=n==="call"?["tool","arguments"]:["list_tools","events"].includes(n)?["cursor"]:[];if(Object.keys(o).some(u=>!a.includes(u)))return i("invalid_argument","Unknown operation parameter");if(n==="call"&&(typeof o.tool!="string"||!o.tool||o.arguments!==void 0&&(!o.arguments||typeof o.arguments!="object"||Array.isArray(o.arguments))))return i("invalid_argument","call requires a tool string and argument map");if(this.stopping)return i("stopped","MCP service is shutting down");if(!Object.hasOwn(this.connections,r))return i("not_found","Unknown MCP connection: "+r);let c=this.entries.get(r);if(n==="status")return Fr(s(),null,null,{phase:c?.phase??"absent",active:c?.active??!1});if(n==="events"){if(!c)return i("not_found","MCP connection is not open");try{return Fr(s(),null,null,c.events.read(o.cursor))}catch(u){return i(u.code,u.message)}}if(n==="close"){if(!c)return Fr(s());if(c.active||c.closing||c.phase==="closing")return i("busy","MCP connection has active work");let u=this.context(r,c);return await this.closeEntry(r,c),Fr(u)}if(c?.active||c?.closing||c?.phase==="closing")return i("busy","MCP connection has active work");let l=c?c.transport?.connected?"reused":"reinitialized":"new";return c||(c={phase:"opening",active:!1,epoch:0},this.entries.set(r,c)),c.active=!0,this.cancelIdle(c),c.work=this.perform(r,c,n,o,l),c.work}async perform(t,r,n,o,s){try{if(!r.transport?.connected){r.transport&&await r.transport.close(),r.phase="opening",r.epoch=++this.nextEpoch,r.events=new Ci(this.service_epoch+"/"+t+"/"+r.epoch);let a=new Li(this.connections[t],(c,l)=>r.events.push(c,l),()=>{r.transport!==a||r.closing||(r.phase="disconnected")});r.transport=a;try{await r.transport.open()}catch(c){throw await r.transport.close(),this.entries.get(t)===r&&this.entries.delete(t),c}}if(r.phase="active",!r.transport.capabilities.tools)throw new ct("unsupported","MCP server does not advertise tools");let i=await r.transport.request(n==="call"?"tools/call":"tools/list",n==="call"?{name:o.tool,arguments:o.arguments??{}}:{...o.cursor!==void 0?{cursor:o.cursor}:{}});return Fr(this.context(t,r,s),i?.isError?"tool_error":null,i?.isError?"MCP tool returned isError":null,i)}catch(i){return Fr(this.context(t,r,s),i.code??"internal",i.message,i.value??null,i.outcome??"not_sent")}finally{r.active=!1,r.closing||(r.phase=r.transport?.connected?"ready":"disconnected",this.stopping||this.armIdle(t,r))}}cancelIdle(t){t.idle!==void 0&&(this.clock.clearTimeout(t.idle),t.idle=void 0)}armIdle(t,r){if(this.cancelIdle(r),this.entries.get(t)!==r)return;let n=this.connections[t].idle_ms;n>0&&!r.active&&!r.closing&&["ready","disconnected"].includes(r.phase)&&(r.idle=this.clock.setTimeout(()=>{!r.active&&!r.closing&&["ready","disconnected"].includes(r.phase)&&this.closeEntry(t,r)},n))}closeEntry(t,r){return r.closing||(this.cancelIdle(r),r.phase="closing",r.closing=(async()=>{r.active&&await r.work,r.phase="closing",await r.transport?.close(),r.phase="closed",this.entries.get(t)===r&&this.entries.delete(t)})()),r.closing}shutdown(){return this.shutdownPromise?this.shutdownPromise:(this.stopping=!0,this.shutdownPromise=Promise.all([...this.entries].map(([t,r])=>this.closeEntry(t,r))).then(()=>{}),this.shutdownPromise)}cancel(){this.stopping=!0;for(let t of this.entries.values())this.cancelIdle(t),t.transport?.child?.kill("SIGTERM")}};import{readFileSync as wR}from"node:fs";import{dirname as Yp,resolve as Qp}from"node:path";function mR(e,t){let r=e.slice(0,t).split(/\r?\n/);return[r.length,r.pop().length+1]}function fR(e,t,r){let n=e.split(/\r?\n/),o="",s=(Math.log10(t+1)|0)+1;for(let i=t-1;i<=t+1;i++){let a=n[i-1];a&&(o+=i.toString().padEnd(s," "),o+=": ",o+=a,o+=`
|
|
196
196
|
`,i===t&&(o+=" ".repeat(s+r+2),o+=`^
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lmctl-ai/lmctl",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.254",
|
|
4
4
|
"description": "A provider-agnostic control plane for teams of AI coding agents — across providers, with independent review and durable memory.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"homepage": "https://lmctl.com",
|