@lmctl-ai/lmctl 0.2.317 → 0.2.319
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 +85 -84
- package/package.json +1 -1
package/dist/cli/lmscript.js
CHANGED
|
@@ -421,23 +421,24 @@ fn clamp(val, low, high) {
|
|
|
421
421
|
}
|
|
422
422
|
return val;
|
|
423
423
|
}
|
|
424
|
-
`,Am=null;Jn=new WeakMap,No=new WeakMap,hv=["get_property","has_property","get_properties","set_property"];jl=class t{sources=new Map;loaded=!1;path="the registered property source";hint="Define it in the property source";tree={};known=[];overlay;constructor(e,n){this.tree.Directory=e,this.tree.NonInteractive=n.LMCTL_NON_INTERACTIVE==="1"}addSource(e,n,r){this.sources.has(e)||(this.sources.set(e,n),this.known.push(...r))}setOverlay(e){if(this.overlay){if($O(this.overlay,e))return;throw Error("Cannot set a different property overlay on a reused PropertyStore; create a new PropertyStore for each overlay")}if(this.loaded)throw Error("Set the property overlay before loading the store");this.overlay=oi(e)}fork(){let e=new t(this.tree.Directory,{LMCTL_NON_INTERACTIVE:this.tree.NonInteractive?"1":"0"});for(let[n,r]of this.sources)e.sources.set(n,r);e.known.push(...this.known),e.loaded=this.loaded,e.path=this.path,e.hint=this.hint;for(let[n,r]of Object.entries(this.tree))ct(e.tree,n,structuredClone(r));return this.overlay&&(e.overlay=oi(this.overlay)),e}load(e){if(this.loaded)return;let n={},r=[];for(let s of this.sources.values()){let i;try{if(i=s(),!ii(i.properties))throw Error("Property document must be a table in "+i.path);for(let a of["Directory","NonInteractive"])if(Object.hasOwn(i.properties,a))throw Error("Property '"+a+"' is read-only in "+i.path);i={...i,properties:structuredClone(i.properties)}}catch(a){throw Error("Property '"+e+"': "+(a instanceof Error?a.message:String(a)))}this.path=i.path,this.hint=i.hint??"Define it in the property source",r.push(i.path);let o=Um(i.properties,this.known,i.path);for(let[a,l]of Object.entries(o)){if(Object.hasOwn(n,a))throw Error("Property '"+a+"' conflicts with another source in "+i.path);ct(n,a,structuredClone(l))}}if(this.overlay){let s=Um(this.overlay.properties,this.known,this.overlay.path);n=Wv(n,s,r.join(", ")||this.path,this.overlay.path),this.path=r.concat(this.overlay.path).join(", ")}for(let[s,i]of Object.entries(n))ct(this.tree,s,i);this.loaded=!0}find(e,n=!0){let r=$l(jm(e),this.known);n&&!["Directory","NonInteractive"].includes(r.split(".")[0])&&this.load(r);let s=this.tree;for(let i of r.split(".")){if(!s||typeof s!="object"||!Object.hasOwn(s,i))return{found:!1,value:void 0,key:r};s=s[i]}return{found:!0,value:s,key:r}}missing(e){throw Error(`Property '${e}' is not defined in ${this.path}; ${this.hint}`)}get(e,...n){let r=this.find(e);return r.found?Gn(r.value,r.key):n.length?n[0]:this.missing(r.key)}has(e){return this.find(e).found}copy(e=""){if(!e)return this.load("<all>"),Gn(this.tree,"");let n=this.find(e);if(!n.found)return this.missing(n.key);if(!n.value||typeof n.value!="object"||Array.isArray(n.value)||n.value instanceof Date)throw Error(`Property '${n.key}' is not a table; get_properties requires a table`);return Gn(n.value,n.key)}set(e,n){let r=$l(jm(e),this.known);if(["Directory","NonInteractive"].includes(r.split(".")[0]))throw Error(`Property '${r}' is read-only`);let s=Gn(n,r),i=this.find(r),o=this.tree,a=r.split(".");for(let u of a.slice(0,-1)){if(Object.hasOwn(o,u)||ct(o,u,{}),!o[u]||typeof o[u]!="object"||Array.isArray(o[u])||o[u]instanceof Date)throw Error(`Property '${u}' is a value, not a table`);o=o[u]}let l=i.found?Gn(i.value,r):null,c=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)&&!(u instanceof Date);if(i.found&&c(i.value)!==c(s))throw Error(`Property '${r}' cannot change between a table and a value`);return ct(o,a.at(-1),s),l}view(e=""){let n=i=>{let o=e?e+"."+i:i,a=this.find(o);if(!a.found)return this.missing(a.key);if(a.value&&typeof a.value=="object"&&!Array.isArray(a.value)&&!(a.value instanceof Date))return this.view(a.key);let l=Gn(a.value,a.key),c=u=>{if(u&&typeof u=="object"){for(let d of Object.values(u))c(d);Object.freeze(u)}return u};return c(l)},r=()=>{throw Error(`PROPS${e?"."+e:""} is read-only; use set_property`)},s=new Proxy({},{get:(i,o)=>typeof o=="symbol"||o==="then"?void 0:o==="toJSON"?()=>this.copy(e):n(o),ownKeys:()=>(e||this.load("<keys>"),Object.keys(e?this.find(e).value:this.tree)),getOwnPropertyDescriptor:(i,o)=>{if(typeof o!="string")return;!e&&!["Directory","NonInteractive"].includes(o)&&this.load("<keys>");let a=e?this.find(e).value:this.tree;return Object.hasOwn(a,o)?{enumerable:!0,configurable:!0}:void 0},set:r,deleteProperty:r,defineProperty:r,setPrototypeOf:r});return Jn.set(s,n),No.set(s,()=>this.copy(e)),s}};qn=new xv;hL=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;Xn=class{variables=new Set;shadowedGlobals=new Set;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolvingScope(e){return this.variables.has(e)?this:this.parent?.resolvingScope(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}resolveInScope(e){return this.variables.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.resolveInScope(e):!1}},Hm=class{diagnostics=[];hostFunctions=new Map;knownHostReferences=new Map;options;functions=new Map;currentScope=new Xn;loopDepth=0;inFunction=!1;hasConcurrency=!1;usedGlobals=new Set;usedProperties=!1;loadedPackages=new Set;functionPackages=new WeakMap;recoverLabels=new Set;hasRecover=!1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recoverContexts=[];constructor(e,n={}){this.options=n;for(let[r,s]of e.entries())this.hostFunctions.set(r,s),this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.usedGlobals.clear(),this.usedProperties=!1,this.loadedPackages=new Set,this.functionPackages=new WeakMap,this.recoverLabels.clear(),this.hasRecover=!1,this.recoverContexts=[],this.recoverScopedReads=new WeakMap,this.recoverScopedWrites=new WeakMap,this.loopDepth=0,this.inFunction=!1,this.currentScope=new Xn,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,s]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);this.checkRecoverSiblings(e.statements),this.collectKnownHostReferences(e);for(let r of e.statements)r.kind==="FunctionDeclStmt"?this.functionPackages.set(r,new Set(this.loadedPackages)):this.checkStmt(r);let n=this.loadedPackages;for(let r of e.statements)r.kind==="FunctionDeclStmt"&&(this.loadedPackages=this.functionPackages.get(r),this.checkStmt(r));return this.loadedPackages=n,this.diagnostics}collectKnownHostReferences(e){this.knownHostReferences.clear();let n=new Map,r=new Map,s=(a,l)=>{n.set(a,(n.get(a)??0)+1),l&&r.set(a,l)},i=a=>{if(!(!a||typeof a!="object")){if(a.kind==="AssignExpr")s(a.target,a.value);else if(a.kind==="VarDeclStmt")s(a.name,a.initializer);else if(a.kind==="TupleAssignExpr")for(let l of a.targets)s(l);else if(a.kind==="TupleVarDeclStmt")for(let l of a.names)s(l);else if(a.kind==="ForInStmt")s(a.name);else if(a.kind==="FunctionDeclStmt")for(let l of a.params)s(l);for(let l of Object.values(a))Array.isArray(l)?l.forEach(i):l&&typeof l=="object"&&i(l)}};i(e);let o=(a,l=new Set)=>{if(l.has(a))return;if(l.add(a),!n.has(a))return this.hostFunctions.get(a);if(n.get(a)!==1)return;let c=r.get(a);for(;c?.kind==="GroupingExpr";)c=c.expression;return c?.kind==="IdentifierExpr"?o(c.name,l):void 0};for(let a of n.keys()){let l=o(a);l&&this.knownHostReferences.set(a,l)}}addError(e,n,r,s){this.diagnostics.push({message:e,line:n,column:r,severity:"error",file:s})}isPropsBinding(e){return e==="PROPS"||e.endsWith(".PROPS")}checkReservedBinding(e,n){e.some(r=>r==="RESUMEPOINT"||r.endsWith(".RESUMEPOINT"))&&this.addError("'RESUMEPOINT' is reserved; rename this binding (RESUMEPOINT is read-only)",n.line,n.column,n.file)}checkRecoverSiblings(e){let n=!1;for(let r of e)r.kind==="RecoverStmt"&&(n&&this.addError("Only one recover statement is allowed in this statement list",r.line,r.column,r.file),n=!0)}isScopeOrAncestor(e,n){if(!n)return!1;let r=e;for(;r;){if(r===n)return!0;r=r.parent}return!1}noteRecoverWrite(e,n,r){let s=this.currentScope.resolvingScope(e),i=this.recoverContexts.find(o=>o.scope===s);if(i){if(r){let o=this.recoverScopedWrites.get(r);o||this.recoverScopedWrites.set(r,o=new Map),o.set(e,i.stmt)}if(!n){i.noInitializer.add(e);return}}if(n)for(let o of this.recoverContexts){if(!this.isScopeOrAncestor(o.scope,s))continue;let a=o.assigned.get(e);a||o.assigned.set(e,a=new Set),a.add(o.point)}}noteRecoverRead(e,n=e){let r=this.currentScope.resolvingScope(e.name),s=this.recoverContexts.find(i=>i.scope===r);s&&this.recoverScopedReads.set(n,s.stmt);for(let i of this.recoverContexts){if(!this.isScopeOrAncestor(i.scope,r))continue;let o=i.assigned.get(e.name);if(!o||o.has(i.point)||i.noInitializer.has(e.name)||i.warned.has(e.name))continue;i.warned.add(e.name);let a=[...o].sort((l,c)=>l-c).map(l=>i.points[l]).join(", ");this.diagnostics.push({severity:"warning",message:`Variable '${e.name}' read in resumepoint '${i.points[i.point]}' is assigned only in earlier resumepoint(s): ${a}; resuming here may skip initialization`,line:e.line,column:e.column,file:e.file})}}packageBindingCollision(e){return this.options.sourcePackages?.has(e.split(".").at(-1))??!1}collectFunction(e){for(let r of[e.name,...e.params])this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a function or parameter",e.line,e.column,e.file);if((this.isPropsBinding(e.name)||e.params.includes("PROPS"))&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name,...e.params],e),!e.isStdlib&&this.options.reservedFunctionPrefixes?.some(r=>e.name.startsWith(r))){this.addError(`Function name '${e.name}' uses a reserved built-in prefix`,e.line,e.column,e.file);return}if(this.functions.has(e.name)){let r=this.functions.get(e.name);if(r.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(r.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=r.file?`${r.file}:${r.line}`:`line ${r.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let n=new Set;for(let r of e.params)n.has(r)&&this.addError(`Duplicate parameter name '${r}' in function '${e.name}'`,e.line,e.column,e.file),n.add(r);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"PackageStmt":{(this.currentScope.parent||this.inFunction)&&this.addError("package must be the first file-level statement",e.line,e.column,e.file),(this.options.reservedFunctionPrefixes?.some(n=>e.name.startsWith(n))||this.options.builtinProviderNames?.includes(e.name))&&this.addError("Package name '"+e.name+"' uses a reserved built-in name/prefix",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),(e.name==="ARGV"||this.currentScope.resolve(e.name)||this.functions.has(e.name))&&this.addError("Package name collision: '"+e.name+"' is already a variable or function",e.line,e.column,e.file),this.loadedPackages.add(e.name);break}case"ImportStmt":{this.addError("Import must be at file top level; move the literal include before use",e.line,e.column,e.file);break}case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let n=this.currentScope,r=this.inFunction;this.inFunction=!0,this.currentScope=new Xn(n,!0);for(let i of e.params)this.currentScope.define(i);let s=this.loopDepth;this.loopDepth=0,this.checkRecoverSiblings(e.body.statements);for(let i of e.body.statements)this.checkStmt(i);this.loopDepth=s,this.inFunction=r,this.currentScope=n;break}case"VarDeclStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a variable",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.currentScope.hasInCurrent(e.name)&&!(this.options.builtinGlobals?.includes(e.name)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(e.name))&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer,!0),this.currentScope.define(e.name),this.currentScope.shadowedGlobals.add(e.name),this.noteRecoverWrite(e.name,e.initializer!==void 0&&e.initializer!==null);break}case"TupleVarDeclStmt":{e.names.some(n=>this.isPropsBinding(n))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.names,e),this.checkExpr(e.initializer);for(let n of e.names)this.packageBindingCollision(n)&&this.addError("Package name collision: '"+n+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.hasInCurrent(n)&&!(this.options.builtinGlobals?.includes(n)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(n))&&this.addError(`Variable '${n}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(n),this.currentScope.shadowedGlobals.add(n),this.noteRecoverWrite(n,!0);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForInStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a loop binding",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.checkExpr(e.iterable);let n=this.currentScope;if(this.currentScope=new Xn(n),this.currentScope.define(e.name),this.loopDepth++,e.body.kind==="BlockStmt")for(let r of e.body.statements)this.checkStmt(r);else this.checkStmt(e.body);this.loopDepth--,this.currentScope=n;break}case"ForStmt":{let n=s=>{if(!(!s||typeof s!="object")){if(s.kind==="CommandExpr"){let i=s;this.addError("command: not allowed in a loop header; assign argv before the loop",i.line,i.column,i.file);return}for(let i of Object.values(s))Array.isArray(i)?i.forEach(n):n(i)}};n(e.init);let r=this.currentScope;this.currentScope=new Xn(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,e.update&&this.checkExpr(e.update),this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value,!0);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let n=this.currentScope;this.currentScope=new Xn(n),this.checkRecoverSiblings(e.statements);for(let r of e.statements)this.checkStmt(r);this.currentScope=n;break}case"RecoverStmt":{this.hasRecover=!0,this.loopDepth>0&&this.addError("recover is not allowed lexically inside a loop body",e.line,e.column,e.file);let n=new Set;for(let i of e.points)n.has(i.name)&&this.addError(`Duplicate resumepoint '${i.name}'`,i.line,i.column,i.file),n.add(i.name),this.recoverLabels.add(i.name);let r=this.currentScope;this.currentScope=new Xn(r);let s={stmt:e,scope:this.currentScope,points:e.points.map(i=>i.name),point:0,assigned:new Map,noInitializer:new Set,warned:new Set};this.recoverContexts.push(s),e.points.forEach((i,o)=>{s.point=o,this.checkRecoverSiblings(i.statements);for(let a of i.statements)this.checkStmt(a)}),this.recoverContexts.pop(),this.currentScope=r;break}case"SyncAssignStmt":{this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value),this.noteRecoverWrite(e.target,!0,e);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let n=e.call;n.args.length===0&&this.addError(`Synchronized call '${n.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let r=this.hostFunctions.get(n.callee);(!r||!r.isContainerMutation)&&this.addError(`Synchronized call '${n.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr,e.expr.kind==="AssignExpr"||e.expr.kind==="CommandExpr"&&e.expr.mode==="system");break}}}checkReadPath(e){let n=e.args[0];for(;n.kind==="GroupingExpr";)n=n.expression;if(n.kind!=="PathLiteralExpr"){if(n.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof n.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!U.statSync(n.value).isFile())throw new Error("path is not a regular file");U.accessSync(n.value,U.constants.R_OK)}catch(r){this.addError(`Cannot read file ${JSON.stringify(n.value)}: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,e.file)}}}optionLiteral(e){if(e.kind==="GroupingExpr")return this.optionLiteral(e.expression);if(e.kind==="LiteralExpr")return{type:e.value===null?"null":typeof e.value,value:e.value};if(e.kind==="ArrayExpr"||e.kind==="TupleExpr")return{type:"list"};if(e.kind==="ObjectExpr")return{type:"map"};if(e.kind==="UnaryExpr"&&e.operator==="-"&&e.operand.kind==="LiteralExpr"&&typeof e.operand.value=="number")return{type:"number",value:-e.operand.value}}optionSuggestion(e,n){let r=a=>a.toLowerCase().replace(/[_-]/g,"");function s(a,l){let c=Array.from({length:l.length+1},(u,d)=>d);for(let u=1;u<=a.length;u++){let d=[u];for(let m=1;m<=l.length;m++)d[m]=Math.min(d[m-1]+1,c[m]+1,c[m-1]+(a[u-1]===l[m-1]?0:1));c=d}return c[l.length]}let i=n.filter(a=>a.name!=="*"),o=a=>{let l=r(e),c=r(a),u=0;for(;u<l.length&&u<c.length&&l[u]===c[u];)u++;return s(l,c)/Math.max(1,l.length,c.length)-u/Math.max(1,l.length)};return i.sort((a,l)=>o(a.name)-o(l.name)),i[0]?`; did you mean '${i[0].name}'?`:""}checkHostOptions(e,n){for(let[r,s]of n.entries()){if(!s.keys)continue;let i=e.args[r];for(;i?.kind==="GroupingExpr";)i=i.expression;if(i?.kind!=="ObjectExpr")continue;let o=new Set,a=s.open||s.keys.some(l=>l.name==="*"&&(l.type==="any"||l.type==="open"));for(let l of i.properties){let c=l.line??i.line,u=l.column??i.column,d=l.file??i.file;o.has(l.key)&&this.addError(`Duplicate option '${l.key}' in '${e.callee}' argument '${s.name}'`,c,u,d),o.add(l.key);let m=s.keys.find(g=>g.name===l.key);if(!m){a||this.addError(`Unknown option '${l.key}' in '${e.callee}' argument '${s.name}'${this.optionSuggestion(l.key,s.keys)}`,c,u,d);continue}let p=this.optionLiteral(l.value);if(!p||!m.type||m.type==="any"||m.type==="open")continue;let f=m.type.split("|").map(g=>g.trim().replace(/^array$/,"list").replace(/^object$/,"map")),h=["string","number","boolean","null","list","map"];f.every(g=>h.includes(g))&&!f.includes(p.type)&&this.addError(`Option '${l.key}' expects ${m.type}, got ${p.type}`,l.value.line,l.value.column,l.value.file),m.values&&p.type!=="list"&&p.type!=="map"&&!m.values.includes(p.value)&&this.addError(`Option '${l.key}' has a literal value outside its declared values`,l.value.line,l.value.column,l.value.file)}for(let l of s.keys)l.required&&l.name!=="*"&&!o.has(l.name)&&this.addError(`Missing required option '${l.name}' in '${e.callee}' argument '${s.name}'`,i.line,i.column,i.file)}for(let r=0;r<n.length;r++){let s=n[r];if(!s.checkLiteral||s.keys||s.rest)continue;let i=e.args[r];if(!i)continue;let o=this.optionLiteral(i);if(!o)continue;let a=s.type?.trim().toLowerCase();if(a&&a!=="any"&&a!=="json"&&a!=="open"){let l=a.split("|").map(u=>u.trim().replace(/^array$/,"list").replace(/^object$/,"map").replace(/^bool$/,"boolean")),c=["string","number","boolean","null","list","map"];l.every(u=>c.includes(u))&&!l.includes(o.type)&&this.addError(`Argument '${s.name}' in '${e.callee}' expects ${s.type}, got ${o.type}`,i.line,i.column,i.file)}s.values&&o.type!=="list"&&o.type!=="map"&&!s.values.some(l=>Object.is(l,o.value))&&this.addError(`Argument '${s.name}' in '${e.callee}' has a literal value outside its declared values`,i.line,i.column,i.file)}}checkPackageMember(e,n){let r=e.split(".")[0],s=this.options.sourcePackages?.get(r);if(!this.loadedPackages.has(r)&&this.currentScope.resolve(r)){this.addError("Map member calls are not supported; use a named function",n.line,n.column,n.file);return}if(!this.loadedPackages.has(r)){this.addError("package "+r+" not loaded: import it before use; import order matters, leaf packages first",n.line,n.column,n.file);return}s?.members.includes(e)||this.addError("Unknown package member '"+e+"'"+this.optionSuggestion(e,(s?.members??[]).map(i=>({name:i}))),n.line,n.column,n.file)}checkPropertyPath(e,n){let r;try{r=jm(e)}catch(l){this.addError(l.message,n.line,n.column,n.file);return}let s=this.options.propertyDeclarations;if(!s||(r=$l(r,s.known),s.known.includes(r)||s.closedTables?.includes(r)))return;let o=r.split(".")[0],a=this.optionSuggestion(r,s.known.map(l=>({name:l})));s.closedTables?.includes(o)&&this.addError(`Unknown property '${e}'${a}`,n.line,n.column,n.file)}checkExpr(e,n=!1){switch(e.kind){case"CommandExpr":e.words.length||this.addError("command: a program is required",e.line,e.column,e.file),n||this.addError("command: allowed only as a simple initializer, return value, or standalone system statement",e.line,e.column,e.file);for(let r of e.words)for(let s of r.pieces)typeof s!="string"&&this.checkExpr(s.expression);e.mode==="system"&&this.checkExpr({kind:"CallExpr",callee:"system",args:[{kind:"ArrayExpr",elements:[],line:e.line,column:e.column}],line:e.line,column:e.column,file:e.file});break;case"InterpolatedStringExpr":for(let r of e.parts)typeof r!="string"&&this.checkExpr(r.expression);break;case"LiteralExpr":break;case"MethodCallExpr":{if(e.receiver.kind==="IdentifierExpr"&&!e.receiver.name.includes(".")&&!this.currentScope.resolve(e.receiver.name)&&!this.functions.has(e.receiver.name)){let s=e.receiver.name+"."+e.method;Object.hasOwn(ko,s)&&!this.options.sourcePackages?.has(e.receiver.name)?this.addError(si(s),e.receiver.line,e.receiver.column,e.file):(this.addError("Call to undefined function '"+s+"'",e.receiver.line,e.receiver.column,e.file),this.checkPackageMember(s,e.receiver));for(let i of e.args)this.checkExpr(i);break}this.checkExpr(e.receiver);let r=yl(e.method);if(!r.length)this.addError("unknown method '"+e.method+"'; methods: "+am(),e.line,e.column,e.file);else{let s=$_(e.method);s.includes(e.args.length)||this.addError("method "+e.method+"() expects "+s.join(" or ")+" argument"+(s.length===1&&s[0]===1?"":"s")+", received "+e.args.length+"; signatures: "+r.join(", "),e.line,e.column,e.file)}for(let s of e.args)this.checkExpr(s);break}case"PathLiteralExpr":{let r=this.options.hostContext?.platform??this.options.platform??process.platform,s;try{s=sm(e.mode,e.raw,r)}catch(i){if(!(i instanceof sn))throw i;this.addError(i.message,e.line,e.column,e.file);break}if(this.options.checkPaths){let i=M_(e.mode,e.raw,s,this.options.hostContext?.cwd??process.cwd(),r,this.options.pathAccess??im);i&&this.addError(i,e.line,e.column,e.file)}break}case"DataBlockExpr":{let r=El[e.marker],s="_"+e.marker+"_",i=!1;for(let a of e.options){let l=r[a.name];if(!l)this.addError(s+": unknown option '"+a.name+"'"+(Object.keys(r).length?this.optionSuggestion(a.name,Object.keys(r).map(c=>({name:c})))+"; known options: "+Object.keys(r).join(", "):"; "+s+" takes no options"),a.line,a.column,a.file);else{let c=this.optionLiteral(a.value);c?c.type!==l.type&&(i=!0,this.addError(s+": option '"+a.name+"' must be a "+l.type+"; found "+c.type,a.line,a.column,a.file)):i=!0}this.checkExpr(a.value)}let o=0;for(let a of e.lines)for(let l of a.pieces)typeof l!="string"&&(o++,this.checkExpr(l.expression));if(e.closed&&!i&&!e.options.some(a=>!r[a.name]))for(let a of sv(e.marker,Nv(e),new Array(o).fill(it),Pm(e,l=>this.optionLiteral(l.value).value))){let l=Ov(e,a);this.addError(Wn[e.marker]+": "+a.message,l.line,l.column,e.file)}break}case"IdentifierExpr":{if(e.name.includes(".")){this.checkPackageMember(e.name,e),this.loadedPackages.has(e.name.split(".")[0])&&!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError("Package variable '"+e.name+"' used before declaration",e.line,e.column,e.file);break}(e.name==="PROPS"||e.name==="expand"||hv.includes(e.name))&&(this.usedProperties=!0);let r=this.currentScope.resolvingScope(e.name);r&&!r.parent&&this.options.globals?.includes(e.name)&&this.usedGlobals.add(e.name),this.noteRecoverRead(e),!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(Object.hasOwn(ko,e.name)?si(e.name,"Undeclared variable"):this.options.propertyDeclarations?.removedGlobals?.[e.name]?`'${e.name}' was replaced by ${this.options.propertyDeclarations.removedGlobals[e.name]}; declare a local variable if intended`:`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.packageBindingCollision(e.target)&&this.addError("Package name collision: '"+e.target+"' is a variable",e.line,e.column,e.file),e.target.includes(".")&&this.checkPackageMember(e.target,e),this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.checkExpr(e.value,n&&e.value.kind!=="AssignExpr"),this.currentScope.resolveInScope(e.target)||this.currentScope.define(e.target),this.currentScope.resolvingScope(e.target)?.shadowedGlobals.add(e.target),this.noteRecoverWrite(e.target,!0,e);break}case"TupleAssignExpr":{e.targets.some(r=>this.isPropsBinding(r))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.targets,e),this.checkExpr(e.value);for(let r of e.targets)this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.resolveInScope(r)||this.currentScope.define(r),this.currentScope.resolvingScope(r)?.shadowedGlobals.add(r),this.noteRecoverWrite(r,!0,e);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"ConditionalExpr":{this.checkExpr(e.condition),this.checkExpr(e.trueArm),this.checkExpr(e.falseArm);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{let r=Ul(e);r&&this.checkPropertyPath(r,e),this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{if(e.callee==="system"){let a=l=>l.kind==="LiteralExpr"?typeof l.value=="string":l.kind==="InterpolatedStringExpr"?!0:l.kind==="GroupingExpr"?a(l.expression):l.kind==="BinaryExpr"&&l.operator==="+"?a(l.left)||a(l.right):!1;e.args[0]&&a(e.args[0])&&this.addError("command: system(string) is not supported; write system PROGRAM ARGS or system([program, args...]); for an explicit shell invoke bash -c with a script field",e.line,e.column,e.file)}if(e.callee.includes(".")&&(Object.hasOwn(ko,e.callee)&&!this.options.sourcePackages?.has(e.callee.split(".")[0])?this.addError(si(e.callee),e.line,e.column,e.file):this.checkPackageMember(e.callee,e)),hv.includes(e.callee)&&(this.usedProperties=!0,e.args[0]?.kind==="LiteralExpr"&&typeof e.args[0].value=="string"&&e.args[0].value!==""&&this.checkPropertyPath(e.args[0].value,e.args[0])),e.callee==="expand"){let a=e.args[0];if(a?.kind==="LiteralExpr"&&typeof a.value=="string")try{let l=vo(a.value),c=e.args[1];for(;c?.kind==="GroupingExpr";)c=c.expression;let u=e.args[1]?c?.kind==="ObjectExpr"?new Set(c.properties.map(m=>m.key)):void 0:new Set,d=new Set;for(let m of l)typeof m!="string"&&(m.kind==="property"?(this.usedProperties=!0,this.checkPropertyPath(m.key,a)):m.kind==="variable"&&u&&!u.has(m.name)&&d.add(m.name));if(d.size){let m=[...d].map(p=>`${p} (not defined)`).join("; ");this.addError(`expand: missing references: ${m}; assign a temporary variable first and pass it in vars.`,a.line,a.column,a.file)}}catch(l){this.addError(l.message,a.line,a.column,a.file)}else this.usedProperties=!0}let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(si(e.callee),e.line,e.column,e.file);let s=this.hostFunctions.get(e.callee)??this.knownHostReferences.get(e.callee),i=a=>{if(a.kind==="AssignExpr")return a.target==="dryrun"||i(a.value);if(a.kind==="TupleAssignExpr")return a.targets.includes("dryrun")||i(a.value);for(let l of Object.values(a))if(l&&typeof l=="object"&&(Array.isArray(l)?l.some(c=>c&&typeof c=="object"&&i(c)):i(l)))return!0;return!1};(s||!r||r.isHost)&&e.args.some(i)&&this.addError(`dryrun is supplied by the language; omit it from '${e.callee}' arguments`,e.line,e.column,e.file);let o=s?.signature?.publicArity??s?.arity;!r&&typeof o=="number"&&e.args.length!==o&&this.addError(`Function '${e.callee}' expects ${o} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),typeof o=="object"&&(e.args.length<o.min||e.args.length>(o.max??1/0))&&this.addError(`Function '${e.callee}' expects ${o.min}..${o.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),(this.hostFunctions.has(e.callee)||s?.signature?.dryrunIndex!==void 0)&&(s?.signature?.publicParams?this.checkHostOptions(e,s.signature.publicParams):s?.params&&this.checkHostOptions(e,s.params)),this.options.checkFiles&&s?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let a of e.args)this.checkExpr(a);r||this.noteRecoverRead({...e,kind:"IdentifierExpr",name:e.callee},e);break}}}};ze=class{value;constructor(e){this.value=e}},ot=class{},at=class{},Vn=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},gt=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,n){this.values.set(e,n)}ownBindings(){return this.values.entries()}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}hasInScope(e){return this.values.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.hasInScope(e):!1}writeTarget(e){return this.values.has(e)?this:!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)?this.parent.writeTarget(e):this}set(e,n){if(this.values.has(e)){this.values.set(e,n);return}if(!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)){this.parent.set(e,n);return}this.values.set(e,n)}},Bl=class{holderTaskId;depth=0;waiters=[];acquire(e=0,n=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((r,s)=>{let i;n>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${n}ms (possible deadlock)`)))},n));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,r()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,n=0,r=1e4){await this.acquire(n,r);try{return await e()}finally{this.release()}}},qm=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let n=this.bindingLocks.get(e);return n||(n=new Bl,this.bindingLocks.set(e,n)),n}getObjectLock(e){let n=this.objectLocks.get(e);return n||(n=new Bl,this.objectLocks.set(e,n)),n}},Ee=Object.freeze({readonly:!0}),EL=t=>{for(let e of Object.values(t))Object.freeze(e);return Object.freeze(t)},Xm=EL({warning:{readonly:!0,control:"warning",dummyType:"string"},which:Ee,get_property:Ee,has_property:Ee,get_properties:Ee,expand:Ee,set_property:{dummyType:"null"},read:Ee,read_file:Ee,read_lines:{readonly:!0,dummyType:"array"},read_json:{readonly:!0,dummyType:"map"},read_csv:{readonly:!0,dummyType:"array"},file_exists:{readonly:!0,dummyType:"boolean"},glob:{readonly:!0,dummyType:"array"},list_dir:{readonly:!0,dummyType:"array"},read_tree:{readonly:!0,dummyType:"array"},csv_parse:{readonly:!0,dummyType:"array"},csv_stringify:{readonly:!0,dummyType:"string"},basename:{readonly:!0,dummyType:"string"},dirname:{readonly:!0,dummyType:"string"},path_join:{readonly:!0,dummyType:"string"},abs_path:{readonly:!0,dummyType:"string"},write:{dummyType:"boolean"},write_file:{dummyType:"boolean"},write_file_exclusive:{dummyType:"boolean"},write_files:{dummyType:"map"},write_lines:{dummyType:"boolean"},write_json:{dummyType:"boolean"},write_csv:{dummyType:"boolean"},append_file:{dummyType:"boolean"},delete_file:{dummyType:"boolean"},remove_file:{dummyType:"boolean"},mkdir:{dummyType:"boolean"},rmdir:{dummyType:"boolean"},copy_file:{dummyType:"boolean"},move_file:{dummyType:"boolean"},temp_file:{dummyType:"null"},env:{readonly:!0,frozen:"env"},getenv:{readonly:!0,frozen:"env"},set_env:{dummyType:"boolean"},list:{readonly:!0,dummyType:"array"},array:{readonly:!0,dummyType:"array"},push:Ee,pop:Ee,shift:Ee,unshift:Ee,insert:Ee,remove_at:Ee,concat:{readonly:!0,dummyType:"array"},reverse:{readonly:!0,dummyType:"array"},sort:{readonly:!0,dummyType:"array"},unique:{readonly:!0,dummyType:"array"},flatten:{readonly:!0,dummyType:"array"},first:Ee,last:Ee,sum:{readonly:!0,dummyType:"number"},avg:{readonly:!0,dummyType:"number"},map:{readonly:!0,dummyType:"map"},hash:{readonly:!0,dummyType:"map"},from_entries:{readonly:!0,dummyType:"map"},clear:Ee,size:{readonly:!0,dummyType:"number"},len:{readonly:!0,dummyType:"number"},keys:{readonly:!0,dummyType:"array"},values:{readonly:!0,dummyType:"array"},entries:{readonly:!0,dummyType:"array"},items:{readonly:!0,dummyType:"array"},has_key:{readonly:!0,dummyType:"boolean"},get:Ee,getstr:{readonly:!0,dummyType:"string"},getnum:{readonly:!0,dummyType:"number"},getbool:{readonly:!0,dummyType:"boolean"},getlist:{readonly:!0,dummyType:"array"},set:Ee,delete_key:Ee,merge:{readonly:!0,dummyType:"map"},clone:Ee,pluck:{readonly:!0,dummyType:"array"},filter_by:{readonly:!0,dummyType:"array"},find_by:Ee,json_parse:Ee,json_parse_safe:Ee,json_stringify:{readonly:!0,dummyType:"string"},regex_test:{readonly:!0,dummyType:"boolean"},regex_match:{readonly:!0,dummyType:"array"},regex_find_all:{readonly:!0,dummyType:"array"},regex_replace:{readonly:!0,dummyType:"string"},split_regex:{readonly:!0,dummyType:"array"},split:{readonly:!0,dummyType:"array"},lines:{readonly:!0,dummyType:"array"},last_line_as_status:Ee,parse_file_blocks:{readonly:!0,dummyType:"array"},format_file_blocks:{readonly:!0,dummyType:"string"},kv_from_last_paragraph:{readonly:!0,dummyType:"map"},split_command:{readonly:!0,dummyType:"array"},words:{readonly:!0,dummyType:"array"},join:{readonly:!0,dummyType:"string"},trim:{readonly:!0,dummyType:"string"},strip:{readonly:!0,dummyType:"string"},trim_start:{readonly:!0,dummyType:"string"},lstrip:{readonly:!0,dummyType:"string"},trim_end:{readonly:!0,dummyType:"string"},rstrip:{readonly:!0,dummyType:"string"},to_upper:{readonly:!0,dummyType:"string"},upper:{readonly:!0,dummyType:"string"},to_lower:{readonly:!0,dummyType:"string"},lower:{readonly:!0,dummyType:"string"},upper_first:{readonly:!0,dummyType:"string"},title_case:{readonly:!0,dummyType:"string"},contains:{readonly:!0,dummyType:"boolean"},includes:{readonly:!0,dummyType:"boolean"},starts_with:{readonly:!0,dummyType:"boolean"},startswith:{readonly:!0,dummyType:"boolean"},ends_with:{readonly:!0,dummyType:"boolean"},endswith:{readonly:!0,dummyType:"boolean"},index_of:{readonly:!0,dummyType:"number"},last_index_of:{readonly:!0,dummyType:"number"},count_matches:{readonly:!0,dummyType:"number"},substr:{readonly:!0,dummyType:"string"},substring:{readonly:!0,dummyType:"string"},slice:Ee,char_at:{readonly:!0,dummyType:"string"},char_code:{readonly:!0,dummyType:"number"},from_char_code:{readonly:!0,dummyType:"string"},replace:{readonly:!0,dummyType:"string"},replace_all:{readonly:!0,dummyType:"string"},repeat:{readonly:!0,dummyType:"string"},pad_start:{readonly:!0,dummyType:"string"},pad_end:{readonly:!0,dummyType:"string"},reverse_str:{readonly:!0,dummyType:"string"},is_empty:{readonly:!0,dummyType:"boolean"},is_digit:{readonly:!0,dummyType:"boolean"},is_alpha:{readonly:!0,dummyType:"boolean"},is_alnum:{readonly:!0,dummyType:"boolean"},is_array:{readonly:!0,dummyType:"boolean"},is_string:{readonly:!0,dummyType:"boolean"},is_number:{readonly:!0,dummyType:"boolean"},is_map:{readonly:!0,dummyType:"boolean"},is_function:{readonly:!0,dummyType:"boolean"},format:{readonly:!0,dummyType:"string"},sprintf:{readonly:!0,dummyType:"string"},cmd_render:{readonly:!0,dummyType:"string"},range:{readonly:!0,dummyType:"array"},abs:{readonly:!0,dummyType:"number"},min:{readonly:!0,dummyType:"number"},max:{readonly:!0,dummyType:"number"},floor:{readonly:!0,dummyType:"number"},ceil:{readonly:!0,dummyType:"number"},round:{readonly:!0,dummyType:"number"},sqrt:{readonly:!0,dummyType:"number"},pow:{readonly:!0,dummyType:"number"},sha256:{readonly:!0,dummyType:"string"},now:{readonly:!0,dummyType:"number",frozen:"now"},timestamp:{readonly:!0,dummyType:"number",frozen:"timestamp"},date:{readonly:!0,dummyType:"string",frozen:"date"},strftime:{readonly:!0,dummyType:"string"},coalesce:Ee,if_null:Ee,if_else:Ee,str:{readonly:!0,dummyType:"string"},num:{readonly:!0,dummyType:"number"},type:{readonly:!0,dummyType:"string"},require:{readonly:!0,control:"require"},assert:{readonly:!0,control:"assert"},error:{readonly:!0,control:"error",dummyType:"string"},exit:{readonly:!0,control:"exit",dummyType:"null"},print:{control:"print",dummyType:"string",taints:!1},println:{control:"println",dummyType:"string",taints:!1},printf:{control:"printf",dummyType:"string",taints:!1},system:{dummyType:"SystemResult",process:!0},run_script:{dummyType:"map",dummyValue:()=>({success:!0,stdout:"",output:[],exit_code:0,code:0,value:null,errors:[]})},http_get:{dummyType:"string"},random:{dummyType:"number"},sleep_ms:{dummyType:"null"},prompt_human:{dummyType:"null"},prompt_human_config:{dummyType:"map"}}),TL={stdout:"",stderr:"",code:0,signal:null,timed_out:!1,duration_ms:0,pid:null,dry:!0};qe=Symbol("core dry policy"),Gm=Symbol("dry invocation"),Jm=Symbol("implicit preflight work limit"),Vm=Symbol("implicit preflight stdout");Kt=class extends Error{isControlFlow=!0;exitCode=0};Hl=class{entries=[];lastSite={line:1,column:1};failure;recordedDiagnostics=[];recordError(e,n=this.lastSite){this.sealed||(this.check(),this.recordedDiagnostics.push({...n,severity:"error",message:e}))}scriptExit;sealed=!1;loopLimit;platform;timeout;deadline=1/0;wallClock;environment;planBytes=0;work=0;workLimit;replay;cleanups=new Map;own(e){this.cleanups.has(e)||this.cleanups.set(e,{started:!1})}dispose(e){this.own(e);let n=this.cleanups.get(e);return n.started||(n.started=!0,n.value=e.dispose(),lt(n.value)&&Promise.resolve(n.value).catch(()=>{})),n.value}controller=new AbortController;truncation;onStart;start(){Number.isFinite(this.deadline)||(this.deadline=performance.now()+this.timeout,this.onStart?.())}constructor(e={}){if(this.replay=e[Vm],this.workLimit=e[Jm]??1/0,this.platform=e.hostContext?.platform??e.platform??process.platform,this.wallClock=e.dryrunClockMs??Date.now(),!Number.isFinite(this.wallClock))throw Error("Dry wall clock must be finite");this.environment=Object.freeze(Object.assign(Object.create(null),e.hostContext?.env??process.env)),this.loopLimit=e.dryLoopLimit??10,this.timeout=e.dryrunTimeoutMs??5e3;for(let n of[this.loopLimit,this.timeout])if(!Number.isSafeInteger(n)||n<=0)throw Error("Dry bounds must be positive safe integers")}hasTaintedValues=!1;get tainted(){return this.hasTaintedValues}at(e){this.lastSite={file:e.file,line:e.line,column:e.column},++this.work>this.workLimit&&this.truncate("work budget exceeded"),this.check()}check(){if(this.truncation)throw new Kt(this.truncation);if(this.sealed)throw new Kt("Dry pass finished");performance.now()>=this.deadline&&this.truncate("time budget exceeded")}truncate(e){this.truncation??="dry run truncated: "+e,this.sealed=!0,this.controller.abort();for(let n of[...this.cleanups.keys()].reverse())try{this.dispose(n)}catch{}throw new Kt(this.truncation)}async wait(e){let n=Promise.resolve(e);n.catch(()=>{}),this.check();let r;try{let s=await Promise.race([n,new Promise((i,o)=>{let a=()=>{r&&(clearTimeout(r),r=void 0);let l=this.deadline-performance.now();if(l<=0)try{this.truncate("time budget exceeded")}catch(c){o(c)}else r=setTimeout(a,Math.min(2147483647,Math.max(1,l)))};this.onStart=a,a()})]);return this.check(),s}finally{r&&clearTimeout(r),this.onStart=void 0}}loop(e,n){return this.at(n),e<this.loopLimit?!1:(this.append({seq:this.entries.length+1,kind:"loop",file:n.file??"<main>",line:n.line,column:n.column,iterations:e,limit:this.loopLimit,message:"loop truncated at "+this.loopLimit,simulated:!1}),this.hasTaintedValues=!0,!0)}propertyView;propertyLoads=[];prepareProperties(e){if(e&&["Directory","NonInteractive"].includes(e.split(".")[0]))return;let n=this.propertyLoads.map(r=>r());return n.some(lt)?Promise.all(n):void 0}fail(e,n=this.lastSite){throw this.check(),this.failure??={site:{...n},message:e,untrusted:this.tainted},new Kt(e)}finishExit(e,n=this.lastSite){this.scriptExit??={site:{...n},code:e}}captureFailure(e,n=this.lastSite){if(this.truncation)return;if(performance.now()>=this.deadline){try{this.truncate("time budget exceeded")}catch{}return}let r=SL(e);if(r!==void 0){this.finishExit(r,n);return}if(e?.isControlFlow&&e?.resourceFailure===void 0)return;let s=e instanceof P?{file:e.file,line:e.line,column:e.column}:n;this.failure??={site:{...s},message:e instanceof Error?e.message:String(e),untrusted:this.tainted}}captureOutput(e,n){if(!this.replay)return;this.check();let r=Buffer.byteLength(n)+Buffer.byteLength(this.lastSite.file??"")+32;this.planBytes+r>1024*1024-4096&&this.truncate("console output size exceeded"),this.planBytes+=r,this.replay.push({name:e,text:n,site:{...this.lastSite}})}record(e,n,r,s,i,o=!0){this.sealed||(this.check(),this.append({seq:this.entries.length+1,kind:s,file:r.file??"<main>",line:r.line,column:r.column,function:e,arguments:n,simulated:!0,...i?{argv:[...i],renderedArgv:rp(i,this.platform==="win32"?"windows":"posix"),dialect:this.platform==="win32"?"windows":"posix"}:{}}),this.hasTaintedValues||=o)}snapshot(e){let n=new Map,r=new Map,s=0,i=a=>{s+=a,this.check(),s+this.planBytes>1024*1024-4096&&this.truncate("plan size exceeded")},o=(a,l,c)=>{if(i(8),c>256&&this.truncate("plan size traversal depth exceeded"),a===null||typeof a=="boolean")return a;if(typeof a=="string")return i(Buffer.byteLength(a)),a;if(typeof a=="number")return Number.isFinite(a)?a:{$type:String(a)};if(typeof a=="bigint"){let g=String(a);return i(g.length),{$type:"bigint",value:g}}if(typeof a=="symbol"){r.has(a)||r.set(a,r.size+1);let g=String(a);return i(Buffer.byteLength(g)),{$type:"symbol",id:r.get(a),value:g}}if(typeof a>"u"||typeof a=="function")return{$type:typeof a};if(Oe(a))return{$type:"resource"};if(Jn.has(a)&&(a=gs(a)),Se.isProxy(a))return{$type:"proxy"};let u=ap(a);if(u)return{$type:Se.isMap(a)?"Map":Se.isSet(a)?"Set":Se.isDate(a)?"Date":Se.isRegExp(a)?"RegExp":Se.isNativeError(a)?"Error":Se.isArrayBufferView(a)?"TypedArray":u};if(n.has(a))return{$ref:n.get(a)};n.set(a,l),Array.isArray(a)&&i(a.length);let d=Array.isArray(a)?new Array(a.length):{},m=Reflect.ownKeys(a);i(m.length*8);let p=Array.isArray(a),f=m.some(g=>typeof g=="symbol"||g==="$ref"||g==="$type"||p&&g!=="length"&&!(/^(0|[1-9][0-9]*)$/.test(g)&&Number(g)<a.length)),h=[];for(let g of m.filter(y=>y!=="length"||!Array.isArray(a)).sort((y,b)=>String(y)<String(b)?-1:String(y)>String(b)?1:0)){let y=typeof g=="symbol"?"symbol:"+h.length:g;i(Buffer.byteLength(y));let b=Object.getOwnPropertyDescriptor(a,g),_="value"in b?o(b.value,f?l+"/properties/"+h.length+"/1":l+"/"+y.replaceAll("~","~0").replaceAll("/","~1"),c+1):{$type:"accessor"};f?h.push([typeof g=="symbol"?o(g,l+"/properties/"+h.length+"/0",c+1):g,_]):Object.defineProperty(d,y,{value:_,enumerable:!0,writable:!0,configurable:!0})}return f?{$type:p?"array":"object",...p?{length:a.length}:{},properties:h}:d};return o(e,"$",0)}append(e){let n=Buffer.byteLength(JSON.stringify(e))+1;this.planBytes+n>1024*1024-4096&&this.truncate("plan size exceeded"),this.planBytes+=n,this.entries.push(e)}capture(e){if(this.truncation)return;let n=e.diagnostics;if(!this.failure){let r=n.find(s=>s.severity==="error");r&&(this.failure={site:r,message:r.message,untrusted:this.tainted})}!this.failure&&!this.scriptExit&&e.exitCode&&e.exitCode!==0&&(this.failure={site:this.lastSite,message:"exit("+e.exitCode+")",untrusted:this.tainted})}report(e){let n=[...e.diagnostics];this.capture(e);let r=[...this.recordedDiagnostics];for(let l of e.errors??[])r.some(c=>c.message===l)||r.push({...this.lastSite,severity:"error",message:l});if(this.sealed=!0,this.truncation&&!this.failure)return Om({version:1,status:"truncated",entries:this.entries,stop:{file:this.lastSite.file??"<main>",line:this.lastSite.line,column:this.lastSite.column,reason:this.truncation},diagnostics:[...r,...n.filter(l=>l.severity!=="error"),{...this.lastSite,severity:"warning",message:this.truncation}],exitCode:0});if(!this.failure){let l=this.scriptExit?{file:this.scriptExit.site.file??"<main>",line:this.scriptExit.site.line,column:this.scriptExit.site.column,reason:"script exit with code "+this.scriptExit.code}:null;return Om({version:1,status:this.scriptExit?"complete":this.entries.some(c=>c.kind==="loop")?"loop-limited":"complete",entries:this.entries,stop:l,diagnostics:[...r,...n],exitCode:0})}let{site:s,message:i,untrusted:o}=this.failure,a=o?"needs a real result: "+i:i;return Om({version:1,status:o?"needs-real-result":"failed",entries:this.entries,stop:{file:s.file??"<main>",line:s.line,column:s.column,reason:a},diagnostics:[...r,...!o&&n.some(l=>l.severity==="error")?n:[...n.filter(l=>l.severity!=="error"),{...s,severity:o?"warning":"error",message:a}]],exitCode:o?0:2})}};kL=new Set(["read","read_file","read_lines","read_json","read_csv"]);Ym=new WeakMap,Ro=class{constructor(e){Ym.set(this,e)}},xL=5e3;IL=1,Qm=class{id;constructor(e){Kv++,zv.add(this),Object.defineProperty(this,"id",{value:e,enumerable:!0}),Object.freeze(this)}},Kv=0;zv=new WeakSet;Rv=new WeakMap,Yv=1e7;xo=class{failure;records=[];label;parent;base;constructor(e,n,r){this.label=e,this.parent=n,this.base=r}isAncestorOf(e){for(let n=e.parent;n;n=n.parent)if(n===this)return!0;return!1}},Qv=new xv;Zm=class{token=`run-${process.pid}-${IL++}`;root=new xo("root");ordinal=0;terminating=!1;records=new WeakMap;ordered=[];rawRecords=new WeakMap;scopes=new WeakMap;onFailure;defaultDeadlineMs;failures=[];constructor(e,n={}){this.onFailure=e;let r=n.defaultDeadlineMs;this.defaultDeadlineMs=typeof r=="number"&&Number.isFinite(r)&&r>0?r:xL}scopeFor(e){for(let n=e;n;n=n.isFunctionScope?void 0:n.parent){let r=this.scopes.get(n);if(r)return r}return this.root}enterScope(e,n,r){let s=new xo(r,n);return this.scopes.set(e,s),s}temporaryScope(e,n,r){return new xo(n,e,r)}register(e,n,r,s){let i=String(e.id),o={handle:new Qm(i),raw:e,kind:typeof e.kind=="string"&&e.kind?e.kind:n,id:i,site:r,ordinal:++this.ordinal,owner:s,state:"open",adoptable:!0,unresolved:!1};return Rv.set(o.handle,`${o.kind} ${o.id}`),this.records.set(o.handle,o),this.rawRecords.set(e,o),this.ordered.push(o),s.records.push(o),o.handle}terminate(){if(!this.terminating){this.terminating=!0;for(let e of[...this.ordered].sort((n,r)=>r.ordinal-n.ordinal))if(!(e.state==="closed"||e.state==="close_failed"))try{typeof e.raw.finalizeSync=="function"&&(e.raw.finalizeSync(),e.state="closed")}catch(n){this.fail(e,"critical finalization failed: "+String(n))}}}authorizeRaw(e,n,r,s=!1){let i=e!==null&&typeof e=="object"?this.rawRecords.get(e):void 0;if(!i)throw Error("Resource "+String(e?.kind??"batch")+" "+String(e?.id)+" belongs to another run: "+r);if(i.owner!==n&&!i.owner.isAncestorOf(n))throw Error("Resource "+i.kind+" "+i.id+" is not authorized in this borrower scope: "+r);if(!s&&i.state!=="open")throw Error("Resource "+i.kind+" "+i.id+" is closed: "+r);return i}lookup(e){return this.records.get(e)}describe(e){let n=this.records.get(e);return n?`${n.kind} ${n.id}`:`${Rv.get(e)??e.id} (from another run)`}borrow(e){if(Oe(e)){let n=this.records.get(e);n&&(n.adoptable=!1)}}bind(e,n,r){if(!Oe(e))return;let s=this.records.get(e);if(!s)return`resource ${e.id} belongs to another run`;let i=this.scopeFor(n);if(s.adoptable){s.adoptable=!1,i!==s.owner&&(s.owner.records.splice(s.owner.records.indexOf(s),1),i.records.push(s),s.owner=i);return}if(i!==s.owner&&i.isAncestorOf(s.owner))return`resource ${s.kind} ${s.id} cannot escape its owner into the longer-lived binding '${r}'`}close(e,n){if(e.closing)return e.closing;e.state="closing";let r=e.raw,s=r.closeDeadlineMs,i=typeof s=="number"&&Number.isFinite(s)&&s>0?s:this.defaultDeadlineMs,o=performance.now(),a;e.closing=new Promise(c=>{a=c});let l=`close did not finish within its ${i} ms deadline`;return(async()=>{let c,u=!1;try{let d=r.close({reason:this.terminating?"cancelled":e.owner.failure!==void 0?"error":"done",error:e.owner.failure instanceof Error?e.owner.failure.message:e.owner.failure==null?void 0:String(e.owner.failure),explicit:n});if(lt(d)){let m=Promise.resolve(d).then(()=>!0);m.catch(()=>{});let p=i-(performance.now()-o);if(!(p>0&&await Promise.race([m,new Promise(h=>{c=setTimeout(()=>h(!1),p)})]))){this.critical(e),u=this.fail(e,l);return}}if(performance.now()-o>i){this.critical(e),u=this.fail(e,l);return}if(this.terminating&&e.state==="close_failed")return;e.state="closed",u=!0}catch(d){u=this.fail(e,d instanceof Error?d.message:String(d))}finally{c&&clearTimeout(c),a(u)}})(),e.closing}critical(e){try{typeof e.raw.finalizeSync=="function"&&e.raw.finalizeSync()}catch(n){this.report(`resource ${e.kind} ${e.id} (${e.site}): critical finalization failed: ${n instanceof Error?n.message:String(n)}`)}}fail(e,n){return e.state="close_failed",e.unresolved=!0,this.report(`resource close failed: ${e.kind} ${e.id} (${e.site}): ${n}`),!1}report(e){this.failures.push(e);try{this.onFailure(e)}catch{}}async drain(e){for(let n of[...e.records].sort((r,s)=>s.ordinal-r.ordinal))if(!(n.state==="closed"||n.state==="close_failed"))try{await this.close(n)}catch{}}snapshot(){return this.ordered.map(e=>({id:e.id,kind:e.kind,owner:e.owner.label,site:e.site,state:e.state,unresolved:e.unresolved,ordinal:e.ordinal}))}},Wl=class{nativeImports;executionOrigin;processContext;warningDiagnostics=[];dry;tracer;platform;abortSignal;resources;resourcesEnabled;temporaryScopes=new Map;globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new qm;isAsync;nextTaskId=1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recovery;initialGlobals;callDepth=0;noPreflight;asyncCallDepth=new Map;recordedErrors;promptHumanConfig;childEngineFactory;compileOptions;constructor(e,n=m=>console.log(m),r=!1,s,i,o,a=Eo(void 0),l=process.platform,c,u=!1,d){this.nativeImports=d,this.dry=c,this.noPreflight=u,this.platform=l,this.recovery=a,this.recordedErrors=a.errors,this.stdout=n,this.stderr=i,this.isAsync=r,this.initialGlobals=s,this.globalEnv=new gt,this.hostFunctions=new Map(e),this.promptHumanConfig=o??{mode:"interactive"},this.resourcesEnabled=[...this.hostFunctions.values()].some(R=>R.returnsResource===!0),this.resources=new Zm(R=>{Nl(this.recovery,R);try{this.stderr?.(`error: ${R}`)}catch{}});let m=e.get("print");(!m||m.isDefault)&&this.hostFunctions.set("print",{...m,fn:(...R)=>{let N=m?.signature?.dryrunIndex===0?R.shift()===!0:!1,O=R.map(A=>typeof A=="object"?JSON.stringify(A):String(A)).join(" ");return N||this.stdout(O),O},arity:m?.signature?.nativeArity??m?.arity??{min:0},description:m?.description??"Prints formatted values to output log",isDefault:!0});let p=e.get("println");(!p||p.isDefault)&&this.hostFunctions.set("println",{...p,fn:(...R)=>{let N=p?.signature?.dryrunIndex===0?R.shift()===!0:!1,O=R.map(A=>typeof A=="object"?JSON.stringify(A):String(A)).join(" ");return N||this.stdout(O),O},arity:p?.signature?.nativeArity??p?.arity??{min:0},description:p?.description??"Prints line to output log",isDefault:!0});let f=e.get("printf");(!f||f.isDefault)&&this.hostFunctions.set("printf",{...f,fn:(...R)=>{let N=f?.signature?.dryrunIndex===0?R.shift()===!0:!1,[O,...A]=R,w=Ll(O,A,"printf");return N||this.stdout(w),w},arity:f?.signature?.nativeArity??f?.arity??{min:2},description:f?.description??"Formats and prints %s, %d, %f and %% using sprintf rules",isDefault:!0});let h=e.get("require");(!h||h.isDefault)&&this.hostFunctions.set("require",{...h,fn:(R,N)=>np(R,N,O=>{Nl(this.recovery,O),this.stderr?.(`error: ${O}`)}),arity:2,isDefault:!0});let g=e.get("error");(!g||g.isDefault)&&this.hostFunctions.set("error",{...g,fn:(...R)=>{let N=R.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return Nl(this.recovery,N),this.stderr?this.stderr(`error: ${N}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${N}
|
|
425
|
-
`):console.error(`error: ${N}`),N},arity:{min:1},description:g?.description??"Prints error message to stderr and records it for execution error summary",isDefault:!0});let y=e.get("system");(!y||y.isDefault)&&this.hostFunctions.set("system",{...y,fn:(R,N)=>jv(R,N,{async:this.isAsync,platform:this.platform,signal:this.abortSignal,context:this.processContext}),arity:y?.arity??{min:1,max:2},description:"Executes argv directly with shell:false and optional timeoutMs (default 60000) or options {cwd, timeoutMs, stdin}, returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",isDefault:!0});let b=e.get("prompt_human_config");(!b||b.isDefault)&&this.hostFunctions.set("prompt_human_config",{...b,fn:(R,N)=>{if(R===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 R=="string")R==="interactive"?this.promptHumanConfig.mode="interactive":R==="file"?(this.promptHumanConfig.mode="file",N&&(this.promptHumanConfig.dir=String(N))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=R);else if(R&&typeof R=="object"){let O=R.mode?String(R.mode):R.dir?"file":this.promptHumanConfig.mode??"interactive",A=R.dir!==void 0?String(R.dir):this.promptHumanConfig.dir,w=R.timeout_ms!==void 0?Number(R.timeout_ms):R.timeoutMs!==void 0?Number(R.timeoutMs):this.promptHumanConfig.timeoutMs,T=R.poll_ms!==void 0?Number(R.poll_ms):R.pollIntervalMs!==void 0?Number(R.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=O==="file"?"file":"interactive",this.promptHumanConfig.dir=A,this.promptHumanConfig.timeoutMs=typeof w=="number"&&Number.isFinite(w)?w:void 0,this.promptHumanConfig.pollIntervalMs=typeof T=="number"&&Number.isFinite(T)&&T>0?T:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},arity:b?.arity??{min:0,max:2},description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",isDefault:!0});let _=e.get("prompt_human");(!_||_.isDefault)&&this.hostFunctions.set("prompt_human",{..._,fn:(R,N)=>{if((N?.mode??(N?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let A=N?.dir??this.promptHumanConfig.dir;if(!A)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsync)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return Bv(R,{dir:A,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,onWaiting:w=>this.stderr?this.stderr(w):typeof process<"u"&&process.stderr?process.stderr.write(w):void 0})}return this.isAsync?Gl(R,void 0,void 0,this.abortSignal):Uv(R)},arity:_?.arity??{min:0,max:2},description:"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",isDefault:!0});let v=e.get("cmd_render");(!v||v.isDefault)&&this.hostFunctions.set("cmd_render",{...v,fn:(R,N)=>rp(R,N,this.platform),arity:{min:1,max:2},isDefault:!0});let E=e.get("run_script");(!E||E.isDefault)&&this.hostFunctions.set("run_script",{...E,fn:(R,N=[])=>{let O=this.processContext,A=se.resolve(O?.cwd??process.cwd(),String(R));if(!U.existsSync(A))throw new Error(`run_script: file not found: '${A}'`);let w=U.readFileSync(A,"utf-8"),T=Array.isArray(N)?N.map(String):[],k=this.childEngineFactory?this.childEngineFactory({args:T}):new Er;if(!this.childEngineFactory){for(let[I,C]of this.hostFunctions)k.hasFunction(I)?C.isDefault||k.registerFunction(I,C.fn,C.signature?.nativeArity??C.arity,{description:C.description,params:C.signature?.nativeParams??C.params,returnType:C.returnType,readonly:C.readonly,dryControl:C.dryControl,[qe]:C[qe],doc:C.doc,allowOverwrite:!0,isContainerMutation:C.isContainerMutation,...hs(C)},!1,C.isContainerMutation):k.registerFunction(I,C.fn,C.signature?.nativeArity??C.arity,{description:C.description,params:C.signature?.nativeParams??C.params,returnType:C.returnType,readonly:C.readonly,dryControl:C.dryControl,[qe]:C[qe],doc:C.doc,isDefault:C.isDefault,isContainerMutation:C.isContainerMutation,...hs(C)});k.setGlobal("args",[...T]),k.setGlobal("ARGV",[...T])}if(this.isAsync)return(async()=>{let I=await k.runAsync(w,{file:A,entryLocation:A,executionOrigin:wr({source_kind:"file",script_file:A,source_name:A,parent_run_id:this.executionOrigin?.run_id}),signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight,hostContext:O,propertyStore:this.compileOptions?.propertyStore}),C=ys(I.value);if(C)throw new Error(`run_script: ${Oe(C)?`the child result contains resource ${C.id}, which cannot leave the child run`:Lm(C,"child run")}`);let M=I.output.join(`
|
|
424
|
+
`,Am=null;Jn=new WeakMap,No=new WeakMap,hv=["get_property","has_property","get_properties","set_property"];jl=class t{sources=new Map;loaded=!1;path="the registered property source";hint="Define it in the property source";tree={};known=[];overlay;constructor(e,n){this.tree.Directory=e,this.tree.NonInteractive=n.LMCTL_NON_INTERACTIVE==="1"}addSource(e,n,r){this.sources.has(e)||(this.sources.set(e,n),this.known.push(...r))}setOverlay(e){if(this.overlay){if($O(this.overlay,e))return;throw Error("Cannot set a different property overlay on a reused PropertyStore; create a new PropertyStore for each overlay")}if(this.loaded)throw Error("Set the property overlay before loading the store");this.overlay=oi(e)}fork(){let e=new t(this.tree.Directory,{LMCTL_NON_INTERACTIVE:this.tree.NonInteractive?"1":"0"});for(let[n,r]of this.sources)e.sources.set(n,r);e.known.push(...this.known),e.loaded=this.loaded,e.path=this.path,e.hint=this.hint;for(let[n,r]of Object.entries(this.tree))ct(e.tree,n,structuredClone(r));return this.overlay&&(e.overlay=oi(this.overlay)),e}load(e){if(this.loaded)return;let n={},r=[];for(let s of this.sources.values()){let i;try{if(i=s(),!ii(i.properties))throw Error("Property document must be a table in "+i.path);for(let a of["Directory","NonInteractive"])if(Object.hasOwn(i.properties,a))throw Error("Property '"+a+"' is read-only in "+i.path);i={...i,properties:structuredClone(i.properties)}}catch(a){throw Error("Property '"+e+"': "+(a instanceof Error?a.message:String(a)))}this.path=i.path,this.hint=i.hint??"Define it in the property source",r.push(i.path);let o=Um(i.properties,this.known,i.path);for(let[a,l]of Object.entries(o)){if(Object.hasOwn(n,a))throw Error("Property '"+a+"' conflicts with another source in "+i.path);ct(n,a,structuredClone(l))}}if(this.overlay){let s=Um(this.overlay.properties,this.known,this.overlay.path);n=Wv(n,s,r.join(", ")||this.path,this.overlay.path),this.path=r.concat(this.overlay.path).join(", ")}for(let[s,i]of Object.entries(n))ct(this.tree,s,i);this.loaded=!0}find(e,n=!0){let r=$l(jm(e),this.known);n&&!["Directory","NonInteractive"].includes(r.split(".")[0])&&this.load(r);let s=this.tree;for(let i of r.split(".")){if(!s||typeof s!="object"||!Object.hasOwn(s,i))return{found:!1,value:void 0,key:r};s=s[i]}return{found:!0,value:s,key:r}}missing(e){throw Error(`Property '${e}' is not defined in ${this.path}; ${this.hint}`)}get(e,...n){let r=this.find(e);return r.found?Gn(r.value,r.key):n.length?n[0]:this.missing(r.key)}has(e){return this.find(e).found}copy(e=""){if(!e)return this.load("<all>"),Gn(this.tree,"");let n=this.find(e);if(!n.found)return this.missing(n.key);if(!n.value||typeof n.value!="object"||Array.isArray(n.value)||n.value instanceof Date)throw Error(`Property '${n.key}' is not a table; get_properties requires a table`);return Gn(n.value,n.key)}set(e,n){let r=$l(jm(e),this.known);if(["Directory","NonInteractive"].includes(r.split(".")[0]))throw Error(`Property '${r}' is read-only`);let s=Gn(n,r),i=this.find(r),o=this.tree,a=r.split(".");for(let u of a.slice(0,-1)){if(Object.hasOwn(o,u)||ct(o,u,{}),!o[u]||typeof o[u]!="object"||Array.isArray(o[u])||o[u]instanceof Date)throw Error(`Property '${u}' is a value, not a table`);o=o[u]}let l=i.found?Gn(i.value,r):null,c=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)&&!(u instanceof Date);if(i.found&&c(i.value)!==c(s))throw Error(`Property '${r}' cannot change between a table and a value`);return ct(o,a.at(-1),s),l}view(e=""){let n=i=>{let o=e?e+"."+i:i,a=this.find(o);if(!a.found)return this.missing(a.key);if(a.value&&typeof a.value=="object"&&!Array.isArray(a.value)&&!(a.value instanceof Date))return this.view(a.key);let l=Gn(a.value,a.key),c=u=>{if(u&&typeof u=="object"){for(let d of Object.values(u))c(d);Object.freeze(u)}return u};return c(l)},r=()=>{throw Error(`PROPS${e?"."+e:""} is read-only; use set_property`)},s=new Proxy({},{get:(i,o)=>typeof o=="symbol"||o==="then"?void 0:o==="toJSON"?()=>this.copy(e):n(o),ownKeys:()=>(e||this.load("<keys>"),Object.keys(e?this.find(e).value:this.tree)),getOwnPropertyDescriptor:(i,o)=>{if(typeof o!="string")return;!e&&!["Directory","NonInteractive"].includes(o)&&this.load("<keys>");let a=e?this.find(e).value:this.tree;return Object.hasOwn(a,o)?{enumerable:!0,configurable:!0}:void 0},set:r,deleteProperty:r,defineProperty:r,setPrototypeOf:r});return Jn.set(s,n),No.set(s,()=>this.copy(e)),s}};qn=new xv;hL=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;Xn=class{variables=new Set;shadowedGlobals=new Set;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolvingScope(e){return this.variables.has(e)?this:this.parent?.resolvingScope(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}resolveInScope(e){return this.variables.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.resolveInScope(e):!1}},Hm=class{diagnostics=[];hostFunctions=new Map;knownHostReferences=new Map;options;functions=new Map;currentScope=new Xn;loopDepth=0;inFunction=!1;hasConcurrency=!1;usedGlobals=new Set;usedProperties=!1;loadedPackages=new Set;functionPackages=new WeakMap;recoverLabels=new Set;hasRecover=!1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recoverContexts=[];constructor(e,n={}){this.options=n;for(let[r,s]of e.entries())this.hostFunctions.set(r,s),this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.usedGlobals.clear(),this.usedProperties=!1,this.loadedPackages=new Set,this.functionPackages=new WeakMap,this.recoverLabels.clear(),this.hasRecover=!1,this.recoverContexts=[],this.recoverScopedReads=new WeakMap,this.recoverScopedWrites=new WeakMap,this.loopDepth=0,this.inFunction=!1,this.currentScope=new Xn,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,s]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof(s.signature?.publicArity??s.arity)=="number"?s.signature?.publicArity??s.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);this.checkRecoverSiblings(e.statements),this.collectKnownHostReferences(e);for(let r of e.statements)r.kind==="FunctionDeclStmt"?this.functionPackages.set(r,new Set(this.loadedPackages)):this.checkStmt(r);let n=this.loadedPackages;for(let r of e.statements)r.kind==="FunctionDeclStmt"&&(this.loadedPackages=this.functionPackages.get(r),this.checkStmt(r));return this.loadedPackages=n,this.diagnostics}collectKnownHostReferences(e){this.knownHostReferences.clear();let n=new Map,r=new Map,s=(a,l)=>{n.set(a,(n.get(a)??0)+1),l&&r.set(a,l)},i=a=>{if(!(!a||typeof a!="object")){if(a.kind==="AssignExpr")s(a.target,a.value);else if(a.kind==="VarDeclStmt")s(a.name,a.initializer);else if(a.kind==="TupleAssignExpr")for(let l of a.targets)s(l);else if(a.kind==="TupleVarDeclStmt")for(let l of a.names)s(l);else if(a.kind==="ForInStmt")s(a.name);else if(a.kind==="FunctionDeclStmt")for(let l of a.params)s(l);for(let l of Object.values(a))Array.isArray(l)?l.forEach(i):l&&typeof l=="object"&&i(l)}};i(e);let o=(a,l=new Set)=>{if(l.has(a))return;if(l.add(a),!n.has(a))return this.hostFunctions.get(a);if(n.get(a)!==1)return;let c=r.get(a);for(;c?.kind==="GroupingExpr";)c=c.expression;return c?.kind==="IdentifierExpr"?o(c.name,l):void 0};for(let a of n.keys()){let l=o(a);l&&this.knownHostReferences.set(a,l)}}addError(e,n,r,s){this.diagnostics.push({message:e,line:n,column:r,severity:"error",file:s})}isPropsBinding(e){return e==="PROPS"||e.endsWith(".PROPS")}checkReservedBinding(e,n){e.some(r=>r==="RESUMEPOINT"||r.endsWith(".RESUMEPOINT"))&&this.addError("'RESUMEPOINT' is reserved; rename this binding (RESUMEPOINT is read-only)",n.line,n.column,n.file)}checkRecoverSiblings(e){let n=!1;for(let r of e)r.kind==="RecoverStmt"&&(n&&this.addError("Only one recover statement is allowed in this statement list",r.line,r.column,r.file),n=!0)}isScopeOrAncestor(e,n){if(!n)return!1;let r=e;for(;r;){if(r===n)return!0;r=r.parent}return!1}noteRecoverWrite(e,n,r){let s=this.currentScope.resolvingScope(e),i=this.recoverContexts.find(o=>o.scope===s);if(i){if(r){let o=this.recoverScopedWrites.get(r);o||this.recoverScopedWrites.set(r,o=new Map),o.set(e,i.stmt)}if(!n){i.noInitializer.add(e);return}}if(n)for(let o of this.recoverContexts){if(!this.isScopeOrAncestor(o.scope,s))continue;let a=o.assigned.get(e);a||o.assigned.set(e,a=new Set),a.add(o.point)}}noteRecoverRead(e,n=e){let r=this.currentScope.resolvingScope(e.name),s=this.recoverContexts.find(i=>i.scope===r);s&&this.recoverScopedReads.set(n,s.stmt);for(let i of this.recoverContexts){if(!this.isScopeOrAncestor(i.scope,r))continue;let o=i.assigned.get(e.name);if(!o||o.has(i.point)||i.noInitializer.has(e.name)||i.warned.has(e.name))continue;i.warned.add(e.name);let a=[...o].sort((l,c)=>l-c).map(l=>i.points[l]).join(", ");this.diagnostics.push({severity:"warning",message:`Variable '${e.name}' read in resumepoint '${i.points[i.point]}' is assigned only in earlier resumepoint(s): ${a}; resuming here may skip initialization`,line:e.line,column:e.column,file:e.file})}}packageBindingCollision(e){return this.options.sourcePackages?.has(e.split(".").at(-1))??!1}collectFunction(e){for(let r of[e.name,...e.params])this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a function or parameter",e.line,e.column,e.file);if((this.isPropsBinding(e.name)||e.params.includes("PROPS"))&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name,...e.params],e),!e.isStdlib&&this.options.reservedFunctionPrefixes?.some(r=>e.name.startsWith(r))){this.addError(`Function name '${e.name}' uses a reserved built-in prefix`,e.line,e.column,e.file);return}if(this.functions.has(e.name)){let r=this.functions.get(e.name);if(r.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(r.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=r.file?`${r.file}:${r.line}`:`line ${r.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let n=new Set;for(let r of e.params)n.has(r)&&this.addError(`Duplicate parameter name '${r}' in function '${e.name}'`,e.line,e.column,e.file),n.add(r);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"PackageStmt":{(this.currentScope.parent||this.inFunction)&&this.addError("package must be the first file-level statement",e.line,e.column,e.file),(this.options.reservedFunctionPrefixes?.some(n=>e.name.startsWith(n))||this.options.builtinProviderNames?.includes(e.name))&&this.addError("Package name '"+e.name+"' uses a reserved built-in name/prefix",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),(e.name==="ARGV"||this.currentScope.resolve(e.name)||this.functions.has(e.name))&&this.addError("Package name collision: '"+e.name+"' is already a variable or function",e.line,e.column,e.file),this.loadedPackages.add(e.name);break}case"ImportStmt":{this.addError("Import must be at file top level; move the literal include before use",e.line,e.column,e.file);break}case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let n=this.currentScope,r=this.inFunction;this.inFunction=!0,this.currentScope=new Xn(n,!0);for(let i of e.params)this.currentScope.define(i);let s=this.loopDepth;this.loopDepth=0,this.checkRecoverSiblings(e.body.statements);for(let i of e.body.statements)this.checkStmt(i);this.loopDepth=s,this.inFunction=r,this.currentScope=n;break}case"VarDeclStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a variable",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.currentScope.hasInCurrent(e.name)&&!(this.options.builtinGlobals?.includes(e.name)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(e.name))&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer,!0),this.currentScope.define(e.name),this.currentScope.shadowedGlobals.add(e.name),this.noteRecoverWrite(e.name,e.initializer!==void 0&&e.initializer!==null);break}case"TupleVarDeclStmt":{e.names.some(n=>this.isPropsBinding(n))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.names,e),this.checkExpr(e.initializer);for(let n of e.names)this.packageBindingCollision(n)&&this.addError("Package name collision: '"+n+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.hasInCurrent(n)&&!(this.options.builtinGlobals?.includes(n)&&!this.currentScope.parent&&!this.currentScope.shadowedGlobals.has(n))&&this.addError(`Variable '${n}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(n),this.currentScope.shadowedGlobals.add(n),this.noteRecoverWrite(n,!0);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForInStmt":{this.packageBindingCollision(e.name)&&this.addError("Package name collision: '"+e.name+"' is a loop binding",e.line,e.column,e.file),this.isPropsBinding(e.name)&&this.addError("PROPS is a reserved read-only map binding",e.line,e.column,e.file),this.checkReservedBinding([e.name],e),this.checkExpr(e.iterable);let n=this.currentScope;if(this.currentScope=new Xn(n),this.currentScope.define(e.name),this.loopDepth++,e.body.kind==="BlockStmt")for(let r of e.body.statements)this.checkStmt(r);else this.checkStmt(e.body);this.loopDepth--,this.currentScope=n;break}case"ForStmt":{let n=s=>{if(!(!s||typeof s!="object")){if(s.kind==="CommandExpr"){let i=s;this.addError("command: not allowed in a loop header; assign argv before the loop",i.line,i.column,i.file);return}for(let i of Object.values(s))Array.isArray(i)?i.forEach(n):n(i)}};n(e.init);let r=this.currentScope;this.currentScope=new Xn(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,e.update&&this.checkExpr(e.update),this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value,!0);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let n=this.currentScope;this.currentScope=new Xn(n),this.checkRecoverSiblings(e.statements);for(let r of e.statements)this.checkStmt(r);this.currentScope=n;break}case"RecoverStmt":{this.hasRecover=!0,this.loopDepth>0&&this.addError("recover is not allowed lexically inside a loop body",e.line,e.column,e.file);let n=new Set;for(let i of e.points)n.has(i.name)&&this.addError(`Duplicate resumepoint '${i.name}'`,i.line,i.column,i.file),n.add(i.name),this.recoverLabels.add(i.name);let r=this.currentScope;this.currentScope=new Xn(r);let s={stmt:e,scope:this.currentScope,points:e.points.map(i=>i.name),point:0,assigned:new Map,noInitializer:new Set,warned:new Set};this.recoverContexts.push(s),e.points.forEach((i,o)=>{s.point=o,this.checkRecoverSiblings(i.statements);for(let a of i.statements)this.checkStmt(a)}),this.recoverContexts.pop(),this.currentScope=r;break}case"SyncAssignStmt":{this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value),this.noteRecoverWrite(e.target,!0,e);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let n=e.call;n.args.length===0&&this.addError(`Synchronized call '${n.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let r=this.hostFunctions.get(n.callee);(!r||!r.isContainerMutation)&&this.addError(`Synchronized call '${n.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr,e.expr.kind==="AssignExpr"||e.expr.kind==="CommandExpr"&&e.expr.mode==="system");break}}}checkReadPath(e){let n=e.args[0];for(;n.kind==="GroupingExpr";)n=n.expression;if(n.kind!=="PathLiteralExpr"){if(n.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof n.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!U.statSync(n.value).isFile())throw new Error("path is not a regular file");U.accessSync(n.value,U.constants.R_OK)}catch(r){this.addError(`Cannot read file ${JSON.stringify(n.value)}: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,e.file)}}}optionLiteral(e){if(e.kind==="GroupingExpr")return this.optionLiteral(e.expression);if(e.kind==="LiteralExpr")return{type:e.value===null?"null":typeof e.value,value:e.value};if(e.kind==="ArrayExpr"||e.kind==="TupleExpr")return{type:"list"};if(e.kind==="ObjectExpr")return{type:"map"};if(e.kind==="UnaryExpr"&&e.operator==="-"&&e.operand.kind==="LiteralExpr"&&typeof e.operand.value=="number")return{type:"number",value:-e.operand.value}}optionSuggestion(e,n){let r=a=>a.toLowerCase().replace(/[_-]/g,"");function s(a,l){let c=Array.from({length:l.length+1},(u,d)=>d);for(let u=1;u<=a.length;u++){let d=[u];for(let m=1;m<=l.length;m++)d[m]=Math.min(d[m-1]+1,c[m]+1,c[m-1]+(a[u-1]===l[m-1]?0:1));c=d}return c[l.length]}let i=n.filter(a=>a.name!=="*"),o=a=>{let l=r(e),c=r(a),u=0;for(;u<l.length&&u<c.length&&l[u]===c[u];)u++;return s(l,c)/Math.max(1,l.length,c.length)-u/Math.max(1,l.length)};return i.sort((a,l)=>o(a.name)-o(l.name)),i[0]?`; did you mean '${i[0].name}'?`:""}checkHostOptions(e,n){for(let[r,s]of n.entries()){if(!s.keys)continue;let i=e.args[r];for(;i?.kind==="GroupingExpr";)i=i.expression;if(i?.kind!=="ObjectExpr")continue;let o=new Set,a=s.open||s.keys.some(l=>l.name==="*"&&(l.type==="any"||l.type==="open"));for(let l of i.properties){let c=l.line??i.line,u=l.column??i.column,d=l.file??i.file;o.has(l.key)&&this.addError(`Duplicate option '${l.key}' in '${e.callee}' argument '${s.name}'`,c,u,d),o.add(l.key);let m=s.keys.find(g=>g.name===l.key);if(!m){a||this.addError(`Unknown option '${l.key}' in '${e.callee}' argument '${s.name}'${this.optionSuggestion(l.key,s.keys)}`,c,u,d);continue}let p=this.optionLiteral(l.value);if(!p||!m.type||m.type==="any"||m.type==="open")continue;let f=m.type.split("|").map(g=>g.trim().replace(/^array$/,"list").replace(/^object$/,"map")),h=["string","number","boolean","null","list","map"];f.every(g=>h.includes(g))&&!f.includes(p.type)&&this.addError(`Option '${l.key}' expects ${m.type}, got ${p.type}`,l.value.line,l.value.column,l.value.file),m.values&&p.type!=="list"&&p.type!=="map"&&!m.values.includes(p.value)&&this.addError(`Option '${l.key}' has a literal value outside its declared values`,l.value.line,l.value.column,l.value.file)}for(let l of s.keys)l.required&&l.name!=="*"&&!o.has(l.name)&&this.addError(`Missing required option '${l.name}' in '${e.callee}' argument '${s.name}'`,i.line,i.column,i.file)}for(let r=0;r<n.length;r++){let s=n[r];if(!s.checkLiteral||s.keys||s.rest)continue;let i=e.args[r];if(!i)continue;let o=this.optionLiteral(i);if(!o)continue;let a=s.type?.trim().toLowerCase();if(a&&a!=="any"&&a!=="json"&&a!=="open"){let l=a.split("|").map(u=>u.trim().replace(/^array$/,"list").replace(/^object$/,"map").replace(/^bool$/,"boolean")),c=["string","number","boolean","null","list","map"];l.every(u=>c.includes(u))&&!l.includes(o.type)&&this.addError(`Argument '${s.name}' in '${e.callee}' expects ${s.type}, got ${o.type}`,i.line,i.column,i.file)}s.values&&o.type!=="list"&&o.type!=="map"&&!s.values.some(l=>Object.is(l,o.value))&&this.addError(`Argument '${s.name}' in '${e.callee}' has a literal value outside its declared values`,i.line,i.column,i.file)}}checkPackageMember(e,n){let r=e.split(".")[0],s=this.options.sourcePackages?.get(r);if(!this.loadedPackages.has(r)&&this.currentScope.resolve(r)){this.addError("Map member calls are not supported; use a named function",n.line,n.column,n.file);return}if(!this.loadedPackages.has(r)){this.addError("package "+r+" not loaded: import it before use; import order matters, leaf packages first",n.line,n.column,n.file);return}s?.members.includes(e)||this.addError("Unknown package member '"+e+"'"+this.optionSuggestion(e,(s?.members??[]).map(i=>({name:i}))),n.line,n.column,n.file)}checkPropertyPath(e,n){let r;try{r=jm(e)}catch(l){this.addError(l.message,n.line,n.column,n.file);return}let s=this.options.propertyDeclarations;if(!s||(r=$l(r,s.known),s.known.includes(r)||s.closedTables?.includes(r)))return;let o=r.split(".")[0],a=this.optionSuggestion(r,s.known.map(l=>({name:l})));s.closedTables?.includes(o)&&this.addError(`Unknown property '${e}'${a}`,n.line,n.column,n.file)}checkExpr(e,n=!1){switch(e.kind){case"CommandExpr":e.words.length||this.addError("command: a program is required",e.line,e.column,e.file),n||this.addError("command: allowed only as a simple initializer, return value, or standalone system statement",e.line,e.column,e.file);for(let r of e.words)for(let s of r.pieces)typeof s!="string"&&this.checkExpr(s.expression);e.mode==="system"&&this.checkExpr({kind:"CallExpr",callee:"system",args:[{kind:"ArrayExpr",elements:[],line:e.line,column:e.column}],line:e.line,column:e.column,file:e.file});break;case"InterpolatedStringExpr":for(let r of e.parts)typeof r!="string"&&this.checkExpr(r.expression);break;case"LiteralExpr":break;case"MethodCallExpr":{if(e.receiver.kind==="IdentifierExpr"&&!e.receiver.name.includes(".")&&!this.currentScope.resolve(e.receiver.name)&&!this.functions.has(e.receiver.name)){let s=e.receiver.name+"."+e.method;Object.hasOwn(ko,s)&&!this.options.sourcePackages?.has(e.receiver.name)?this.addError(si(s),e.receiver.line,e.receiver.column,e.file):(this.addError("Call to undefined function '"+s+"'",e.receiver.line,e.receiver.column,e.file),this.checkPackageMember(s,e.receiver));for(let i of e.args)this.checkExpr(i);break}this.checkExpr(e.receiver);let r=yl(e.method);if(!r.length)this.addError("unknown method '"+e.method+"'; methods: "+am(),e.line,e.column,e.file);else{let s=$_(e.method);s.includes(e.args.length)||this.addError("method "+e.method+"() expects "+s.join(" or ")+" argument"+(s.length===1&&s[0]===1?"":"s")+", received "+e.args.length+"; signatures: "+r.join(", "),e.line,e.column,e.file)}for(let s of e.args)this.checkExpr(s);break}case"PathLiteralExpr":{let r=this.options.hostContext?.platform??this.options.platform??process.platform,s;try{s=sm(e.mode,e.raw,r)}catch(i){if(!(i instanceof sn))throw i;this.addError(i.message,e.line,e.column,e.file);break}if(this.options.checkPaths){let i=M_(e.mode,e.raw,s,this.options.hostContext?.cwd??process.cwd(),r,this.options.pathAccess??im);i&&this.addError(i,e.line,e.column,e.file)}break}case"DataBlockExpr":{let r=El[e.marker],s="_"+e.marker+"_",i=!1;for(let a of e.options){let l=r[a.name];if(!l)this.addError(s+": unknown option '"+a.name+"'"+(Object.keys(r).length?this.optionSuggestion(a.name,Object.keys(r).map(c=>({name:c})))+"; known options: "+Object.keys(r).join(", "):"; "+s+" takes no options"),a.line,a.column,a.file);else{let c=this.optionLiteral(a.value);c?c.type!==l.type&&(i=!0,this.addError(s+": option '"+a.name+"' must be a "+l.type+"; found "+c.type,a.line,a.column,a.file)):i=!0}this.checkExpr(a.value)}let o=0;for(let a of e.lines)for(let l of a.pieces)typeof l!="string"&&(o++,this.checkExpr(l.expression));if(e.closed&&!i&&!e.options.some(a=>!r[a.name]))for(let a of sv(e.marker,Nv(e),new Array(o).fill(it),Pm(e,l=>this.optionLiteral(l.value).value))){let l=Ov(e,a);this.addError(Wn[e.marker]+": "+a.message,l.line,l.column,e.file)}break}case"IdentifierExpr":{if(e.name.includes(".")){this.checkPackageMember(e.name,e),this.loadedPackages.has(e.name.split(".")[0])&&!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError("Package variable '"+e.name+"' used before declaration",e.line,e.column,e.file);break}(e.name==="PROPS"||e.name==="expand"||hv.includes(e.name))&&(this.usedProperties=!0);let r=this.currentScope.resolvingScope(e.name);r&&!r.parent&&this.options.globals?.includes(e.name)&&this.usedGlobals.add(e.name),this.noteRecoverRead(e),!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(Object.hasOwn(ko,e.name)?si(e.name,"Undeclared variable"):this.options.propertyDeclarations?.removedGlobals?.[e.name]?`'${e.name}' was replaced by ${this.options.propertyDeclarations.removedGlobals[e.name]}; declare a local variable if intended`:`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.packageBindingCollision(e.target)&&this.addError("Package name collision: '"+e.target+"' is a variable",e.line,e.column,e.file),e.target.includes(".")&&this.checkPackageMember(e.target,e),this.isPropsBinding(e.target)&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding([e.target],e),this.checkExpr(e.value,n&&e.value.kind!=="AssignExpr"),this.currentScope.resolveInScope(e.target)||this.currentScope.define(e.target),this.currentScope.resolvingScope(e.target)?.shadowedGlobals.add(e.target),this.noteRecoverWrite(e.target,!0,e);break}case"TupleAssignExpr":{e.targets.some(r=>this.isPropsBinding(r))&&this.addError("PROPS is read-only; use set_property",e.line,e.column,e.file),this.checkReservedBinding(e.targets,e),this.checkExpr(e.value);for(let r of e.targets)this.packageBindingCollision(r)&&this.addError("Package name collision: '"+r+"' is a tuple binding",e.line,e.column,e.file),this.currentScope.resolveInScope(r)||this.currentScope.define(r),this.currentScope.resolvingScope(r)?.shadowedGlobals.add(r),this.noteRecoverWrite(r,!0,e);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"ConditionalExpr":{this.checkExpr(e.condition),this.checkExpr(e.trueArm),this.checkExpr(e.falseArm);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{let r=Ul(e);r&&this.checkPropertyPath(r,e),this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{if(e.callee==="system"){let a=l=>l.kind==="LiteralExpr"?typeof l.value=="string":l.kind==="InterpolatedStringExpr"?!0:l.kind==="GroupingExpr"?a(l.expression):l.kind==="BinaryExpr"&&l.operator==="+"?a(l.left)||a(l.right):!1;e.args[0]&&a(e.args[0])&&this.addError("command: system(string) is not supported; write system PROGRAM ARGS or system([program, args...]); for an explicit shell invoke bash -c with a script field",e.line,e.column,e.file)}if(e.callee.includes(".")&&(Object.hasOwn(ko,e.callee)&&!this.options.sourcePackages?.has(e.callee.split(".")[0])?this.addError(si(e.callee),e.line,e.column,e.file):this.checkPackageMember(e.callee,e)),hv.includes(e.callee)&&(this.usedProperties=!0,e.args[0]?.kind==="LiteralExpr"&&typeof e.args[0].value=="string"&&e.args[0].value!==""&&this.checkPropertyPath(e.args[0].value,e.args[0])),e.callee==="expand"){let a=e.args[0];if(a?.kind==="LiteralExpr"&&typeof a.value=="string")try{let l=vo(a.value),c=e.args[1];for(;c?.kind==="GroupingExpr";)c=c.expression;let u=e.args[1]?c?.kind==="ObjectExpr"?new Set(c.properties.map(m=>m.key)):void 0:new Set,d=new Set;for(let m of l)typeof m!="string"&&(m.kind==="property"?(this.usedProperties=!0,this.checkPropertyPath(m.key,a)):m.kind==="variable"&&u&&!u.has(m.name)&&d.add(m.name));if(d.size){let m=[...d].map(p=>`${p} (not defined)`).join("; ");this.addError(`expand: missing references: ${m}; assign a temporary variable first and pass it in vars.`,a.line,a.column,a.file)}}catch(l){this.addError(l.message,a.line,a.column,a.file)}else this.usedProperties=!0}let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(si(e.callee),e.line,e.column,e.file);let s=this.hostFunctions.get(e.callee)??this.knownHostReferences.get(e.callee),i=a=>{if(a.kind==="AssignExpr")return a.target==="dryrun"||i(a.value);if(a.kind==="TupleAssignExpr")return a.targets.includes("dryrun")||i(a.value);for(let l of Object.values(a))if(l&&typeof l=="object"&&(Array.isArray(l)?l.some(c=>c&&typeof c=="object"&&i(c)):i(l)))return!0;return!1};(s||!r||r.isHost)&&e.args.some(i)&&this.addError(`dryrun is supplied by the language; omit it from '${e.callee}' arguments`,e.line,e.column,e.file);let o=s?.signature?.publicArity??s?.arity;!r&&typeof o=="number"&&e.args.length!==o&&this.addError(`Function '${e.callee}' expects ${o} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),typeof o=="object"&&(e.args.length<o.min||e.args.length>(o.max??1/0))&&this.addError(`Function '${e.callee}' expects ${o.min}..${o.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),(this.hostFunctions.has(e.callee)||s?.signature?.dryrunIndex!==void 0)&&(s?.signature?.publicParams?this.checkHostOptions(e,s.signature.publicParams):s?.params&&this.checkHostOptions(e,s.params)),this.options.checkFiles&&s?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let a of e.args)this.checkExpr(a);r||this.noteRecoverRead({...e,kind:"IdentifierExpr",name:e.callee},e);break}}}};ze=class{value;constructor(e){this.value=e}},ot=class{},at=class{},Vn=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},gt=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionScope;constructor(e,n=!1){this.parent=e,this.isFunctionScope=n}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,n){this.values.set(e,n)}ownBindings(){return this.values.entries()}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}hasInScope(e){return this.values.has(e)?!0:this.isFunctionScope?!1:this.parent?this.parent.hasInScope(e):!1}writeTarget(e){return this.values.has(e)?this:!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)?this.parent.writeTarget(e):this}set(e,n){if(this.values.has(e)){this.values.set(e,n);return}if(!this.isFunctionScope&&this.parent&&this.parent.hasInScope(e)){this.parent.set(e,n);return}this.values.set(e,n)}},Bl=class{holderTaskId;depth=0;waiters=[];acquire(e=0,n=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((r,s)=>{let i;n>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${n}ms (possible deadlock)`)))},n));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,r()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,n=0,r=1e4){await this.acquire(n,r);try{return await e()}finally{this.release()}}},qm=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let n=this.bindingLocks.get(e);return n||(n=new Bl,this.bindingLocks.set(e,n)),n}getObjectLock(e){let n=this.objectLocks.get(e);return n||(n=new Bl,this.objectLocks.set(e,n)),n}},Ee=Object.freeze({readonly:!0}),EL=t=>{for(let e of Object.values(t))Object.freeze(e);return Object.freeze(t)},Xm=EL({warning:{readonly:!0,control:"warning",dummyType:"string"},which:Ee,get_property:Ee,has_property:Ee,get_properties:Ee,expand:Ee,set_property:{dummyType:"null"},read:Ee,read_file:Ee,read_lines:{readonly:!0,dummyType:"array"},read_json:{readonly:!0,dummyType:"map"},read_csv:{readonly:!0,dummyType:"array"},file_exists:{readonly:!0,dummyType:"boolean"},glob:{readonly:!0,dummyType:"array"},list_dir:{readonly:!0,dummyType:"array"},read_tree:{readonly:!0,dummyType:"array"},csv_parse:{readonly:!0,dummyType:"array"},csv_stringify:{readonly:!0,dummyType:"string"},basename:{readonly:!0,dummyType:"string"},dirname:{readonly:!0,dummyType:"string"},path_join:{readonly:!0,dummyType:"string"},abs_path:{readonly:!0,dummyType:"string"},write:{dummyType:"boolean"},write_file:{dummyType:"boolean"},write_file_exclusive:{dummyType:"boolean"},write_files:{dummyType:"map"},write_lines:{dummyType:"boolean"},write_json:{dummyType:"boolean"},write_csv:{dummyType:"boolean"},append_file:{dummyType:"boolean"},delete_file:{dummyType:"boolean"},remove_file:{dummyType:"boolean"},mkdir:{dummyType:"boolean"},rmdir:{dummyType:"boolean"},copy_file:{dummyType:"boolean"},move_file:{dummyType:"boolean"},temp_file:{dummyType:"null"},env:{readonly:!0,frozen:"env"},getenv:{readonly:!0,frozen:"env"},set_env:{dummyType:"boolean"},list:{readonly:!0,dummyType:"array"},array:{readonly:!0,dummyType:"array"},push:Ee,pop:Ee,shift:Ee,unshift:Ee,insert:Ee,remove_at:Ee,concat:{readonly:!0,dummyType:"array"},reverse:{readonly:!0,dummyType:"array"},sort:{readonly:!0,dummyType:"array"},unique:{readonly:!0,dummyType:"array"},flatten:{readonly:!0,dummyType:"array"},first:Ee,last:Ee,sum:{readonly:!0,dummyType:"number"},avg:{readonly:!0,dummyType:"number"},map:{readonly:!0,dummyType:"map"},hash:{readonly:!0,dummyType:"map"},from_entries:{readonly:!0,dummyType:"map"},clear:Ee,size:{readonly:!0,dummyType:"number"},len:{readonly:!0,dummyType:"number"},keys:{readonly:!0,dummyType:"array"},values:{readonly:!0,dummyType:"array"},entries:{readonly:!0,dummyType:"array"},items:{readonly:!0,dummyType:"array"},has_key:{readonly:!0,dummyType:"boolean"},get:Ee,getstr:{readonly:!0,dummyType:"string"},getnum:{readonly:!0,dummyType:"number"},getbool:{readonly:!0,dummyType:"boolean"},getlist:{readonly:!0,dummyType:"array"},set:Ee,delete_key:Ee,merge:{readonly:!0,dummyType:"map"},clone:Ee,pluck:{readonly:!0,dummyType:"array"},filter_by:{readonly:!0,dummyType:"array"},find_by:Ee,json_parse:Ee,json_parse_safe:Ee,json_stringify:{readonly:!0,dummyType:"string"},regex_test:{readonly:!0,dummyType:"boolean"},regex_match:{readonly:!0,dummyType:"array"},regex_find_all:{readonly:!0,dummyType:"array"},regex_replace:{readonly:!0,dummyType:"string"},split_regex:{readonly:!0,dummyType:"array"},split:{readonly:!0,dummyType:"array"},lines:{readonly:!0,dummyType:"array"},last_line_as_status:Ee,parse_file_blocks:{readonly:!0,dummyType:"array"},format_file_blocks:{readonly:!0,dummyType:"string"},kv_from_last_paragraph:{readonly:!0,dummyType:"map"},split_command:{readonly:!0,dummyType:"array"},words:{readonly:!0,dummyType:"array"},join:{readonly:!0,dummyType:"string"},trim:{readonly:!0,dummyType:"string"},strip:{readonly:!0,dummyType:"string"},trim_start:{readonly:!0,dummyType:"string"},lstrip:{readonly:!0,dummyType:"string"},trim_end:{readonly:!0,dummyType:"string"},rstrip:{readonly:!0,dummyType:"string"},to_upper:{readonly:!0,dummyType:"string"},upper:{readonly:!0,dummyType:"string"},to_lower:{readonly:!0,dummyType:"string"},lower:{readonly:!0,dummyType:"string"},upper_first:{readonly:!0,dummyType:"string"},title_case:{readonly:!0,dummyType:"string"},contains:{readonly:!0,dummyType:"boolean"},includes:{readonly:!0,dummyType:"boolean"},starts_with:{readonly:!0,dummyType:"boolean"},startswith:{readonly:!0,dummyType:"boolean"},ends_with:{readonly:!0,dummyType:"boolean"},endswith:{readonly:!0,dummyType:"boolean"},index_of:{readonly:!0,dummyType:"number"},last_index_of:{readonly:!0,dummyType:"number"},count_matches:{readonly:!0,dummyType:"number"},substr:{readonly:!0,dummyType:"string"},substring:{readonly:!0,dummyType:"string"},slice:Ee,char_at:{readonly:!0,dummyType:"string"},char_code:{readonly:!0,dummyType:"number"},from_char_code:{readonly:!0,dummyType:"string"},replace:{readonly:!0,dummyType:"string"},replace_all:{readonly:!0,dummyType:"string"},repeat:{readonly:!0,dummyType:"string"},pad_start:{readonly:!0,dummyType:"string"},pad_end:{readonly:!0,dummyType:"string"},reverse_str:{readonly:!0,dummyType:"string"},is_empty:{readonly:!0,dummyType:"boolean"},is_digit:{readonly:!0,dummyType:"boolean"},is_alpha:{readonly:!0,dummyType:"boolean"},is_alnum:{readonly:!0,dummyType:"boolean"},is_array:{readonly:!0,dummyType:"boolean"},is_string:{readonly:!0,dummyType:"boolean"},is_number:{readonly:!0,dummyType:"boolean"},is_map:{readonly:!0,dummyType:"boolean"},is_function:{readonly:!0,dummyType:"boolean"},format:{readonly:!0,dummyType:"string"},sprintf:{readonly:!0,dummyType:"string"},cmd_render:{readonly:!0,dummyType:"string"},range:{readonly:!0,dummyType:"array"},abs:{readonly:!0,dummyType:"number"},min:{readonly:!0,dummyType:"number"},max:{readonly:!0,dummyType:"number"},floor:{readonly:!0,dummyType:"number"},ceil:{readonly:!0,dummyType:"number"},round:{readonly:!0,dummyType:"number"},sqrt:{readonly:!0,dummyType:"number"},pow:{readonly:!0,dummyType:"number"},sha256:{readonly:!0,dummyType:"string"},now:{readonly:!0,dummyType:"number",frozen:"now"},timestamp:{readonly:!0,dummyType:"number",frozen:"timestamp"},date:{readonly:!0,dummyType:"string",frozen:"date"},strftime:{readonly:!0,dummyType:"string"},coalesce:Ee,if_null:Ee,if_else:Ee,str:{readonly:!0,dummyType:"string"},num:{readonly:!0,dummyType:"number"},type:{readonly:!0,dummyType:"string"},require:{readonly:!0,control:"require"},assert:{readonly:!0,control:"assert"},error:{readonly:!0,control:"error",dummyType:"string"},exit:{readonly:!0,control:"exit",dummyType:"null"},print:{control:"print",dummyType:"string",taints:!1},println:{control:"println",dummyType:"string",taints:!1},printf:{control:"printf",dummyType:"string",taints:!1},system:{dummyType:"SystemResult",process:!0},run_script:{dummyType:"map",dummyValue:()=>({success:!0,stdout:"",output:[],exit_code:0,code:0,value:null,errors:[]})},http_get:{dummyType:"string"},random:{dummyType:"number"},sleep_ms:{dummyType:"null"},prompt_human:{dummyType:"null"},prompt_human_config:{dummyType:"map"}}),TL={stdout:"",stderr:"",code:0,signal:null,timed_out:!1,duration_ms:0,pid:null,dry:!0};qe=Symbol("core dry policy"),Gm=Symbol("dry invocation"),Jm=Symbol("implicit preflight work limit"),Vm=Symbol("implicit preflight stdout");Kt=class extends Error{isControlFlow=!0;exitCode=0};Hl=class{entries=[];lastSite={line:1,column:1};failure;recordedDiagnostics=[];recordError(e,n=this.lastSite){this.sealed||(this.check(),this.recordedDiagnostics.push({...n,severity:"error",message:e}))}scriptExit;sealed=!1;loopLimit;platform;timeout;deadline=1/0;wallClock;environment;planBytes=0;work=0;workLimit;replay;cleanups=new Map;own(e){this.cleanups.has(e)||this.cleanups.set(e,{started:!1})}dispose(e){this.own(e);let n=this.cleanups.get(e);return n.started||(n.started=!0,n.value=e.dispose(),lt(n.value)&&Promise.resolve(n.value).catch(()=>{})),n.value}controller=new AbortController;truncation;onStart;start(){Number.isFinite(this.deadline)||(this.deadline=performance.now()+this.timeout,this.onStart?.())}constructor(e={}){if(this.replay=e[Vm],this.workLimit=e[Jm]??1/0,this.platform=e.hostContext?.platform??e.platform??process.platform,this.wallClock=e.dryrunClockMs??Date.now(),!Number.isFinite(this.wallClock))throw Error("Dry wall clock must be finite");this.environment=Object.freeze(Object.assign(Object.create(null),e.hostContext?.env??process.env)),this.loopLimit=e.dryLoopLimit??10,this.timeout=e.dryrunTimeoutMs??5e3;for(let n of[this.loopLimit,this.timeout])if(!Number.isSafeInteger(n)||n<=0)throw Error("Dry bounds must be positive safe integers")}hasTaintedValues=!1;get tainted(){return this.hasTaintedValues}at(e){this.lastSite={file:e.file,line:e.line,column:e.column},++this.work>this.workLimit&&this.truncate("work budget exceeded"),this.check()}check(){if(this.truncation)throw new Kt(this.truncation);if(this.sealed)throw new Kt("Dry pass finished");performance.now()>=this.deadline&&this.truncate("time budget exceeded")}truncate(e){this.truncation??="dry run truncated: "+e,this.sealed=!0,this.controller.abort();for(let n of[...this.cleanups.keys()].reverse())try{this.dispose(n)}catch{}throw new Kt(this.truncation)}async wait(e){let n=Promise.resolve(e);n.catch(()=>{}),this.check();let r;try{let s=await Promise.race([n,new Promise((i,o)=>{let a=()=>{r&&(clearTimeout(r),r=void 0);let l=this.deadline-performance.now();if(l<=0)try{this.truncate("time budget exceeded")}catch(c){o(c)}else r=setTimeout(a,Math.min(2147483647,Math.max(1,l)))};this.onStart=a,a()})]);return this.check(),s}finally{r&&clearTimeout(r),this.onStart=void 0}}loop(e,n){return this.at(n),e<this.loopLimit?!1:(this.append({seq:this.entries.length+1,kind:"loop",file:n.file??"<main>",line:n.line,column:n.column,iterations:e,limit:this.loopLimit,message:"loop truncated at "+this.loopLimit,simulated:!1}),this.hasTaintedValues=!0,!0)}propertyView;propertyLoads=[];prepareProperties(e){if(e&&["Directory","NonInteractive"].includes(e.split(".")[0]))return;let n=this.propertyLoads.map(r=>r());return n.some(lt)?Promise.all(n):void 0}fail(e,n=this.lastSite){throw this.check(),this.failure??={site:{...n},message:e,untrusted:this.tainted},new Kt(e)}finishExit(e,n=this.lastSite){this.scriptExit??={site:{...n},code:e}}captureFailure(e,n=this.lastSite){if(this.truncation)return;if(performance.now()>=this.deadline){try{this.truncate("time budget exceeded")}catch{}return}let r=SL(e);if(r!==void 0){this.finishExit(r,n);return}if(e?.isControlFlow&&e?.resourceFailure===void 0)return;let s=e instanceof P?{file:e.file,line:e.line,column:e.column}:n;this.failure??={site:{...s},message:e instanceof Error?e.message:String(e),untrusted:this.tainted}}captureOutput(e,n){if(!this.replay)return;this.check();let r=Buffer.byteLength(n)+Buffer.byteLength(this.lastSite.file??"")+32;this.planBytes+r>1024*1024-4096&&this.truncate("console output size exceeded"),this.planBytes+=r,this.replay.push({name:e,text:n,site:{...this.lastSite},raw:e==="printf"})}record(e,n,r,s,i,o=!0){this.sealed||(this.check(),this.append({seq:this.entries.length+1,kind:s,file:r.file??"<main>",line:r.line,column:r.column,function:e,arguments:n,simulated:!0,...i?{argv:[...i],renderedArgv:rp(i,this.platform==="win32"?"windows":"posix"),dialect:this.platform==="win32"?"windows":"posix"}:{}}),this.hasTaintedValues||=o)}snapshot(e){let n=new Map,r=new Map,s=0,i=a=>{s+=a,this.check(),s+this.planBytes>1024*1024-4096&&this.truncate("plan size exceeded")},o=(a,l,c)=>{if(i(8),c>256&&this.truncate("plan size traversal depth exceeded"),a===null||typeof a=="boolean")return a;if(typeof a=="string")return i(Buffer.byteLength(a)),a;if(typeof a=="number")return Number.isFinite(a)?a:{$type:String(a)};if(typeof a=="bigint"){let g=String(a);return i(g.length),{$type:"bigint",value:g}}if(typeof a=="symbol"){r.has(a)||r.set(a,r.size+1);let g=String(a);return i(Buffer.byteLength(g)),{$type:"symbol",id:r.get(a),value:g}}if(typeof a>"u"||typeof a=="function")return{$type:typeof a};if(Oe(a))return{$type:"resource"};if(Jn.has(a)&&(a=gs(a)),Se.isProxy(a))return{$type:"proxy"};let u=ap(a);if(u)return{$type:Se.isMap(a)?"Map":Se.isSet(a)?"Set":Se.isDate(a)?"Date":Se.isRegExp(a)?"RegExp":Se.isNativeError(a)?"Error":Se.isArrayBufferView(a)?"TypedArray":u};if(n.has(a))return{$ref:n.get(a)};n.set(a,l),Array.isArray(a)&&i(a.length);let d=Array.isArray(a)?new Array(a.length):{},m=Reflect.ownKeys(a);i(m.length*8);let p=Array.isArray(a),f=m.some(g=>typeof g=="symbol"||g==="$ref"||g==="$type"||p&&g!=="length"&&!(/^(0|[1-9][0-9]*)$/.test(g)&&Number(g)<a.length)),h=[];for(let g of m.filter(y=>y!=="length"||!Array.isArray(a)).sort((y,b)=>String(y)<String(b)?-1:String(y)>String(b)?1:0)){let y=typeof g=="symbol"?"symbol:"+h.length:g;i(Buffer.byteLength(y));let b=Object.getOwnPropertyDescriptor(a,g),_="value"in b?o(b.value,f?l+"/properties/"+h.length+"/1":l+"/"+y.replaceAll("~","~0").replaceAll("/","~1"),c+1):{$type:"accessor"};f?h.push([typeof g=="symbol"?o(g,l+"/properties/"+h.length+"/0",c+1):g,_]):Object.defineProperty(d,y,{value:_,enumerable:!0,writable:!0,configurable:!0})}return f?{$type:p?"array":"object",...p?{length:a.length}:{},properties:h}:d};return o(e,"$",0)}append(e){let n=Buffer.byteLength(JSON.stringify(e))+1;this.planBytes+n>1024*1024-4096&&this.truncate("plan size exceeded"),this.planBytes+=n,this.entries.push(e)}capture(e){if(this.truncation)return;let n=e.diagnostics;if(!this.failure){let r=n.find(s=>s.severity==="error");r&&(this.failure={site:r,message:r.message,untrusted:this.tainted})}!this.failure&&!this.scriptExit&&e.exitCode&&e.exitCode!==0&&(this.failure={site:this.lastSite,message:"exit("+e.exitCode+")",untrusted:this.tainted})}report(e){let n=[...e.diagnostics];this.capture(e);let r=[...this.recordedDiagnostics];for(let l of e.errors??[])r.some(c=>c.message===l)||r.push({...this.lastSite,severity:"error",message:l});if(this.sealed=!0,this.truncation&&!this.failure)return Om({version:1,status:"truncated",entries:this.entries,stop:{file:this.lastSite.file??"<main>",line:this.lastSite.line,column:this.lastSite.column,reason:this.truncation},diagnostics:[...r,...n.filter(l=>l.severity!=="error"),{...this.lastSite,severity:"warning",message:this.truncation}],exitCode:0});if(!this.failure){let l=this.scriptExit?{file:this.scriptExit.site.file??"<main>",line:this.scriptExit.site.line,column:this.scriptExit.site.column,reason:"script exit with code "+this.scriptExit.code}:null;return Om({version:1,status:this.scriptExit?"complete":this.entries.some(c=>c.kind==="loop")?"loop-limited":"complete",entries:this.entries,stop:l,diagnostics:[...r,...n],exitCode:0})}let{site:s,message:i,untrusted:o}=this.failure,a=o?"needs a real result: "+i:i;return Om({version:1,status:o?"needs-real-result":"failed",entries:this.entries,stop:{file:s.file??"<main>",line:s.line,column:s.column,reason:a},diagnostics:[...r,...!o&&n.some(l=>l.severity==="error")?n:[...n.filter(l=>l.severity!=="error"),{...s,severity:o?"warning":"error",message:a}]],exitCode:o?0:2})}};kL=new Set(["read","read_file","read_lines","read_json","read_csv"]);Ym=new WeakMap,Ro=class{constructor(e){Ym.set(this,e)}},xL=5e3;IL=1,Qm=class{id;constructor(e){Kv++,zv.add(this),Object.defineProperty(this,"id",{value:e,enumerable:!0}),Object.freeze(this)}},Kv=0;zv=new WeakSet;Rv=new WeakMap,Yv=1e7;xo=class{failure;records=[];label;parent;base;constructor(e,n,r){this.label=e,this.parent=n,this.base=r}isAncestorOf(e){for(let n=e.parent;n;n=n.parent)if(n===this)return!0;return!1}},Qv=new xv;Zm=class{token=`run-${process.pid}-${IL++}`;root=new xo("root");ordinal=0;terminating=!1;records=new WeakMap;ordered=[];rawRecords=new WeakMap;scopes=new WeakMap;onFailure;defaultDeadlineMs;failures=[];constructor(e,n={}){this.onFailure=e;let r=n.defaultDeadlineMs;this.defaultDeadlineMs=typeof r=="number"&&Number.isFinite(r)&&r>0?r:xL}scopeFor(e){for(let n=e;n;n=n.isFunctionScope?void 0:n.parent){let r=this.scopes.get(n);if(r)return r}return this.root}enterScope(e,n,r){let s=new xo(r,n);return this.scopes.set(e,s),s}temporaryScope(e,n,r){return new xo(n,e,r)}register(e,n,r,s){let i=String(e.id),o={handle:new Qm(i),raw:e,kind:typeof e.kind=="string"&&e.kind?e.kind:n,id:i,site:r,ordinal:++this.ordinal,owner:s,state:"open",adoptable:!0,unresolved:!1};return Rv.set(o.handle,`${o.kind} ${o.id}`),this.records.set(o.handle,o),this.rawRecords.set(e,o),this.ordered.push(o),s.records.push(o),o.handle}terminate(){if(!this.terminating){this.terminating=!0;for(let e of[...this.ordered].sort((n,r)=>r.ordinal-n.ordinal))if(!(e.state==="closed"||e.state==="close_failed"))try{typeof e.raw.finalizeSync=="function"&&(e.raw.finalizeSync(),e.state="closed")}catch(n){this.fail(e,"critical finalization failed: "+String(n))}}}authorizeRaw(e,n,r,s=!1){let i=e!==null&&typeof e=="object"?this.rawRecords.get(e):void 0;if(!i)throw Error("Resource "+String(e?.kind??"batch")+" "+String(e?.id)+" belongs to another run: "+r);if(i.owner!==n&&!i.owner.isAncestorOf(n))throw Error("Resource "+i.kind+" "+i.id+" is not authorized in this borrower scope: "+r);if(!s&&i.state!=="open")throw Error("Resource "+i.kind+" "+i.id+" is closed: "+r);return i}lookup(e){return this.records.get(e)}describe(e){let n=this.records.get(e);return n?`${n.kind} ${n.id}`:`${Rv.get(e)??e.id} (from another run)`}borrow(e){if(Oe(e)){let n=this.records.get(e);n&&(n.adoptable=!1)}}bind(e,n,r){if(!Oe(e))return;let s=this.records.get(e);if(!s)return`resource ${e.id} belongs to another run`;let i=this.scopeFor(n);if(s.adoptable){s.adoptable=!1,i!==s.owner&&(s.owner.records.splice(s.owner.records.indexOf(s),1),i.records.push(s),s.owner=i);return}if(i!==s.owner&&i.isAncestorOf(s.owner))return`resource ${s.kind} ${s.id} cannot escape its owner into the longer-lived binding '${r}'`}close(e,n){if(e.closing)return e.closing;e.state="closing";let r=e.raw,s=r.closeDeadlineMs,i=typeof s=="number"&&Number.isFinite(s)&&s>0?s:this.defaultDeadlineMs,o=performance.now(),a;e.closing=new Promise(c=>{a=c});let l=`close did not finish within its ${i} ms deadline`;return(async()=>{let c,u=!1;try{let d=r.close({reason:this.terminating?"cancelled":e.owner.failure!==void 0?"error":"done",error:e.owner.failure instanceof Error?e.owner.failure.message:e.owner.failure==null?void 0:String(e.owner.failure),explicit:n});if(lt(d)){let m=Promise.resolve(d).then(()=>!0);m.catch(()=>{});let p=i-(performance.now()-o);if(!(p>0&&await Promise.race([m,new Promise(h=>{c=setTimeout(()=>h(!1),p)})]))){this.critical(e),u=this.fail(e,l);return}}if(performance.now()-o>i){this.critical(e),u=this.fail(e,l);return}if(this.terminating&&e.state==="close_failed")return;e.state="closed",u=!0}catch(d){u=this.fail(e,d instanceof Error?d.message:String(d))}finally{c&&clearTimeout(c),a(u)}})(),e.closing}critical(e){try{typeof e.raw.finalizeSync=="function"&&e.raw.finalizeSync()}catch(n){this.report(`resource ${e.kind} ${e.id} (${e.site}): critical finalization failed: ${n instanceof Error?n.message:String(n)}`)}}fail(e,n){return e.state="close_failed",e.unresolved=!0,this.report(`resource close failed: ${e.kind} ${e.id} (${e.site}): ${n}`),!1}report(e){this.failures.push(e);try{this.onFailure(e)}catch{}}async drain(e){for(let n of[...e.records].sort((r,s)=>s.ordinal-r.ordinal))if(!(n.state==="closed"||n.state==="close_failed"))try{await this.close(n)}catch{}}snapshot(){return this.ordered.map(e=>({id:e.id,kind:e.kind,owner:e.owner.label,site:e.site,state:e.state,unresolved:e.unresolved,ordinal:e.ordinal}))}},Wl=class{nativeImports;executionOrigin;processContext;warningDiagnostics=[];dry;tracer;platform;abortSignal;resources;resourcesEnabled;temporaryScopes=new Map;globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new qm;isAsync;nextTaskId=1;recoverScopedReads=new WeakMap;recoverScopedWrites=new WeakMap;recovery;initialGlobals;callDepth=0;noPreflight;asyncCallDepth=new Map;recordedErrors;promptHumanConfig;childEngineFactory;compileOptions;constructor(e,n=(m,p)=>{p?process.stdout.write(m):console.log(m)},r=!1,s,i,o,a=Eo(void 0),l=process.platform,c,u=!1,d){this.nativeImports=d,this.dry=c,this.noPreflight=u,this.platform=l,this.recovery=a,this.recordedErrors=a.errors,this.stdout=n,this.stderr=i,this.isAsync=r,this.initialGlobals=s,this.globalEnv=new gt,this.hostFunctions=new Map(e),this.promptHumanConfig=o??{mode:"interactive"},this.resourcesEnabled=[...this.hostFunctions.values()].some(R=>R.returnsResource===!0),this.resources=new Zm(R=>{Nl(this.recovery,R);try{this.stderr?.(`error: ${R}`)}catch{}});let m=e.get("print");(!m||m.isDefault)&&this.hostFunctions.set("print",{...m,fn:(...R)=>{let N=m?.signature?.dryrunIndex===0?R.shift()===!0:!1,O=R.map(A=>typeof A=="object"?JSON.stringify(A):String(A)).join(" ");return N||this.stdout(O),O},arity:m?.signature?.nativeArity??m?.arity??{min:0},description:m?.description??"Prints formatted values to output log",isDefault:!0});let p=e.get("println");(!p||p.isDefault)&&this.hostFunctions.set("println",{...p,fn:(...R)=>{let N=p?.signature?.dryrunIndex===0?R.shift()===!0:!1,O=R.map(A=>typeof A=="object"?JSON.stringify(A):String(A)).join(" ");return N||this.stdout(O),O},arity:p?.signature?.nativeArity??p?.arity??{min:0},description:p?.description??"Prints line to output log",isDefault:!0});let f=e.get("printf");(!f||f.isDefault)&&this.hostFunctions.set("printf",{...f,fn:(...R)=>{let N=f?.signature?.dryrunIndex===0?R.shift()===!0:!1,[O,...A]=R,w=Ll(O,A,"printf");return N||this.stdout(w,!0),w},arity:f?.signature?.nativeArity??f?.arity??{min:2},description:f?.description??"Formats and prints %s, %d, %f and %% using sprintf rules",isDefault:!0});let h=e.get("require");(!h||h.isDefault)&&this.hostFunctions.set("require",{...h,fn:(R,N)=>np(R,N,O=>{Nl(this.recovery,O),this.stderr?.(`error: ${O}`)}),arity:2,isDefault:!0});let g=e.get("error");(!g||g.isDefault)&&this.hostFunctions.set("error",{...g,fn:(...R)=>{let N=R.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return Nl(this.recovery,N),this.stderr?this.stderr(`error: ${N}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${N}
|
|
425
|
+
`):console.error(`error: ${N}`),N},arity:{min:1},description:g?.description??"Prints error message to stderr and records it for execution error summary",isDefault:!0});let y=e.get("system");(!y||y.isDefault)&&this.hostFunctions.set("system",{...y,fn:(R,N)=>jv(R,N,{async:this.isAsync,platform:this.platform,signal:this.abortSignal,context:this.processContext}),arity:y?.arity??{min:1,max:2},description:"Executes argv directly with shell:false and optional timeoutMs (default 60000) or options {cwd, timeoutMs, stdin}, returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",isDefault:!0});let b=e.get("prompt_human_config");(!b||b.isDefault)&&this.hostFunctions.set("prompt_human_config",{...b,fn:(R,N)=>{if(R===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 R=="string")R==="interactive"?this.promptHumanConfig.mode="interactive":R==="file"?(this.promptHumanConfig.mode="file",N&&(this.promptHumanConfig.dir=String(N))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=R);else if(R&&typeof R=="object"){let O=R.mode?String(R.mode):R.dir?"file":this.promptHumanConfig.mode??"interactive",A=R.dir!==void 0?String(R.dir):this.promptHumanConfig.dir,w=R.timeout_ms!==void 0?Number(R.timeout_ms):R.timeoutMs!==void 0?Number(R.timeoutMs):this.promptHumanConfig.timeoutMs,T=R.poll_ms!==void 0?Number(R.poll_ms):R.pollIntervalMs!==void 0?Number(R.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=O==="file"?"file":"interactive",this.promptHumanConfig.dir=A,this.promptHumanConfig.timeoutMs=typeof w=="number"&&Number.isFinite(w)?w:void 0,this.promptHumanConfig.pollIntervalMs=typeof T=="number"&&Number.isFinite(T)&&T>0?T:200}return{mode:this.promptHumanConfig.mode,dir:this.promptHumanConfig.dir??null,timeout_ms:this.promptHumanConfig.timeoutMs??null,poll_interval_ms:this.promptHumanConfig.pollIntervalMs??200}},arity:b?.arity??{min:0,max:2},description:"Configures prompt_human mode ('interactive' or 'file' with dedicated directory, timeout_ms, poll_ms)",isDefault:!0});let _=e.get("prompt_human");(!_||_.isDefault)&&this.hostFunctions.set("prompt_human",{..._,fn:(R,N)=>{if((N?.mode??(N?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let A=N?.dir??this.promptHumanConfig.dir;if(!A)throw new Error("prompt_human: file mode requires a directory (configure via prompt_human_config({ dir }) or pass { dir })");if(!this.isAsync)throw new Error("prompt_human: file mode requires asynchronous execution (runAsync)");return Bv(R,{dir:A,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,onWaiting:w=>this.stderr?this.stderr(w):typeof process<"u"&&process.stderr?process.stderr.write(w):void 0})}return this.isAsync?Gl(R,void 0,void 0,this.abortSignal):Uv(R)},arity:_?.arity??{min:0,max:2},description:"Prompts operator on stdin/terminal or dedicated directory, returning input string or null if closed/non-interactive",isDefault:!0});let v=e.get("cmd_render");(!v||v.isDefault)&&this.hostFunctions.set("cmd_render",{...v,fn:(R,N)=>rp(R,N,this.platform),arity:{min:1,max:2},isDefault:!0});let E=e.get("run_script");(!E||E.isDefault)&&this.hostFunctions.set("run_script",{...E,fn:(R,N=[])=>{let O=this.processContext,A=se.resolve(O?.cwd??process.cwd(),String(R));if(!U.existsSync(A))throw new Error(`run_script: file not found: '${A}'`);let w=U.readFileSync(A,"utf-8"),T=Array.isArray(N)?N.map(String):[],k=this.childEngineFactory?this.childEngineFactory({args:T}):new Er;if(!this.childEngineFactory){for(let[I,C]of this.hostFunctions)k.hasFunction(I)?C.isDefault||k.registerFunction(I,C.fn,C.signature?.nativeArity??C.arity,{description:C.description,params:C.signature?.nativeParams??C.params,returnType:C.returnType,readonly:C.readonly,dryControl:C.dryControl,[qe]:C[qe],doc:C.doc,allowOverwrite:!0,isContainerMutation:C.isContainerMutation,...hs(C)},!1,C.isContainerMutation):k.registerFunction(I,C.fn,C.signature?.nativeArity??C.arity,{description:C.description,params:C.signature?.nativeParams??C.params,returnType:C.returnType,readonly:C.readonly,dryControl:C.dryControl,[qe]:C[qe],doc:C.doc,isDefault:C.isDefault,isContainerMutation:C.isContainerMutation,...hs(C)});k.setGlobal("args",[...T]),k.setGlobal("ARGV",[...T])}if(this.isAsync)return(async()=>{let I=await k.runAsync(w,{file:A,entryLocation:A,executionOrigin:wr({source_kind:"file",script_file:A,source_name:A,parent_run_id:this.executionOrigin?.run_id}),signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight,hostContext:O,propertyStore:this.compileOptions?.propertyStore}),C=ys(I.value);if(C)throw new Error(`run_script: ${Oe(C)?`the child result contains resource ${C.id}, which cannot leave the child run`:Lm(C,"child run")}`);let M=I.stdout??I.output.join(`
|
|
426
426
|
`)+(I.output.length>0?`
|
|
427
|
-
`:""),D=I.exitCode!==void 0?I.exitCode:I.success&&!I.errors?.length?0:1,j={success:I.success&&D===0,stdout:M,output:[...I.output],value:I.value??null,exit_code:D,code:D,errors:I.errors??[]};for(let
|
|
427
|
+
`:""),D=I.exitCode!==void 0?I.exitCode:I.success&&!I.errors?.length?0:1,j={success:I.success&&D===0,stdout:M,output:[...I.output],value:I.value??null,exit_code:D,code:D,errors:I.errors??[]};for(let $ of[...I.errors??[],...I.diagnostics.filter(Z=>Z.severity==="error").map(Z=>Z.message)])this.recordedErrors.push($);return j})();{let I=k.run(w,{file:A,entryLocation:A,executionOrigin:wr({source_kind:"file",script_file:A,source_name:A,parent_run_id:this.executionOrigin?.run_id}),signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight,hostContext:O,propertyStore:this.compileOptions?.propertyStore}),C=I.stdout??I.output.join(`
|
|
428
428
|
`)+(I.output.length>0?`
|
|
429
|
-
`:""),M=I.exitCode!==void 0?I.exitCode:I.success&&!I.errors?.length?0:1,D={success:I.success&&M===0,stdout:C,output:[...I.output],value:I.value??null,exit_code:M,code:M,errors:I.errors??[]};for(let j of[...I.errors??[],...I.diagnostics.filter(F=>F.severity==="error").map(F=>F.message)])this.recordedErrors.push(j);return D}},arity:E?.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 x=e.get("http_get");(!x||x.isDefault)&&this.hostFunctions.set("http_get",{...x,fn:R=>this.isAsync?WO(R):Mv(R),arity:x?.arity??1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let S=e.get("sleep_ms");if((!S||S.isDefault)&&this.hostFunctions.set("sleep_ms",{...S,fn:R=>{if(typeof R!="number"||!Number.isFinite(R)||R<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(R>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(O=>setTimeout(O,R));let N=Date.now()+R;for(;Date.now()<N;);return null},arity:S?.arity??1,description:"Sleeps for the specified milliseconds",isDefault:!0}),this.dry)for(let[R,N]of e)N.signature?.dryrunIndex!==void 0&&this.hostFunctions.set(R,N)}evaluateProgram(e){if(this.globalEnv=new gt,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 P("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 P("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 P(`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(tt(this.abortSignal),this.recovery.pending.length>0)throw new P(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(tt(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new P(`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 P(`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 ze?e.kind==="ReturnStmt"&&r.jump("return",e):s instanceof ot||s instanceof at||r.raise(s,e),s}}execStmtCore(e,n){switch(this.dry?.at(e),tt(this.abortSignal),e.kind){case"PackageStmt":{if(e.nativeModule&&!this.dry){let r=this.nativeImports?.get(e.nativeModule)?.();if(lt(r))throw new P("Native import requires runAsync",e.line,e.column,"RUNTIME",e.file)}return}case"ImportStmt":return;case"BlockStmt":{let r=new gt(n);for(let s of e.statements)this.execStmt(s,r);return}case"VarDeclStmt":{let r=null;return e.initializer&&(r=this.evalExpr(e.initializer,n)),n.define(e.name,r),r}case"TupleVarDeclStmt":{let r=this.evalExpr(e.initializer,n);if(!Array.isArray(r))throw new P(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?(this.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));){if(++r>1e6&&!this.dry)throw new P("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");s?.loopIter(i,r,e,n);try{this.execStmt(e.body,n)}catch(a){if(a instanceof ot){o="break";break}if(a instanceof at)continue;throw a}}}catch(a){throw o=a instanceof ze?"return":"raise",a}finally{s?.loopExit(i,r,o)}return}case"ForInStmt":{let r=gv(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&&s===this.dry.loopLimit)&&!this.dry?.loop(s,e);l++){let c=r[l];if(++s>1e6&&!this.dry)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let u=new gt(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 ot){a="break";break}if(d instanceof at)continue;throw d}}}catch(l){throw a=l instanceof ze?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ForStmt":{let r=new gt(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}if(++s>1e6&&!this.dry)throw new P("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");i?.loopIter(o,s,e,r);try{this.execStmt(e.body,r)}catch(l){if(l instanceof ot){a="break";break}if(!(l instanceof at))throw l}if(this.dry?.loop(s,e))break;e.update&&this.evalExpr(e.update,r)}}catch(l){throw a=l instanceof ze?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new ze(r)}case"BreakStmt":throw new ot;case"ContinueStmt":throw new at;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new P("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let r=this.evalExpr(e.expr,n);return this.invokeNamed("system",[r],n,e.expr.line,e.expr.column,e.expr.file)}return this.evalExpr(e.expr,n)}case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new gt(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 Vt(this.recovery,o),o}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(tt(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=fv(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:Wm(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new P("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"PathLiteralExpr":return bv(e,this.platform);case"DataBlockExpr":{let r=Pm(e,i=>this.evalExpr(i.value,n)),s=[];for(let i of e.lines)for(let o of i.pieces)typeof o!="string"&&s.push(this.evalExpr(o.expression,n));return av(e,r,s)}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 P(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<r.length?r[s]:null,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),ct(r,s,i),i;throw new P("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,n);case"TupleExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ArrayExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ObjectExpr":{let r={};for(let s of e.properties)ct(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Ul(e);if(r)try{this.dry&&this.dry.at(e);let o=this.dry?.prepareProperties(r);if(lt(o))throw o.catch(()=>{}),Error("Async properties require dryRunAsync");return Rt(this.dry?this.dry.propertyView:this.resolveIdentifier("PROPS",n,e),r)}catch(o){throw this.dry?new P(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 P("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Jn.has(s)?Tv(s,i,e,this.dry):_v(s,i,e)}case"MethodCallExpr":{let r=this.evalExpr(e.receiver,n),s=e.args.map(i=>this.evalExpr(i,n));return vv(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 P(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.evalExpr(e.trueArm,n):this.evalExpr(e.falseArm,n)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?this.evalExpr(e.right,n):o}if(e.operator==="||"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?o:this.evalExpr(e.right,n)}let r=this.evalExpr(e.left,n),s=this.evalExpr(e.right,n),i=e.operator;switch(i){case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":if(s===0)throw new P("Division by zero",e.line,e.column,"RUNTIME",e.file);return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:throw new P(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let r=e.args.map(s=>this.evalExpr(s,n));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),this.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}resolveIdentifier(e,n,r){if(this.recovery.active&&this.checkRecoverRead(e,n,r,r),n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&Ym.has(s)){this.dry&&this.dry.at(r);try{let i=Ym.get(s)();return lt(i)?i.catch(o=>{throw new P(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new P(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new Vn(e);throw new P(`Variable '${e}' was read before its binding was initialized`,r.line,r.column,"RUNTIME",r.file)}resolveCallTarget(e,n){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;let r=n.get(e);return r instanceof Vn?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);a.call(e,l?l.params.map((u,d)=>({name:u,value:n[d]})):n.map(u=>({value:u})),!l,l);let c;try{c=this.invokeNamedCore(e,n,r,s,i,o)}catch(u){throw u instanceof ze||u instanceof ot||u instanceof at||a.raise(u,{line:s,column:i,file:o}),a.ret(null,!0,u),u}return a.ret(c),c}invokeNamedCore(e,n,r,s,i,o){if(this.dry?.at({line:s,column:i,file:o}),tt(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Rl)throw this.callDepth--,new P(`Execution fuel exhausted: maximum function call depth exceeded (${Rl})`,s,i,"RUNTIME",o);let l=new gt(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 ze)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{if(a[qe]?.control==="warning"){To(a,n);let u=String(this.dry?cn(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:u,line:s,column:i,file:o}),u}if(this.dry){let u=Sv(a,n,e,{line:s,column:i,file:o},this.dry,this.platform);if(u.skip)return u.value;let d=wo(a,u.args);if(this.dry.check(),lt(d)&&(Promise.resolve(d).catch(()=>{}),this.dry.fail("Async host requires dryRunAsync",{line:s,column:i,file:o})),this.dry.failure)throw new Kt(this.dry.failure.message);return ys(d)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:o}),a[qe]?.taints===!1&&this.dry.captureOutput(e,d),u.handled&&this.dry.record(e,u.publicArgs,{line:s,column:i,file:o},"handled",void 0,u.taints),d}let l=To(a,n);if(a.returnsResource)throw new P(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);tt(this.abortSignal);let c=wo(a,l);if(a.returnsResource&<(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 $t||l?.name==="LMScriptExit"||l?.isControlFlow?l:new P(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new P(`'${e}' is not a function`,s,i,"RUNTIME",o):new P(si(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 P(`Resource ${this.resources.describe(e)} ${n}`,r.line,r.column,"RUNTIME",r.file)}refuseResource(e,n,r){if(Oe(e))throw this.resourceError(e,n,r)}bindResource(e,n,r,s){let i=this.resources.bind(e,n,r);if(i)throw new P(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(Oe))return r;let a={line:s,column:i,file:o};if(!e.usesResource&&!e.closesResource)throw this.resourceError(r.find(Oe),`cannot be passed to '${n}'`,a);let l=[];for(let c of r){if(!Oe(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 gt,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 Vt(this.recovery,s),this.resources.root.failure=ps(s),s}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),Oe(r))r=null;else if(kv()){let s=ys(r);if(s)throw new P(Oe(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:Lm(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 ze?e.kind==="ReturnStmt"&&s.jump("return",e,i):o instanceof ot||o instanceof at||s.raise(o,e,i),o}}async execStmtAsyncCore(e,n,r){switch(this.dry?.at(e),tt(this.abortSignal),e.kind){case"PackageStmt":{e.nativeModule&&!this.dry&&await this.nativeImports?.get(e.nativeModule)?.();return}case"ImportStmt":return;case"BlockStmt":{let s=new gt(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 Vt(this.recovery,o),i.failure=ps(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)),Oe(s)&&this.bindResource(s,n,e.name,e),n.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(Array.isArray(s))for(let i=0;i<e.names.length&&i<s.length;i++)this.bindResource(s[i],n,e.names[i],e);if(!Array.isArray(s))throw new P(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?(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));){if(++s>1e6&&!this.dry)throw new P("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");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 ot){l="break";break}if(c instanceof at)continue;throw c}}}catch(c){throw l=c instanceof ze?"return":"raise",c}finally{i?.loopExit(a,s,l,o)}return}case"ForInStmt":{let s=gv(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&&i===this.dry.loopLimit)&&!this.dry?.loop(i,e);u++){let d=s[u];if(++i>1e6&&!this.dry)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let m=new gt(n);m.define(e.name,d),o?.loopIter(l,i,e,m,a);let p=this.resourcesEnabled?this.resources.enterScope(m,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let f of e.body.statements)await this.execStmtAsync(f,m,r);else await this.execStmtAsync(e.body,m,r)}catch(f){throw Vt(this.recovery,f),p&&(p.failure=ps(f)),f}finally{p&&p.records.length>0&&await this.resources.drain(p)}}catch(f){if(f instanceof ot){c="break";break}if(f instanceof at)continue;throw f}}}catch(u){throw c=u instanceof ze?"return":"raise",u}finally{o?.loopExit(l,i,c,a)}return}case"ForStmt":{let s=new gt(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}if(++o>1e6&&!this.dry)throw new P("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");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 ot){u="break";break}if(!(d instanceof at))throw d}if(this.dry?.loop(o,e))break;e.update&&await this.evalExprAsync(e.update,s,r)}}catch(d){throw u=d instanceof ze?"return":"raise",d}finally{a?.loopExit(c,o,u,l)}}catch(o){throw Vt(this.recovery,o),i&&(i.failure=ps(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 Oe(s)&&this.refuseResource(s,"cannot be returned: a resource stays with its owner (return copied data instead)",e),new ze(s)}case"BreakStmt":throw new ot;case"ContinueStmt":throw new at;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 P(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let o=`bind:${i.env.id}:${i.name}`;await this.lockManager.getBindingLock(o).withLock(async()=>{let l=await this.evalExprAsync(e.value,n,r);this.bindResource(l,i.env,i.name,e),i.env.define(i.name,l)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new P("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,n,r),a=await this.evalExprAsync(e.value,n,r);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),ct(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new P("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new P(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],n,r);if(o==null||typeof o!="object"&&typeof o!="function")throw new P("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let s=await this.evalExprAsync(e.expr,n,r);return await this.invokeCallAsync("system",[s],n,e.expr.line,e.expr.column,r,e.expr.file)}return await this.evalExprAsync(e.expr,n,r)}case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new gt(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 Vt(this.recovery,l),o&&(o.failure=ps(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(tt(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=fv(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+=Wm(o,i)}return s}case"LiteralExpr":return e.value;case"PathLiteralExpr":return bv(e,this.platform);case"DataBlockExpr":{let s={};for(let o of e.options)s[o.name]=await this.evalExprAsync(o.value,n,r);let i=[];for(let o of e.lines)for(let a of o.pieces)typeof a!="string"&&i.push(await this.evalExprAsync(a.expression,n,r));return av(e,Pm(e,o=>s[o.name]),i)}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 Oe(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 P(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null,a=this.recovery.active?this.recoverWriteScope(e.targets[i],e):void 0;Oe(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),ct(s,i,o),o;throw new P("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,n,r);case"TupleExpr":{let s=[];for(let i of e.elements){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),ct(s,i.key,o)}return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(r)??0,i=async u=>{let d=this.nextTaskId++;this.asyncCallDepth.set(d,s);let m=this.resourcesEnabled?this.resources.temporaryScope(this.ownerFor(n,r),"task",this.resources.scopeFor(n)):void 0;m&&this.pushTemporaryScope(d,m);try{let p=await this.evalExprAsync(u,n,d),f=kv()?ys(p):void 0;if(f)throw new P(Oe(f)?`Resource ${this.resources.describe(f)} cannot be a parallel task result: it stays with the task that opened it`:Lm(f,"parallel task"),u.line,u.column,"RUNTIME",u.file);return p}catch(p){throw this.dry?.captureFailure(p,u),Vt(this.recovery,p),m&&(m.failure=ps(p)),p}finally{m&&(this.popTemporaryScope(d),m.records.length>0&&await this.resources.drain(m))}};if(this.dry){let u=[];for(let d of e.tasks)this.dry.at(d),u.push(await i(d));return u}let o=e.tasks.map(i),a=await Promise.allSettled(o),l=[],c;for(let u of a)u.status==="fulfilled"?l.push(u.value):c||(c=u.reason);if(c)throw c;return l}case"IndexExpr":{let s=Ul(e);if(s)try{return this.dry&&(this.dry.at(e),await this.dry.prepareProperties(s)),Rt(this.dry?this.dry.propertyView:await this.resolveIdentifier("PROPS",n,e),s)}catch(a){throw this.dry?new P(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),Oe(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 P("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Jn.has(i)?Tv(i,o,e,this.dry):_v(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),vv(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 P(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,n,r):await this.evalExprAsync(e.falseArm,n,r)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?await this.evalExprAsync(e.right,n,r):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,n,r)}let s=await this.evalExprAsync(e.left,n,r),i=await this.evalExprAsync(e.right,n,r),o=e.operator;switch((Oe(s)||Oe(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 P("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new P(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,n,r));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),await this.invokeCallAsync(e.callee,s,n,e.line,e.column,r,e.file)}}}async invokeCallAsync(e,n,r,s,i,o,a){let l=this.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);let d=this.coOf(o);l.call(c,u?u.params.map((p,f)=>({name:p,value:n[f]})):n.map(p=>({value:p})),!u,u,d);let m;try{m=await this.invokeCallAsyncCore(e,n,r,s,i,o,a)}catch(p){throw p instanceof ze||p instanceof ot||p instanceof at||l.raise(p,{line:s,column:i,file:a},d),l.ret(null,!0,p,d),p}return l.ret(m,!1,void 0,d),m}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(tt(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>Rl)throw this.asyncCallDepth.set(o,u-1),new P(`Execution fuel exhausted: maximum function call depth exceeded (${Rl})`,s,i,"RUNTIME",a);let d=new gt(this.globalEnv,!0),m=this.resourcesEnabled?this.resources.enterScope(d,this.ownerFor(r,o),`function ${l}`):void 0;for(let p=0;p<c.params.length;p++)m&&this.resources.borrow(n[p]),d.define(c.params[p],n[p]);try{for(let p of c.body.statements)await this.execStmtAsync(p,d,o)}catch(p){if(p instanceof ze)return p.value;throw this.dry?.captureFailure(p),Vt(this.recovery,p),m&&(m.failure=ps(p)),p}finally{m&&m.records.length>0&&await this.resources.drain(m),this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{if(c[qe]?.control==="warning"){To(c,n);let h=String(this.dry?cn(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:h,line:s,column:i,file:a}),h}if(this.dry){let h=Sv(c,n,l,{line:s,column:i,file:a},this.dry,this.platform);if(h.skip)return h.value;let g=await this.dry.wait(wo(c,h.args));if(this.dry.failure)throw new Kt(this.dry.failure.message);return ys(g)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:a}),c[qe]?.taints===!1&&this.dry.captureOutput(l,g),h.handled&&this.dry.record(l,h.publicArgs,{line:s,column:i,file:a},"handled",void 0,h.taints),g}let u=To(c,n),d=AL(u)?await this.resourceCallArgs(c,l,u,s,i,a):u,p=c.returnsResource||c.usesResource||c.closesResource?Qv.run({runtime:this.resources,scope:this.ownerFor(r,o),site:(a??"<main>")+":"+s+":"+i},()=>wo(c,d)):wo(c,d),f=p instanceof Promise?await p:p;return c.returnsResource?this.registerHostResource(f,l,this.ownerFor(r,o),s,i,a):f}catch(u){throw this.dry?.captureFailure(u,{line:s,column:i,file:a}),u instanceof $t||u?.name==="LMScriptExit"||u?.isControlFlow?u:new P(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new P(`'${l}' is not a function`,s,i,"RUNTIME",a):new P(si(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},CL=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. Function bodies establish an isolated local variable scope for assignments, preventing accidental mutation of caller variables.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system(["echo", "1"]), system(["echo", "2"]) ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],NL=[{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 same classification with dry: true and nothing created.",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 (default 262144) 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:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), reports through injected diagnostics/captured errors and stops with exit 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_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns first [full_match, group1, ...], including with g; missing optional groups become null. Rejects sticky y.",example:'regex_match("a1 b2", "([a-z])([0-9])", "g");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns capture arrays for matches; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_find_all("a1 b2", "([a-z])([0-9])");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:"JavaScript regex replacement with $1 captures; use g for repeated replacement.",example:'regex_replace("a1", "([a-z])([0-9])", "$2$1");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits using JavaScript regex semantics.",example:'split_regex("a b", " +");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width/other precision limit: 10000. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the 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:"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 = 60000 | 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 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: 60000), or options {cwd: string (relative to the invocation directory), timeoutMs: number (default 60000), 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 and prints %s, %d, %f and %% using the sprintf width and precision rules.",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline.",example:'println("Done.");'},{name:"sleep_ms",category:"System & Process",signature:"sleep_ms(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep_ms(1000);"},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in milliseconds.",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now or a supplied epoch-millisecond value.",example:"created = date(0);"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null (including no arguments).",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"http_get",category:"System & Process",signature:"http_get(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = http_get("https://example.com");'}],OL=[{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);"}];Er=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;promptHumanConfig={mode:"interactive"};hostCatalog=new Map;nativeCatalog=new Map;builtinProviders=new Map;hostResolver;reservedFunctionPrefixes;builtinProviderNames;constructor(e={}){this.hostResolver=e.resolveHostModule,this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions();for(let[n,r]of[["get_property",{min:1,max:2}],["has_property",1],["get_properties",{min:0,max:1}],["set_property",2]])this.registerFunction(n,()=>{throw Error("Property store is not running")},r,"Read or overlay hierarchical run-local properties; no persistence");this.registerFunction("expand",()=>{throw Error("Template resolver is not running")},{min:1,max:2},"Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque"),this.registerFunction("warning",n=>String(n),1,{description:"Adds a located non-failure warning",isDefault:!0,returnType:"string"}),this.registerFunction("which",n=>Im(n,process.cwd(),process.env),1,{description:"Finds the first executable path without spawning",isDefault:!0,returnType:"string|null"});for(let n of["print","println","printf"]){let r=this.hostFunctions.get(n),s=[{name:"dryrun",type:"boolean",optional:!0},...n==="printf"?[{name:"format",type:"string"}]:[],{name:"values",type:"any",rest:!0}],i=ln(n,{min:n==="printf"?2:0},s,"string",r.doc),o=r.fn;n==="printf"?r.fn=(a,...l)=>a?Ll(l[0],l.slice(1),"printf"):o(...l):r.fn=(a,...l)=>a?l.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" "):o(...l),Object.assign(r,{params:i.nativeParams,arity:i.nativeArity,signature:i,returnType:"string"})}for(let[n,r]of this.hostFunctions){let s=Xm[n];s&&(r[qe]=s)}this.registerDefaultDocs();for(let[n,r,s]of[["get_property","get_property(key, [default])","Returns a copied property value; absent keys are errors unless a default is supplied."],["has_property","has_property(key)","Tests property presence; missing/invalid profile errors remain loud."],["get_properties","get_properties([prefix])","Returns a detached nested property table copy."],["set_property","set_property(key, value)","Returns the previous value and changes only the run-local overlay; invocation facts are read-only."]])this.functionDocs.set(n,{name:n,signature:r,description:s,module:"core",category:"Properties"});this.functionDocs.set("expand",{name:"expand",signature:"expand(text, [vars])",description:"Resolve ${name} from an explicit vars map, ${PROPS.path}, and ${ARGV[n]}; $${ escapes, no caller-local capture or recursive expansion.",module:"core",category:"Strings"})}registerDefaultDocs(){for(let e of CL)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of NL)this.registerFunctionDoc({...e,module:e.module??"core"});for(let e of OL)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){let n=Nm({...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:ln(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"}}:{},...r.dryrunIndex===void 0?{}:{signature:e+"("+r.publicParams.map(s=>s.rest?"..."+s.name:s.optional?"["+s.name+"]":s.name).join(", ")+")",parameters:n.parameters?.filter(s=>s.name!=="dryrun")}}}getFunctionCategories(){let e=new Set;for(let n of this.functionDocs.values())e.add(n.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(n=>n.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=U.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
|
|
429
|
+
`:""),M=I.exitCode!==void 0?I.exitCode:I.success&&!I.errors?.length?0:1,D={success:I.success&&M===0,stdout:C,output:[...I.output],value:I.value??null,exit_code:M,code:M,errors:I.errors??[]};for(let j of[...I.errors??[],...I.diagnostics.filter($=>$.severity==="error").map($=>$.message)])this.recordedErrors.push(j);return D}},arity:E?.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 x=e.get("http_get");(!x||x.isDefault)&&this.hostFunctions.set("http_get",{...x,fn:R=>this.isAsync?WO(R):Mv(R),arity:x?.arity??1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let S=e.get("sleep_ms");if((!S||S.isDefault)&&this.hostFunctions.set("sleep_ms",{...S,fn:R=>{if(typeof R!="number"||!Number.isFinite(R)||R<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(R>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(O=>setTimeout(O,R));let N=Date.now()+R;for(;Date.now()<N;);return null},arity:S?.arity??1,description:"Sleeps for the specified milliseconds",isDefault:!0}),this.dry)for(let[R,N]of e)N.signature?.dryrunIndex!==void 0&&this.hostFunctions.set(R,N)}evaluateProgram(e){if(this.globalEnv=new gt,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 P("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 P("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 P(`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(tt(this.abortSignal),this.recovery.pending.length>0)throw new P(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(tt(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new P(`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 P(`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 ze?e.kind==="ReturnStmt"&&r.jump("return",e):s instanceof ot||s instanceof at||r.raise(s,e),s}}execStmtCore(e,n){switch(this.dry?.at(e),tt(this.abortSignal),e.kind){case"PackageStmt":{if(e.nativeModule&&!this.dry){let r=this.nativeImports?.get(e.nativeModule)?.();if(lt(r))throw new P("Native import requires runAsync",e.line,e.column,"RUNTIME",e.file)}return}case"ImportStmt":return;case"BlockStmt":{let r=new gt(n);for(let s of e.statements)this.execStmt(s,r);return}case"VarDeclStmt":{let r=null;return e.initializer&&(r=this.evalExpr(e.initializer,n)),n.define(e.name,r),r}case"TupleVarDeclStmt":{let r=this.evalExpr(e.initializer,n);if(!Array.isArray(r))throw new P(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?(this.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));){if(++r>1e6&&!this.dry)throw new P("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");s?.loopIter(i,r,e,n);try{this.execStmt(e.body,n)}catch(a){if(a instanceof ot){o="break";break}if(a instanceof at)continue;throw a}}}catch(a){throw o=a instanceof ze?"return":"raise",a}finally{s?.loopExit(i,r,o)}return}case"ForInStmt":{let r=gv(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&&s===this.dry.loopLimit)&&!this.dry?.loop(s,e);l++){let c=r[l];if(++s>1e6&&!this.dry)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let u=new gt(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 ot){a="break";break}if(d instanceof at)continue;throw d}}}catch(l){throw a=l instanceof ze?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ForStmt":{let r=new gt(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}if(++s>1e6&&!this.dry)throw new P("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");i?.loopIter(o,s,e,r);try{this.execStmt(e.body,r)}catch(l){if(l instanceof ot){a="break";break}if(!(l instanceof at))throw l}if(this.dry?.loop(s,e))break;e.update&&this.evalExpr(e.update,r)}}catch(l){throw a=l instanceof ze?"return":"raise",l}finally{i?.loopExit(o,s,a)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new ze(r)}case"BreakStmt":throw new ot;case"ContinueStmt":throw new at;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new P("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let r=this.evalExpr(e.expr,n);return this.invokeNamed("system",[r],n,e.expr.line,e.expr.column,e.expr.file)}return this.evalExpr(e.expr,n)}case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new gt(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 Vt(this.recovery,o),o}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(tt(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=fv(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:Wm(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new P("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"PathLiteralExpr":return bv(e,this.platform);case"DataBlockExpr":{let r=Pm(e,i=>this.evalExpr(i.value,n)),s=[];for(let i of e.lines)for(let o of i.pieces)typeof o!="string"&&s.push(this.evalExpr(o.expression,n));return av(e,r,s)}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 P(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<r.length?r[s]:null,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),ct(r,s,i),i;throw new P("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,n);case"TupleExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ArrayExpr":return e.elements.map(r=>this.evalExpr(r,n));case"ObjectExpr":{let r={};for(let s of e.properties)ct(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Ul(e);if(r)try{this.dry&&this.dry.at(e);let o=this.dry?.prepareProperties(r);if(lt(o))throw o.catch(()=>{}),Error("Async properties require dryRunAsync");return Rt(this.dry?this.dry.propertyView:this.resolveIdentifier("PROPS",n,e),r)}catch(o){throw this.dry?new P(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 P("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Jn.has(s)?Tv(s,i,e,this.dry):_v(s,i,e)}case"MethodCallExpr":{let r=this.evalExpr(e.receiver,n),s=e.args.map(i=>this.evalExpr(i,n));return vv(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 P(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.evalExpr(e.trueArm,n):this.evalExpr(e.falseArm,n)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?this.evalExpr(e.right,n):o}if(e.operator==="||"){let o=this.evalExpr(e.left,n);return this.isTruthy(o)?o:this.evalExpr(e.right,n)}let r=this.evalExpr(e.left,n),s=this.evalExpr(e.right,n),i=e.operator;switch(i){case"+":return typeof r=="string"||typeof s=="string"?String(r)+String(s):r+s;case"-":return r-s;case"*":return r*s;case"/":if(s===0)throw new P("Division by zero",e.line,e.column,"RUNTIME",e.file);return r/s;case"%":return r%s;case"==":return r===s;case"!=":return r!==s;case"<":return r<s;case"<=":return r<=s;case">":return r>s;case">=":return r>=s;default:throw new P(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let r=e.args.map(s=>this.evalExpr(s,n));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),this.invokeNamed(this.resolveCallTarget(e.callee,n),r,n,e.line,e.column,e.file)}}}resolveIdentifier(e,n,r){if(this.recovery.active&&this.checkRecoverRead(e,n,r,r),n.has(e)){let s=n.get(e);if(s&&typeof s=="object"&&Ym.has(s)){this.dry&&this.dry.at(r);try{let i=Ym.get(s)();return lt(i)?i.catch(o=>{throw new P(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new P(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new Vn(e);throw new P(`Variable '${e}' was read before its binding was initialized`,r.line,r.column,"RUNTIME",r.file)}resolveCallTarget(e,n){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;let r=n.get(e);return r instanceof Vn?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);a.call(e,l?l.params.map((u,d)=>({name:u,value:n[d]})):n.map(u=>({value:u})),!l,l);let c;try{c=this.invokeNamedCore(e,n,r,s,i,o)}catch(u){throw u instanceof ze||u instanceof ot||u instanceof at||a.raise(u,{line:s,column:i,file:o}),a.ret(null,!0,u),u}return a.ret(c),c}invokeNamedCore(e,n,r,s,i,o){if(this.dry?.at({line:s,column:i,file:o}),tt(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Rl)throw this.callDepth--,new P(`Execution fuel exhausted: maximum function call depth exceeded (${Rl})`,s,i,"RUNTIME",o);let l=new gt(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 ze)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{if(a[qe]?.control==="warning"){To(a,n);let u=String(this.dry?cn(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:u,line:s,column:i,file:o}),u}if(this.dry){let u=Sv(a,n,e,{line:s,column:i,file:o},this.dry,this.platform);if(u.skip)return u.value;let d=wo(a,u.args);if(this.dry.check(),lt(d)&&(Promise.resolve(d).catch(()=>{}),this.dry.fail("Async host requires dryRunAsync",{line:s,column:i,file:o})),this.dry.failure)throw new Kt(this.dry.failure.message);return ys(d)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:o}),a[qe]?.taints===!1&&this.dry.captureOutput(e,d),u.handled&&this.dry.record(e,u.publicArgs,{line:s,column:i,file:o},"handled",void 0,u.taints),d}let l=To(a,n);if(a.returnsResource)throw new P(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);tt(this.abortSignal);let c=wo(a,l);if(a.returnsResource&<(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 $t||l?.name==="LMScriptExit"||l?.isControlFlow?l:new P(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new P(`'${e}' is not a function`,s,i,"RUNTIME",o):new P(si(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 P(`Resource ${this.resources.describe(e)} ${n}`,r.line,r.column,"RUNTIME",r.file)}refuseResource(e,n,r){if(Oe(e))throw this.resourceError(e,n,r)}bindResource(e,n,r,s){let i=this.resources.bind(e,n,r);if(i)throw new P(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(Oe))return r;let a={line:s,column:i,file:o};if(!e.usesResource&&!e.closesResource)throw this.resourceError(r.find(Oe),`cannot be passed to '${n}'`,a);let l=[];for(let c of r){if(!Oe(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 gt,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 Vt(this.recovery,s),this.resources.root.failure=ps(s),s}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),Oe(r))r=null;else if(kv()){let s=ys(r);if(s)throw new P(Oe(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:Lm(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 ze?e.kind==="ReturnStmt"&&s.jump("return",e,i):o instanceof ot||o instanceof at||s.raise(o,e,i),o}}async execStmtAsyncCore(e,n,r){switch(this.dry?.at(e),tt(this.abortSignal),e.kind){case"PackageStmt":{e.nativeModule&&!this.dry&&await this.nativeImports?.get(e.nativeModule)?.();return}case"ImportStmt":return;case"BlockStmt":{let s=new gt(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 Vt(this.recovery,o),i.failure=ps(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)),Oe(s)&&this.bindResource(s,n,e.name,e),n.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,n,r);if(Array.isArray(s))for(let i=0;i<e.names.length&&i<s.length;i++)this.bindResource(s[i],n,e.names[i],e);if(!Array.isArray(s))throw new P(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?(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));){if(++s>1e6&&!this.dry)throw new P("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");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 ot){l="break";break}if(c instanceof at)continue;throw c}}}catch(c){throw l=c instanceof ze?"return":"raise",c}finally{i?.loopExit(a,s,l,o)}return}case"ForInStmt":{let s=gv(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&&i===this.dry.loopLimit)&&!this.dry?.loop(i,e);u++){let d=s[u];if(++i>1e6&&!this.dry)throw new P("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let m=new gt(n);m.define(e.name,d),o?.loopIter(l,i,e,m,a);let p=this.resourcesEnabled?this.resources.enterScope(m,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let f of e.body.statements)await this.execStmtAsync(f,m,r);else await this.execStmtAsync(e.body,m,r)}catch(f){throw Vt(this.recovery,f),p&&(p.failure=ps(f)),f}finally{p&&p.records.length>0&&await this.resources.drain(p)}}catch(f){if(f instanceof ot){c="break";break}if(f instanceof at)continue;throw f}}}catch(u){throw c=u instanceof ze?"return":"raise",u}finally{o?.loopExit(l,i,c,a)}return}case"ForStmt":{let s=new gt(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}if(++o>1e6&&!this.dry)throw new P("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");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 ot){u="break";break}if(!(d instanceof at))throw d}if(this.dry?.loop(o,e))break;e.update&&await this.evalExprAsync(e.update,s,r)}}catch(d){throw u=d instanceof ze?"return":"raise",d}finally{a?.loopExit(c,o,u,l)}}catch(o){throw Vt(this.recovery,o),i&&(i.failure=ps(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 Oe(s)&&this.refuseResource(s,"cannot be returned: a resource stays with its owner (return copied data instead)",e),new ze(s)}case"BreakStmt":throw new ot;case"ContinueStmt":throw new at;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 P(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let o=`bind:${i.env.id}:${i.name}`;await this.lockManager.getBindingLock(o).withLock(async()=>{let l=await this.evalExprAsync(e.value,n,r);this.bindResource(l,i.env,i.name,e),i.env.define(i.name,l)},r);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,n,r);if(s==null||typeof s!="object"&&typeof s!="function")throw new P("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,n,r),a=await this.evalExprAsync(e.value,n,r);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),ct(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new P("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new P(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],n,r);if(o==null||typeof o!="object"&&typeof o!="function")throw new P("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":{if(e.expr.kind==="DataBlockExpr"&&e.expr.marker==="cmd"){let s=await this.evalExprAsync(e.expr,n,r);return await this.invokeCallAsync("system",[s],n,e.expr.line,e.expr.column,r,e.expr.file)}return await this.evalExprAsync(e.expr,n,r)}case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new gt(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 Vt(this.recovery,l),o&&(o.failure=ps(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(tt(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=fv(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+=Wm(o,i)}return s}case"LiteralExpr":return e.value;case"PathLiteralExpr":return bv(e,this.platform);case"DataBlockExpr":{let s={};for(let o of e.options)s[o.name]=await this.evalExprAsync(o.value,n,r);let i=[];for(let o of e.lines)for(let a of o.pieces)typeof a!="string"&&i.push(await this.evalExprAsync(a.expression,n,r));return av(e,Pm(e,o=>s[o.name]),i)}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 Oe(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 P(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null,a=this.recovery.active?this.recoverWriteScope(e.targets[i],e):void 0;Oe(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),ct(s,i,o),o;throw new P("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,n,r);case"TupleExpr":{let s=[];for(let i of e.elements){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),ct(s,i.key,o)}return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(r)??0,i=async u=>{let d=this.nextTaskId++;this.asyncCallDepth.set(d,s);let m=this.resourcesEnabled?this.resources.temporaryScope(this.ownerFor(n,r),"task",this.resources.scopeFor(n)):void 0;m&&this.pushTemporaryScope(d,m);try{let p=await this.evalExprAsync(u,n,d),f=kv()?ys(p):void 0;if(f)throw new P(Oe(f)?`Resource ${this.resources.describe(f)} cannot be a parallel task result: it stays with the task that opened it`:Lm(f,"parallel task"),u.line,u.column,"RUNTIME",u.file);return p}catch(p){throw this.dry?.captureFailure(p,u),Vt(this.recovery,p),m&&(m.failure=ps(p)),p}finally{m&&(this.popTemporaryScope(d),m.records.length>0&&await this.resources.drain(m))}};if(this.dry){let u=[];for(let d of e.tasks)this.dry.at(d),u.push(await i(d));return u}let o=e.tasks.map(i),a=await Promise.allSettled(o),l=[],c;for(let u of a)u.status==="fulfilled"?l.push(u.value):c||(c=u.reason);if(c)throw c;return l}case"IndexExpr":{let s=Ul(e);if(s)try{return this.dry&&(this.dry.at(e),await this.dry.prepareProperties(s)),Rt(this.dry?this.dry.propertyView:await this.resolveIdentifier("PROPS",n,e),s)}catch(a){throw this.dry?new P(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),Oe(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 P("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Jn.has(i)?Tv(i,o,e,this.dry):_v(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),vv(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 P(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,n,r):await this.evalExprAsync(e.falseArm,n,r)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?await this.evalExprAsync(e.right,n,r):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,n,r);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,n,r)}let s=await this.evalExprAsync(e.left,n,r),i=await this.evalExprAsync(e.right,n,r),o=e.operator;switch((Oe(s)||Oe(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 P("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new P(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,n,r));return this.recovery.active&&!this.userFunctions.has(e.callee)&&!this.hostFunctions.has(e.callee)&&this.checkRecoverRead(e.callee,n,e,e),await this.invokeCallAsync(e.callee,s,n,e.line,e.column,r,e.file)}}}async invokeCallAsync(e,n,r,s,i,o,a){let l=this.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);let d=this.coOf(o);l.call(c,u?u.params.map((p,f)=>({name:p,value:n[f]})):n.map(p=>({value:p})),!u,u,d);let m;try{m=await this.invokeCallAsyncCore(e,n,r,s,i,o,a)}catch(p){throw p instanceof ze||p instanceof ot||p instanceof at||l.raise(p,{line:s,column:i,file:a},d),l.ret(null,!0,p,d),p}return l.ret(m,!1,void 0,d),m}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(tt(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>Rl)throw this.asyncCallDepth.set(o,u-1),new P(`Execution fuel exhausted: maximum function call depth exceeded (${Rl})`,s,i,"RUNTIME",a);let d=new gt(this.globalEnv,!0),m=this.resourcesEnabled?this.resources.enterScope(d,this.ownerFor(r,o),`function ${l}`):void 0;for(let p=0;p<c.params.length;p++)m&&this.resources.borrow(n[p]),d.define(c.params[p],n[p]);try{for(let p of c.body.statements)await this.execStmtAsync(p,d,o)}catch(p){if(p instanceof ze)return p.value;throw this.dry?.captureFailure(p),Vt(this.recovery,p),m&&(m.failure=ps(p)),p}finally{m&&m.records.length>0&&await this.resources.drain(m),this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{if(c[qe]?.control==="warning"){To(c,n);let h=String(this.dry?cn(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:h,line:s,column:i,file:a}),h}if(this.dry){let h=Sv(c,n,l,{line:s,column:i,file:a},this.dry,this.platform);if(h.skip)return h.value;let g=await this.dry.wait(wo(c,h.args));if(this.dry.failure)throw new Kt(this.dry.failure.message);return ys(g)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:a}),c[qe]?.taints===!1&&this.dry.captureOutput(l,g),h.handled&&this.dry.record(l,h.publicArgs,{line:s,column:i,file:a},"handled",void 0,h.taints),g}let u=To(c,n),d=AL(u)?await this.resourceCallArgs(c,l,u,s,i,a):u,p=c.returnsResource||c.usesResource||c.closesResource?Qv.run({runtime:this.resources,scope:this.ownerFor(r,o),site:(a??"<main>")+":"+s+":"+i},()=>wo(c,d)):wo(c,d),f=p instanceof Promise?await p:p;return c.returnsResource?this.registerHostResource(f,l,this.ownerFor(r,o),s,i,a):f}catch(u){throw this.dry?.captureFailure(u,{line:s,column:i,file:a}),u instanceof $t||u?.name==="LMScriptExit"||u?.isControlFlow?u:new P(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new P(`'${l}' is not a function`,s,i,"RUNTIME",a):new P(si(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},CL=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. Function bodies establish an isolated local variable scope for assignments, preventing accidental mutation of caller variables.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system(["echo", "1"]), system(["echo", "2"]) ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],NL=[{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 same classification with dry: true and nothing created.",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 (default 262144) 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:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), reports through injected diagnostics/captured errors and stops with exit 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_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns first [full_match, group1, ...], including with g; missing optional groups become null. Rejects sticky y.",example:'regex_match("a1 b2", "([a-z])([0-9])", "g");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns capture arrays for matches; zero-width progress follows code points in u/v modes. Rejects sticky y.",example:'regex_find_all("a1 b2", "([a-z])([0-9])");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:"JavaScript regex replacement with $1 captures; use g for repeated replacement.",example:'regex_replace("a1", "([a-z])([0-9])", "$2$1");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits using JavaScript regex semantics.",example:'split_regex("a b", " +");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width/other precision limit: 10000. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the 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:"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 = 60000 | 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 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: 60000), or options {cwd: string (relative to the invocation directory), timeoutMs: number (default 60000), 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");'}],OL=[{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);"}];Er=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;promptHumanConfig={mode:"interactive"};hostCatalog=new Map;nativeCatalog=new Map;builtinProviders=new Map;hostResolver;reservedFunctionPrefixes;builtinProviderNames;constructor(e={}){this.hostResolver=e.resolveHostModule,this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions();for(let[n,r]of[["get_property",{min:1,max:2}],["has_property",1],["get_properties",{min:0,max:1}],["set_property",2]])this.registerFunction(n,()=>{throw Error("Property store is not running")},r,"Read or overlay hierarchical run-local properties; no persistence");this.registerFunction("expand",()=>{throw Error("Template resolver is not running")},{min:1,max:2},"Expand simple references from explicit vars, PROPS paths and invocation ARGV; inserted text is opaque"),this.registerFunction("warning",n=>String(n),1,{description:"Adds a located non-failure warning",isDefault:!0,returnType:"string"}),this.registerFunction("which",n=>Im(n,process.cwd(),process.env),1,{description:"Finds the first executable path without spawning",isDefault:!0,returnType:"string|null"});for(let n of["print","println","printf"]){let r=this.hostFunctions.get(n),s=[{name:"dryrun",type:"boolean",optional:!0},...n==="printf"?[{name:"format",type:"string"}]:[],{name:"values",type:"any",rest:!0}],i=ln(n,{min:n==="printf"?2:0},s,"string",r.doc),o=r.fn;n==="printf"?r.fn=(a,...l)=>a?Ll(l[0],l.slice(1),"printf"):o(...l):r.fn=(a,...l)=>a?l.map(c=>typeof c=="object"?JSON.stringify(c):String(c)).join(" "):o(...l),Object.assign(r,{params:i.nativeParams,arity:i.nativeArity,signature:i,returnType:"string"})}for(let[n,r]of this.hostFunctions){let s=Xm[n];s&&(r[qe]=s)}this.registerDefaultDocs();for(let[n,r,s]of[["get_property","get_property(key, [default])","Returns a copied property value; absent keys are errors unless a default is supplied."],["has_property","has_property(key)","Tests property presence; missing/invalid profile errors remain loud."],["get_properties","get_properties([prefix])","Returns a detached nested property table copy."],["set_property","set_property(key, value)","Returns the previous value and changes only the run-local overlay; invocation facts are read-only."]])this.functionDocs.set(n,{name:n,signature:r,description:s,module:"core",category:"Properties"});this.functionDocs.set("expand",{name:"expand",signature:"expand(text, [vars])",description:"Resolve ${name} from an explicit vars map, ${PROPS.path}, and ${ARGV[n]}; $${ escapes, no caller-local capture or recursive expansion.",module:"core",category:"Strings"})}registerDefaultDocs(){for(let e of CL)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of NL)this.registerFunctionDoc({...e,module:e.module??"core"});for(let e of OL)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){let n=Nm({...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:ln(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"}}:{},...r.dryrunIndex===void 0?{}:{signature:e+"("+r.publicParams.map(s=>s.rest?"..."+s.name:s.optional?"["+s.name+"]":s.name).join(", ")+")",parameters:n.parameters?.filter(s=>s.name!=="dryrun")}}}getFunctionCategories(){let e=new Set;for(let n of this.functionDocs.values())e.add(n.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(n=>n.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=U.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
|
|
430
430
|
`)?n=n.slice(0,-2):n.endsWith(`
|
|
431
431
|
`)&&(n=n.slice(0,-1)),r?n.length===0?[""]:n.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,n)=>{if(!Array.isArray(n))throw new Error("write_lines: second argument must be an array of lines");let r=n.length===0?"":n.map(String).join(`
|
|
432
432
|
`)+`
|
|
433
|
-
`;return U.writeFileSync(e,r,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from(U.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return U.readdirSync(se.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,n)=>(U.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,n)=>(U.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,n)=>(U.writeFileSync(e,String(n),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,n)=>(U.appendFileSync(e,String(n),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let n=U.readFileSync(e,"utf-8");return JSON.parse(n)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,n,r=2)=>(U.writeFileSync(e,JSON.stringify(n,null,r),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,n=!0,r=",")=>{let s=U.readFileSync(e,"utf-8");return dv(s,n,r)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null."),this.registerFunction("write_csv",(e,n,r=",")=>(U.writeFileSync(e,mv(n,r),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",dv,{min:1,max:3},"Parses inline CSV text into records or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null."),this.registerFunction("csv_stringify",mv,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=se.resolve(BO(),`lmscript-${ep()}`),n=U.openSync(e,"wx",384);return U.closeSync(n),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>U.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{let n=Number(e);throw new $t(Number.isFinite(n)&&n>=0&&n<=255?Math.floor(n):1)},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>U.existsSync(e)?(U.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>U.existsSync(e)?(U.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,n=!0)=>(U.mkdirSync(e,{recursive:!!n}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,n=!1)=>U.existsSync(e)?(n?U.rmSync(e,{recursive:!0,force:!0}):U.rmdirSync(e),!0):!1,{min:1,max:2},"Removes a directory; pass true for recursive removal of a non-empty directory"),this.registerFunction("copy_file",(e,n)=>(U.copyFileSync(e,n),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,n)=>(U.renameSync(e,n),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,n)=>se.basename(e,n),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>se.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>se.join(...e),{min:0},"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>se.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,n=null)=>process.env[e]!==void 0?process.env[e]:n,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,n=null)=>process.env[e]!==void 0?process.env[e]:n,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,n)=>(process.env[e]=String(n),!0),2,"Sets an environment variable for this process and its children"),this.registerFunction("list",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("array",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("push",(e,...n)=>(e.push(...n),e),{min:1},"Pushes item(s) to end of array and returns the same array",!0,!0),this.registerFunction("pop",e=>e.pop(),1,"Pops item from end of array",!0,!0),this.registerFunction("shift",e=>e.shift(),1,"Removes and returns first element",!0,!0),this.registerFunction("unshift",(e,...n)=>(e.unshift(...n),e),{min:1},"Adds item(s) to front of array and returns the same array",!0,!0),this.registerFunction("insert",(e,n,r)=>{let s=n<0?e.length+n:n;return e.splice(s,0,r),e},3,"Inserts item at index and returns the same array",!0,!0),this.registerFunction("remove_at",(e,n)=>{let r=n<0?e.length+n:n,s=e.splice(r,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...n)=>e.concat(...n),{min:1},"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,n)=>{if(!Array.isArray(e))return e;let r=[...e];return n?r.sort((s,i)=>{let o=s?s[n]:void 0,a=i?i[n]:void 0;return o<a?-1:o>a?1:0}):r.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:String(s).localeCompare(String(i)))},{min:1,max:2},"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("unique",e=>Array.isArray(e)?Array.from(new Set(e)):[],1,"Removes duplicate elements"),this.registerFunction("flatten",e=>Array.isArray(e)?e.flat():[],1,"Flattens array one level"),this.registerFunction("first",e=>Array.isArray(e)&&e.length>0?e[0]:null,1,"Returns first element"),this.registerFunction("last",e=>Array.isArray(e)&&e.length>0?e[e.length-1]:null,1,"Returns last element"),this.registerFunction("sum",e=>Array.isArray(e)?e.reduce((n,r)=>n+(typeof r=="number"?r:Number(r)||0),0):0,1,"Calculates sum of array"),this.registerFunction("avg",e=>!Array.isArray(e)||e.length===0?0:e.reduce((r,s)=>r+(typeof s=="number"?s:Number(s)||0),0)/e.length,1,"Calculates average of array"),this.registerFunction("map",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("hash",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("from_entries",e=>Array.isArray(e)?Object.fromEntries(e):{},1,"Creates map from [key, value] pairs"),this.registerFunction("clear",e=>{if(Array.isArray(e))return e.length=0,e;if(e&&typeof e=="object"){for(let n of Object.keys(e))delete e[n];return e}return e},1,"Clears array or map",!0,!0),this.registerFunction("size",e=>Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns number of elements in array, string, or map"),this.registerFunction("system",(e,n)=>jv(e,n,{async:this.isAsyncMode}),{min:1,max:2},"Executes argv directly with shell:false and optional timeoutMs (default 60000) or options {cwd, timeoutMs, stdin}, returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",!0),this.registerFunction("run_script",(e,n=[])=>{let r=se.resolve(String(e));if(!U.existsSync(r))throw new Error(`run_script: file not found: '${r}'`);let s=U.readFileSync(r,"utf-8"),i=Array.isArray(n)?n.map(String):[],o=this.createChildEngine({args:i}),a={file:r,entryLocation:r,resolveHostModule:this.hostResolver};if(this.isAsyncMode)return(async()=>{let l=await o.runAsync(s,a),c=l.output.join(`
|
|
433
|
+
`;return U.writeFileSync(e,r,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from(U.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return U.readdirSync(se.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,n)=>(U.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,n)=>(U.writeFileSync(e,String(n),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,n)=>(U.writeFileSync(e,String(n),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,n)=>(U.appendFileSync(e,String(n),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let n=U.readFileSync(e,"utf-8");return JSON.parse(n)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,n,r=2)=>(U.writeFileSync(e,JSON.stringify(n,null,r),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,n=!0,r=",")=>{let s=U.readFileSync(e,"utf-8");return dv(s,n,r)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null."),this.registerFunction("write_csv",(e,n,r=",")=>(U.writeFileSync(e,mv(n,r),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",dv,{min:1,max:3},"Parses inline CSV text into records or rows. Typed cells: a trimmed -?digits or -?digits.digits cell becomes a number (007 becomes 7), true/false/null in any case become those values; other cells stay text; a missing trailing column is null."),this.registerFunction("csv_stringify",mv,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=se.resolve(BO(),`lmscript-${ep()}`),n=U.openSync(e,"wx",384);return U.closeSync(n),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>U.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{let n=Number(e);throw new $t(Number.isFinite(n)&&n>=0&&n<=255?Math.floor(n):1)},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>U.existsSync(e)?(U.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>U.existsSync(e)?(U.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,n=!0)=>(U.mkdirSync(e,{recursive:!!n}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,n=!1)=>U.existsSync(e)?(n?U.rmSync(e,{recursive:!0,force:!0}):U.rmdirSync(e),!0):!1,{min:1,max:2},"Removes a directory; pass true for recursive removal of a non-empty directory"),this.registerFunction("copy_file",(e,n)=>(U.copyFileSync(e,n),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,n)=>(U.renameSync(e,n),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,n)=>se.basename(e,n),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>se.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>se.join(...e),{min:0},"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>se.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,n=null)=>process.env[e]!==void 0?process.env[e]:n,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,n=null)=>process.env[e]!==void 0?process.env[e]:n,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,n)=>(process.env[e]=String(n),!0),2,"Sets an environment variable for this process and its children"),this.registerFunction("list",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("array",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("push",(e,...n)=>(e.push(...n),e),{min:1},"Pushes item(s) to end of array and returns the same array",!0,!0),this.registerFunction("pop",e=>e.pop(),1,"Pops item from end of array",!0,!0),this.registerFunction("shift",e=>e.shift(),1,"Removes and returns first element",!0,!0),this.registerFunction("unshift",(e,...n)=>(e.unshift(...n),e),{min:1},"Adds item(s) to front of array and returns the same array",!0,!0),this.registerFunction("insert",(e,n,r)=>{let s=n<0?e.length+n:n;return e.splice(s,0,r),e},3,"Inserts item at index and returns the same array",!0,!0),this.registerFunction("remove_at",(e,n)=>{let r=n<0?e.length+n:n,s=e.splice(r,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...n)=>e.concat(...n),{min:1},"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,n)=>{if(!Array.isArray(e))return e;let r=[...e];return n?r.sort((s,i)=>{let o=s?s[n]:void 0,a=i?i[n]:void 0;return o<a?-1:o>a?1:0}):r.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:String(s).localeCompare(String(i)))},{min:1,max:2},"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("unique",e=>Array.isArray(e)?Array.from(new Set(e)):[],1,"Removes duplicate elements"),this.registerFunction("flatten",e=>Array.isArray(e)?e.flat():[],1,"Flattens array one level"),this.registerFunction("first",e=>Array.isArray(e)&&e.length>0?e[0]:null,1,"Returns first element"),this.registerFunction("last",e=>Array.isArray(e)&&e.length>0?e[e.length-1]:null,1,"Returns last element"),this.registerFunction("sum",e=>Array.isArray(e)?e.reduce((n,r)=>n+(typeof r=="number"?r:Number(r)||0),0):0,1,"Calculates sum of array"),this.registerFunction("avg",e=>!Array.isArray(e)||e.length===0?0:e.reduce((r,s)=>r+(typeof s=="number"?s:Number(s)||0),0)/e.length,1,"Calculates average of array"),this.registerFunction("map",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("hash",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("from_entries",e=>Array.isArray(e)?Object.fromEntries(e):{},1,"Creates map from [key, value] pairs"),this.registerFunction("clear",e=>{if(Array.isArray(e))return e.length=0,e;if(e&&typeof e=="object"){for(let n of Object.keys(e))delete e[n];return e}return e},1,"Clears array or map",!0,!0),this.registerFunction("size",e=>Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns number of elements in array, string, or map"),this.registerFunction("system",(e,n)=>jv(e,n,{async:this.isAsyncMode}),{min:1,max:2},"Executes argv directly with shell:false and optional timeoutMs (default 60000) or options {cwd, timeoutMs, stdin}, returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",!0),this.registerFunction("run_script",(e,n=[])=>{let r=se.resolve(String(e));if(!U.existsSync(r))throw new Error(`run_script: file not found: '${r}'`);let s=U.readFileSync(r,"utf-8"),i=Array.isArray(n)?n.map(String):[],o=this.createChildEngine({args:i}),a={file:r,entryLocation:r,resolveHostModule:this.hostResolver};if(this.isAsyncMode)return(async()=>{let l=await o.runAsync(s,a),c=l.stdout??l.output.join(`
|
|
434
434
|
`)+(l.output.length>0?`
|
|
435
|
-
`:""),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??null,exit_code:u,code:u,errors:l.errors??[]}})();{let l=o.run(s,a),c=l.output.join(`
|
|
435
|
+
`:""),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??null,exit_code:u,code:u,errors:l.errors??[]}})();{let l=o.run(s,a),c=l.stdout??l.output.join(`
|
|
436
436
|
`)+(l.output.length>0?`
|
|
437
437
|
`:""),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??null,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}
|
|
438
|
-
`):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=>Mv(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 Bv(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?Gl(e):Uv(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)=>oL(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(gs(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(gs(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(gs(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=bo(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=bo(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=bo(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=bo(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=bo(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",np,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];(Rt(i,a)==null||typeof Rt(i,a)!="object")&&ct(i,a,{}),i=Rt(i,a)}return s.length>0&&ct(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=>Rt(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&Rt(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&&Rt(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...gs(e),...gs(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/),r=[],s=0;for(let i=n.length-1;i>=0&&s<3;i--){let o=n[i].trim();o.length!==0&&(s++,o.startsWith("**")&&o.endsWith("**")&&o.length>=4?o=o.slice(2,-2).trim():o.startsWith("`")&&o.endsWith("`")&&o.length>=2&&(o=o.slice(1,-1).trim()),(o==="DONE"||o==="NOTHING_TO_DO"||o==="BLOCKED"||o==="OTHER")&&r.push(o))}if(r.length===0)return null;for(let i=1;i<r.length;i++)if(r[i]!==r[0])return null;return r[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.registerFunction("parse_file_blocks",e=>XO(e),1,"Parses === FILE: path === ... === END === blocks into [{path, content}]"),this.registerFunction("format_file_blocks",e=>GO(e),1,"Formats [{path, content}] as file blocks; inverse of parse_file_blocks"),this.registerFunction("write_files",(e,n,r)=>YO(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)=>tL(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=>sL(e),1,"Parses key: value lines of the last paragraph into a map"),this.registerFunction("split_command",e=>iL(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 Vn,1,"Checks if value is a first-class function reference"),this.registerFunction("cmd_render",(e,n)=>rp(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)=>Ll(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>Ll(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="")=>So(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",cL,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",uL,{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(So(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(So(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 UO("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)=>LL(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=>Cm(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 Vn?"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=Nm(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(zm):void 0,g=typeof s=="object"?s.returnType:void 0,y=ln(e,r,h,g,u);Ev(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[qe]?{[qe]:s[qe]}:{},dryControl:Al(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,x=y.publicParams.length?y.publicParams.map(S=>S.optional?`[${S.name}]`:S.rest?`...${S.name}`:S.name):Array.from({length:E??v},(S,R)=>(R>=v?"[":"")+"arg"+(R+1)+(R>=v?"]":""));E===void 0&&!y.publicParams.some(S=>S.rest)&&x.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+x.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,[qe]:i[qe],doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...hs(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,[qe]:i[qe],doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...hs(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 qn.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 wL(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:lv(r,n.file)}}}scanAndCheck(e,n={}){return qn.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??bL(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(S=>S.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(S){let R=_L(S);throw new P(`Cannot load module '${v.name}': ${R}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!E)throw new P(`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 x;try{let S=E.declarations,R=S?.functions,N=S?.globals;Array.isArray(R)&&Array.isArray(N)&&(x={readonlyPrograms:fL(S),functions:R.map(O=>Object.freeze({...O,arity:Km(O.arity),params:O.params?Object.freeze(O.params.map(zm)):void 0,doc:Nm(O.doc)})),globals:N.map(O=>({...O})),properties:S.properties?{known:[...S.properties.known],closedTables:[...S.properties.closedTables??[]],removedGlobals:{...S.properties.removedGlobals}}:void 0})}catch{}if(E.name!==v.name||!x||typeof E.activate!="function")throw new P(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let S of x.functions){let R=typeof S.arity=="number"?{min:S.arity,max:S.arity}:S.arity;if(typeof S.name!="string"||!(E.nativeNamespace?new RegExp("^"+E.nativeNamespace+"\\.[A-Za-z_]\\w*$"):/^[a-zA-Z_]\w*$/).test(S.name)||Object.hasOwn(Co,S.name)&&S.name!=="system"||S.name==="RESUMEPOINT"||!R||!Number.isSafeInteger(R.min)||R.min<0||R.max!==void 0&&(!Number.isSafeInteger(R.max)||R.max<R.min))throw new P(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let N=m.get(S.name);if(S.override===!0&&c.has(S.name)&&!["prompt_human","run_script"].includes(S.name))throw new P(`Module '${v.name}' cannot override ${N===void 0?`core function '${S.name}'`:`function '${S.name}' declared by module '${N}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(c.has(S.name)&&!(S.override===!0&&c.get(S.name)?.isDefault))throw new P(`Module function collision: '${S.name}' in module '${v.name}'${N===void 0?"":` is already declared by module '${N}'`}`,v.line,v.column,"CHECKER",v.file);let O=ln(S.name,S.arity,S.params,S.returnType,S.doc);Ev(S.name,S.readonly,O),c.set(S.name,{arity:O.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:S.doc,params:O.nativeParams,returnType:O.returnType??void 0,readonly:S.readonly===!0||void 0,dryControl:Al(S.name,S.dryControl,O),signature:O,...hs(S)}),m.set(S.name,v.name)}for(let S of x.globals){if(!/^[a-zA-Z_]\w*$/.test(S.name)||Object.hasOwn(Co,S.name)||p.has(S.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(S.name)||this.initialGlobals.has(S.name)||n.globals?.includes(S.name))throw new P(`Module global collision or invalid name: '${S.name}'`,v.line,v.column,"CHECKER",v.file);p.add(S.name),this.builtinProviders.has(v.name)&&f.push(S.name)}x.properties&&(h.known=[...h.known,...x.properties.known],h.closedTables=[...h.closedTables??[],...x.properties.closedTables??[]],h.removedGlobals={...h.removedGlobals,...x.properties.removedGlobals}),u.push(E),d.set(E,x)}let g=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],y=new Hm(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 x of E.declarations.functions)v.message.includes(`'${x.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(x=>x.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 ms(_,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:lv(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 Ro(()=>i(a.name)));for(let a of o.functions){let l=ln(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:Al(a.name,a.dryControl,l),signature:l,...hs(a)})}}activationContext(e,n,r,s){let i=(o,a=6e4)=>{let l=qn.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=cn(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");tt(n.signal);let d=ie(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 Xl(c,m,p,n.signal,f);let h=Dv(c,m,p,f);return d?.check(),h};return{executionOrigin:n.executionOrigin,runReadonlyProgram:i,noPreflight:n.noPreflight,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:o=>{let a=ie(n);if(a){a.recordError(o);return}Nl(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=ln(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:pL(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:Al(o.name,o.dryControl,a),signature:a,...hs(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 qn.run(void 0,()=>this.dryRunIsolated(e,n))}dryRunIsolated(e,n){n=Il(n),fs(n.recoveryProbe);let r=new Hl(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?ms(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Gm]: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 qn.run(void 0,()=>this.dryRunAsyncIsolated(e,n))}async dryRunAsyncIsolated(e,n){n=Il(n),fs(n.recoveryProbe);let r=new Hl(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?ms(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Gm]: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 qn.run(void 0,()=>this.runIsolated(e,n))}runIsolated(e,n){if(n=Il(n),n.propertyOverlay)try{n={...n,propertyOverlay:oi(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=[],fs(n.recoveryProbe);let r=n.preparedCheck?ms(n.preparedCheck,n):this.scanAndCheck(e,{...n,checkPaths:n.checkPaths??!0});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,[Vm]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[Jm]: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 qn.run(void 0,()=>this.runAsyncIsolated(e,n))}async runAsyncIsolated(e,n){if(n=Il(n),n.propertyOverlay)try{n={...n,propertyOverlay:oi(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=[],fs(n.recoveryProbe);let r=n.preparedCheck?ms(n.preparedCheck,n):await this.scanAndCheckAsync(e,{...n,checkPaths:n.checkPaths??!0});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,[Vm]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[Jm]: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={}){fs(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?ms(n.preparedCheck,n):this.scanAndCheck(e,{...n,checkPaths:n.checkPaths??!0});if(ie(n)&&(!r.ast||r.diagnostics.some(d=>d.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};ie(n)?.start(),n={...n,propertyStore:n.propertyStore??new jl(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:ie(n)?new Map(cn([...this.initialGlobals])):new Map(this.initialGlobals),properties:s};i.functions.get("which")?.[qe]&&i.functions.set("which",{...i.functions.get("which"),fn:d=>Im(d,n.hostContext?.cwd??process.cwd(),ie(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=ie(n);o&&(o.propertyView=i.globals.get("PROPS"),i.globals.set("PROPS",new Ro(()=>{let d=o.prepareProperties();return lt(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 kl(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)?Rt(m,f.name):void 0,Cm)},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:ie(n)&&d!=="set_property"?(...p)=>{let h=d!=="expand"||typeof p[0]=="string"&&vo(p[0]).some(g=>typeof g!="string"&&g.kind==="property")?ie(n).prepareProperties(d==="expand"?void 0:p[0]):void 0;return lt(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=Eo(n.resumepoint,n.recoveryProbe);i.readonlyRun=c;let u=yv(c,n.signal);try{let d=[],m;try{tt(n.signal);for(let f of r.hostModules??[]){if(this.builtinProviders.has(f.name)||f.nativeNamespace||ie(n)){let g,y=()=>{if(g)return g;tt(n.signal);let b=f.activate(this.activationContext(r,n,f,c));if(lt(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),ie(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))),ie(n)&&r.hostDeclarations?.get(f)?.properties&&(ie(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)),ie(n)||r.usedProperties&&r.hostDeclarations?.get(f)?.properties&&y();continue}let h=f.activate(this.activationContext(r,n,f,c));if(lt(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),tt(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){Vt(c,f),m={...this.moduleFailure(f,r,n),errors:[...c.errors]}}ie(n)?.capture(m);let p=c.errors.length;this.collectModuleErrors(d,m,n.recoveryProbe!==void 0),ie(n)?.capture(m);for(let f of d.reverse())try{let h=ie(n)?ie(n).dispose(f):f.dispose();if(lt(h))throw h.catch(()=>{}),new Error("Async disposal requires runAsync");ie(n)?.check()}catch(h){let g=ie(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],this.finishTrace(i,m),m}finally{c.finished=!0,u()}}async runPhaseAsync(e,n={}){fs(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?ms(n.preparedCheck,n):await this.scanAndCheckAsync(e,{...n,checkPaths:n.checkPaths??!0});this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(ie(n)&&(!s.ast||s.diagnostics.some(m=>m.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};ie(n)?.start(),n={...n,propertyStore:n.propertyStore??new jl(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:ie(n)?new Map(cn([...this.initialGlobals])):new Map(this.initialGlobals),properties:i};o.functions.get("which")?.[qe]&&o.functions.set("which",{...o.functions.get("which"),fn:m=>Im(m,n.hostContext?.cwd??process.cwd(),ie(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=ie(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new Ro(()=>{let m=a.prepareProperties();return lt(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 kl(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)?Rt(p,h.name):void 0,Cm)},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:ie(n)&&m!=="set_property"?(...f)=>{let g=m!=="expand"||typeof f[0]=="string"&&vo(f[0]).some(y=>typeof y!="string"&&y.kind==="property")?ie(n).prepareProperties(m==="expand"?void 0:f[0]):void 0;return lt(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=Eo(n.resumepoint,n.recoveryProbe);o.readonlyRun=u;let d=yv(u,n.signal);try{let m=[],p;try{tt(n.signal);for(let h of s.hostModules??[]){if(this.builtinProviders.has(h.name)||h.nativeNamespace||ie(n)){let y,b,_=()=>y??=Promise.resolve().then(async()=>{tt(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(ie(n)?.sealed){try{await v.dispose()}catch{}throw new Kt("Dry pass finished")}return b=v,m.push(v),ie(n)?.own(v),this.bindModule(h,v,s,o),tt(n.signal),v});h.nativeNamespace&&(o.nativeImports??=new Map,o.nativeImports.set(h.name,_)),this.installBuiltinStubs(h,s,o,v=>async(...E)=>{let x=await _();return ie(n)?.check(),o.functions.get(v).fn(...E)},async v=>(await _(),o.globals.get(v))),ie(n)&&s.hostDeclarations?.get(h)?.properties&&(ie(n).propertyLoads.push(_),i.addSource(h.name,()=>{if(!b?.loadProperties)throw Error("Provider properties unavailable");return b.loadProperties()},s.hostDeclarations.get(h).properties.known)),ie(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),tt(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){Vt(u,h),p={...this.moduleFailure(h,s,n),errors:[...u.errors]}}ie(n)?.capture(p);let f=u.errors.length;this.collectModuleErrors(m,p,n.recoveryProbe!==void 0),ie(n)?.capture(p);for(let h of m.reverse())try{let g=ie(n)?ie(n).dispose(h):h.dispose();ie(n)?await ie(n).wait(g):await g}catch(g){let y=ie(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],this.finishTrace(o,p),p}finally{u.finished=!0,d()}}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=[],{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??Eo(n.resumepoint,n.recoveryProbe),m,p,f=n.trace&&!ie(n)?new co(n.trace):void 0;s.tracer=f;try{m=new Wl(s.functions,y=>{o.push(y),f?.output(y+`
|
|
439
|
-
`),n.stdout?.(y)},!1,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,ie(n),n.noPreflight,s.nativeImports),m.childEngineFactory=y=>this.createChildEngine(y),m.compileOptions=n,m.executionOrigin=n.executionOrigin,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),y}let g=m.getRecordedErrors();return this.outputLogs=[...o],this.lastRecordedErrors=g,{success:!0,value:h,diagnostics:l,output:o,errors:g,resourceRun:p}}catch(h){Vt(d,h);let g=[...d.errors];if(this.lastRecordedErrors=g,h instanceof $t||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 P?h.line:1,b=h instanceof P?h.column:1,_=h instanceof P&&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??Eo(n.resumepoint,n.recoveryProbe),d,m,p=n.trace&&!ie(n)?new co(n.trace):void 0;s.tracer=p;try{d=new Wl(s.functions,g=>{o.push(g),p?.output(g+`
|
|
440
|
-
|
|
438
|
+
`):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=>Mv(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 Bv(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?Gl(e):Uv(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)=>oL(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(gs(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(gs(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(gs(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=bo(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=bo(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=bo(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=bo(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=bo(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",np,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];(Rt(i,a)==null||typeof Rt(i,a)!="object")&&ct(i,a,{}),i=Rt(i,a)}return s.length>0&&ct(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=>Rt(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&Rt(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&&Rt(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...gs(e),...gs(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/),r=[],s=0;for(let i=n.length-1;i>=0&&s<3;i--){let o=n[i].trim();o.length!==0&&(s++,o.startsWith("**")&&o.endsWith("**")&&o.length>=4?o=o.slice(2,-2).trim():o.startsWith("`")&&o.endsWith("`")&&o.length>=2&&(o=o.slice(1,-1).trim()),(o==="DONE"||o==="NOTHING_TO_DO"||o==="BLOCKED"||o==="OTHER")&&r.push(o))}if(r.length===0)return null;for(let i=1;i<r.length;i++)if(r[i]!==r[0])return null;return r[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.registerFunction("parse_file_blocks",e=>XO(e),1,"Parses === FILE: path === ... === END === blocks into [{path, content}]"),this.registerFunction("format_file_blocks",e=>GO(e),1,"Formats [{path, content}] as file blocks; inverse of parse_file_blocks"),this.registerFunction("write_files",(e,n,r)=>YO(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)=>tL(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=>sL(e),1,"Parses key: value lines of the last paragraph into a map"),this.registerFunction("split_command",e=>iL(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 Vn,1,"Checks if value is a first-class function reference"),this.registerFunction("cmd_render",(e,n)=>rp(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)=>Ll(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>Ll(e,n,"printf"),{min:1},"Formats %s, %d, %f and %% with the sprintf rules and writes exactly that text to stdout (no newline added)",!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="")=>So(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",cL,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",uL,{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(So(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(So(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 UO("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)=>LL(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=>Cm(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 Vn?"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=Nm(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(zm):void 0,g=typeof s=="object"?s.returnType:void 0,y=ln(e,r,h,g,u);Ev(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[qe]?{[qe]:s[qe]}:{},dryControl:Al(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,x=y.publicParams.length?y.publicParams.map(S=>S.optional?`[${S.name}]`:S.rest?`...${S.name}`:S.name):Array.from({length:E??v},(S,R)=>(R>=v?"[":"")+"arg"+(R+1)+(R>=v?"]":""));E===void 0&&!y.publicParams.some(S=>S.rest)&&x.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+x.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,[qe]:i[qe],doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...hs(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,[qe]:i[qe],doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...hs(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 qn.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 wL(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:lv(r,n.file)}}}scanAndCheck(e,n={}){return qn.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??bL(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(S=>S.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(S){let R=_L(S);throw new P(`Cannot load module '${v.name}': ${R}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!E)throw new P(`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 x;try{let S=E.declarations,R=S?.functions,N=S?.globals;Array.isArray(R)&&Array.isArray(N)&&(x={readonlyPrograms:fL(S),functions:R.map(O=>Object.freeze({...O,arity:Km(O.arity),params:O.params?Object.freeze(O.params.map(zm)):void 0,doc:Nm(O.doc)})),globals:N.map(O=>({...O})),properties:S.properties?{known:[...S.properties.known],closedTables:[...S.properties.closedTables??[]],removedGlobals:{...S.properties.removedGlobals}}:void 0})}catch{}if(E.name!==v.name||!x||typeof E.activate!="function")throw new P(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let S of x.functions){let R=typeof S.arity=="number"?{min:S.arity,max:S.arity}:S.arity;if(typeof S.name!="string"||!(E.nativeNamespace?new RegExp("^"+E.nativeNamespace+"\\.[A-Za-z_]\\w*$"):/^[a-zA-Z_]\w*$/).test(S.name)||Object.hasOwn(Co,S.name)&&S.name!=="system"||S.name==="RESUMEPOINT"||!R||!Number.isSafeInteger(R.min)||R.min<0||R.max!==void 0&&(!Number.isSafeInteger(R.max)||R.max<R.min))throw new P(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let N=m.get(S.name);if(S.override===!0&&c.has(S.name)&&!["prompt_human","run_script"].includes(S.name))throw new P(`Module '${v.name}' cannot override ${N===void 0?`core function '${S.name}'`:`function '${S.name}' declared by module '${N}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(c.has(S.name)&&!(S.override===!0&&c.get(S.name)?.isDefault))throw new P(`Module function collision: '${S.name}' in module '${v.name}'${N===void 0?"":` is already declared by module '${N}'`}`,v.line,v.column,"CHECKER",v.file);let O=ln(S.name,S.arity,S.params,S.returnType,S.doc);Ev(S.name,S.readonly,O),c.set(S.name,{arity:O.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:S.doc,params:O.nativeParams,returnType:O.returnType??void 0,readonly:S.readonly===!0||void 0,dryControl:Al(S.name,S.dryControl,O),signature:O,...hs(S)}),m.set(S.name,v.name)}for(let S of x.globals){if(!/^[a-zA-Z_]\w*$/.test(S.name)||Object.hasOwn(Co,S.name)||p.has(S.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(S.name)||this.initialGlobals.has(S.name)||n.globals?.includes(S.name))throw new P(`Module global collision or invalid name: '${S.name}'`,v.line,v.column,"CHECKER",v.file);p.add(S.name),this.builtinProviders.has(v.name)&&f.push(S.name)}x.properties&&(h.known=[...h.known,...x.properties.known],h.closedTables=[...h.closedTables??[],...x.properties.closedTables??[]],h.removedGlobals={...h.removedGlobals,...x.properties.removedGlobals}),u.push(E),d.set(E,x)}let g=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],y=new Hm(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 x of E.declarations.functions)v.message.includes(`'${x.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(x=>x.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 ms(_,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:lv(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 Ro(()=>i(a.name)));for(let a of o.functions){let l=ln(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:Al(a.name,a.dryControl,l),signature:l,...hs(a)})}}activationContext(e,n,r,s){let i=(o,a=6e4)=>{let l=qn.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=cn(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");tt(n.signal);let d=ie(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 Xl(c,m,p,n.signal,f);let h=Dv(c,m,p,f);return d?.check(),h};return{executionOrigin:n.executionOrigin,runReadonlyProgram:i,noPreflight:n.noPreflight,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:o=>{let a=ie(n);if(a){a.recordError(o);return}Nl(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=ln(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:pL(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:Al(o.name,o.dryControl,a),signature:a,...hs(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 qn.run(void 0,()=>this.dryRunIsolated(e,n))}dryRunIsolated(e,n){n=Il(n),fs(n.recoveryProbe);let r=new Hl(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?ms(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Gm]: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 qn.run(void 0,()=>this.dryRunAsyncIsolated(e,n))}async dryRunAsyncIsolated(e,n){n=Il(n),fs(n.recoveryProbe);let r=new Hl(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?ms(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Gm]: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 qn.run(void 0,()=>this.runIsolated(e,n))}runIsolated(e,n){if(n=Il(n),n.propertyOverlay)try{n={...n,propertyOverlay:oi(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=[],fs(n.recoveryProbe);let r=n.preparedCheck?ms(n.preparedCheck,n):this.scanAndCheck(e,{...n,checkPaths:n.checkPaths??!0});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,[Vm]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[Jm]: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=[],i="";for(let o of r){if(n.signal?.aborted)return{success:!1,exitCode:1,output:s,diagnostics:[{...o.site,severity:"error",message:"Execution aborted"}],preflight:e};s.push(o.text),i+=o.raw?o.text:o.text+`
|
|
439
|
+
`;try{n.stdout?.(o.text,o.raw)}catch(a){return{success:!1,exitCode:1,output:s,diagnostics:[{...o.site,severity:"error",message:"Error in host function '"+o.name+"': "+(a instanceof Error?a.message:String(a))}],preflight:e}}}return this.outputLogs=[...s],{success:!1,exitCode:1,output:s,stdout:i,diagnostics:e.stop?[e.diagnostics.filter(o=>o.severity==="error"&&o.line===e.stop.line&&o.column===e.stop.column&&(o.message===e.stop.reason||o.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(o=>o.severity==="error"),preflight:e}}}async runAsync(e,n={}){return qn.run(void 0,()=>this.runAsyncIsolated(e,n))}async runAsyncIsolated(e,n){if(n=Il(n),n.propertyOverlay)try{n={...n,propertyOverlay:oi(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=[],fs(n.recoveryProbe);let r=n.preparedCheck?ms(n.preparedCheck,n):await this.scanAndCheckAsync(e,{...n,checkPaths:n.checkPaths??!0});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,[Vm]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[Jm]: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={}){fs(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?ms(n.preparedCheck,n):this.scanAndCheck(e,{...n,checkPaths:n.checkPaths??!0});if(ie(n)&&(!r.ast||r.diagnostics.some(d=>d.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};ie(n)?.start(),n={...n,propertyStore:n.propertyStore??new jl(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:ie(n)?new Map(cn([...this.initialGlobals])):new Map(this.initialGlobals),properties:s};i.functions.get("which")?.[qe]&&i.functions.set("which",{...i.functions.get("which"),fn:d=>Im(d,n.hostContext?.cwd??process.cwd(),ie(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=ie(n);o&&(o.propertyView=i.globals.get("PROPS"),i.globals.set("PROPS",new Ro(()=>{let d=o.prepareProperties();return lt(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 kl(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)?Rt(m,f.name):void 0,Cm)},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:ie(n)&&d!=="set_property"?(...p)=>{let h=d!=="expand"||typeof p[0]=="string"&&vo(p[0]).some(g=>typeof g!="string"&&g.kind==="property")?ie(n).prepareProperties(d==="expand"?void 0:p[0]):void 0;return lt(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=Eo(n.resumepoint,n.recoveryProbe);i.readonlyRun=c;let u=yv(c,n.signal);try{let d=[],m;try{tt(n.signal);for(let f of r.hostModules??[]){if(this.builtinProviders.has(f.name)||f.nativeNamespace||ie(n)){let g,y=()=>{if(g)return g;tt(n.signal);let b=f.activate(this.activationContext(r,n,f,c));if(lt(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),ie(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))),ie(n)&&r.hostDeclarations?.get(f)?.properties&&(ie(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)),ie(n)||r.usedProperties&&r.hostDeclarations?.get(f)?.properties&&y();continue}let h=f.activate(this.activationContext(r,n,f,c));if(lt(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),tt(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){Vt(c,f),m={...this.moduleFailure(f,r,n),errors:[...c.errors]}}ie(n)?.capture(m);let p=c.errors.length;this.collectModuleErrors(d,m,n.recoveryProbe!==void 0),ie(n)?.capture(m);for(let f of d.reverse())try{let h=ie(n)?ie(n).dispose(f):f.dispose();if(lt(h))throw h.catch(()=>{}),new Error("Async disposal requires runAsync");ie(n)?.check()}catch(h){let g=ie(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],this.finishTrace(i,m),m}finally{c.finished=!0,u()}}async runPhaseAsync(e,n={}){fs(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?ms(n.preparedCheck,n):await this.scanAndCheckAsync(e,{...n,checkPaths:n.checkPaths??!0});this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(ie(n)&&(!s.ast||s.diagnostics.some(m=>m.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};ie(n)?.start(),n={...n,propertyStore:n.propertyStore??new jl(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:ie(n)?new Map(cn([...this.initialGlobals])):new Map(this.initialGlobals),properties:i};o.functions.get("which")?.[qe]&&o.functions.set("which",{...o.functions.get("which"),fn:m=>Im(m,n.hostContext?.cwd??process.cwd(),ie(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=ie(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new Ro(()=>{let m=a.prepareProperties();return lt(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 kl(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)?Rt(p,h.name):void 0,Cm)},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:ie(n)&&m!=="set_property"?(...f)=>{let g=m!=="expand"||typeof f[0]=="string"&&vo(f[0]).some(y=>typeof y!="string"&&y.kind==="property")?ie(n).prepareProperties(m==="expand"?void 0:f[0]):void 0;return lt(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=Eo(n.resumepoint,n.recoveryProbe);o.readonlyRun=u;let d=yv(u,n.signal);try{let m=[],p;try{tt(n.signal);for(let h of s.hostModules??[]){if(this.builtinProviders.has(h.name)||h.nativeNamespace||ie(n)){let y,b,_=()=>y??=Promise.resolve().then(async()=>{tt(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(ie(n)?.sealed){try{await v.dispose()}catch{}throw new Kt("Dry pass finished")}return b=v,m.push(v),ie(n)?.own(v),this.bindModule(h,v,s,o),tt(n.signal),v});h.nativeNamespace&&(o.nativeImports??=new Map,o.nativeImports.set(h.name,_)),this.installBuiltinStubs(h,s,o,v=>async(...E)=>{let x=await _();return ie(n)?.check(),o.functions.get(v).fn(...E)},async v=>(await _(),o.globals.get(v))),ie(n)&&s.hostDeclarations?.get(h)?.properties&&(ie(n).propertyLoads.push(_),i.addSource(h.name,()=>{if(!b?.loadProperties)throw Error("Provider properties unavailable");return b.loadProperties()},s.hostDeclarations.get(h).properties.known)),ie(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),tt(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){Vt(u,h),p={...this.moduleFailure(h,s,n),errors:[...u.errors]}}ie(n)?.capture(p);let f=u.errors.length;this.collectModuleErrors(m,p,n.recoveryProbe!==void 0),ie(n)?.capture(p);for(let h of m.reverse())try{let g=ie(n)?ie(n).dispose(h):h.dispose();ie(n)?await ie(n).wait(g):await g}catch(g){let y=ie(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],this.finishTrace(o,p),p}finally{u.finished=!0,d()}}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(g=>g.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', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:n.file}],output:o};let m=i??Eo(n.resumepoint,n.recoveryProbe),p,f,h=n.trace&&!ie(n)?new co(n.trace):void 0;s.tracer=h;try{p=new Wl(s.functions,(b,_)=>{o.push(b);let v=_?b:b+`
|
|
440
|
+
`;a+=v,h?.output(v),n.stdout?.(b,_)},!1,s.globals,n.stderr,this.promptHumanConfig,m,n.hostContext?.platform??n.platform??process.platform,ie(n),n.noPreflight,s.nativeImports),p.childEngineFactory=b=>this.createChildEngine(b),p.compileOptions=n,p.executionOrigin=n.executionOrigin,p.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},p.warningDiagnostics=c,p.abortSignal=n.signal,p.recoverScopedReads=r.recoverScopedReads??new WeakMap,p.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,f=this.trackResourceRun(p.resources),h&&(p.tracer=h,h.begin(n.file??"<main>",e,s.globals));let g;try{g=p.evaluateProgram(l)}catch(b){throw h&&!b?.isControlFlow&&b?.name!=="LMScriptExit"&&h.error(b),b}let y=p.getRecordedErrors();return this.outputLogs=[...o],this.lastRecordedErrors=y,{success:!0,value:g,diagnostics:c,output:o,errors:y,resourceRun:f,stdout:a}}catch(g){Vt(m,g);let y=[...m.errors];if(this.lastRecordedErrors=y,g instanceof $t||g?.name==="LMScriptExit"||g?.isControlFlow){this.outputLogs=[...o];let E=typeof g.exitCode=="number"?g.exitCode:0;return{success:E===0,value:E,exitCode:E,diagnostics:c,output:o,errors:y,resourceRun:f,stdout:a}}let b=g instanceof P?g.line:1,_=g instanceof P?g.column:1,v=g instanceof P&&g.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...c,{message:g?.message||String(g),line:b,column:_,severity:"error",file:v}],output:o,errors:y,resourceRun:f,stdout:a}}}async executeAsync(e,n,r,s,i){let o=[],a="",{ast:l}=r,c=[...r.diagnostics];if(c.filter(h=>h.severity==="error").length>0||!l)return this.outputLogs=o,this.lastRecordedErrors=[],{success:!1,diagnostics:c,output:o,errors:[]};let d=i??Eo(n.resumepoint,n.recoveryProbe),m,p,f=n.trace&&!ie(n)?new co(n.trace):void 0;s.tracer=f;try{m=new Wl(s.functions,(y,b)=>{o.push(y);let _=b?y:y+`
|
|
441
|
+
`;a+=_,f?.output(_),n.stdout?.(y,b)},!0,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,ie(n),n.noPreflight,s.nativeImports),m.childEngineFactory=y=>this.createChildEngine(y),m.compileOptions=n,m.executionOrigin=n.executionOrigin,m.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},m.warningDiagnostics=c,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=await m.evaluateProgramAsync(l)}catch(y){throw f&&!y?.isControlFlow&&y?.name!=="LMScriptExit"&&f.error(y),y}let g=m.getRecordedErrors();return this.outputLogs=[...o],this.lastRecordedErrors=g,{success:!0,value:h,diagnostics:c,output:o,errors:g,resourceRun:p,stdout:a}}catch(h){Vt(d,h);let g=[...d.errors];if(this.lastRecordedErrors=g,h instanceof $t||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:c,output:o,errors:g,resourceRun:p,stdout:a}}let y=h instanceof P?h.line:1,b=h instanceof P?h.column:1,_=h instanceof P&&h.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...c,{message:h?.message||String(h),line:y,column:b,severity:"error",file:_}],output:o,errors:g,resourceRun:p,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??Jv(n.returnType),readonly:n.readonly,dryControl:n.dryControl,signature:n.signature}):void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};Mm=se.basename(tp(import.meta.url));(Mm==="lmscript.ts"||Mm==="lmscript.js"||Mm==="lmscript")&&process.argv[1]&&U.existsSync(process.argv[1])&&U.realpathSync(tp(import.meta.url))===U.realpathSync(se.resolve(process.argv[1]))&&PL()});function DL(t,e,n){let r=ln(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 FL(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 up(t){let e=ln(t.name,t.arity,t.params,t.returnType,t.doc),n=e.dryrunIndex===void 0&&t.doc?.signature?t.doc.signature:DL(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 $L(t,e){let n=t.getFunctionMetadata(e);if(n)return up({name:e,arity:n.arity,params:n.params,returnType:n.returnType??void 0,doc:t.getFunctionDoc(e)})}function eb(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,$L(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,up({...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.
|
|
441
442
|
Example (run each statement on its own line):
|
|
442
443
|
args = cmd program a=" " b="adsfa";
|
|
443
444
|
assert(json_stringify(args) == '["program","a= ","b=adsfa"]');
|
|
@@ -508,17 +509,17 @@ Calls return {status:"ok", result} | {status:"error", error:{code, message}} | {
|
|
|
508
509
|
`).slice(-12).join(`
|
|
509
510
|
`)));return c.stdout},s=(c,u,d)=>Kn(n(c,u,d),r),i=(c,u,d)=>Kn(s(c,["rev-parse","--verify","--end-of-options",ib(u,"revision")],d),Jl),o=({r:c})=>c.code===1&&!c.stderr&&!c.signal&&!c.timed_out,a=(c,u)=>Kn(n(c,["symbolic-ref","--quiet","--short","HEAD"],u),d=>o(d)?null:Jl(r(d)));return{functions:{"git.status":(c,u)=>Kn(s(c,["status","--porcelain=v2","-z","--branch","--ahead-behind","--untracked-files=all","--renames"],u),d=>{let m=ob(d);return m.detached?Kn(a(c,u),p=>(p!==null&&(m.branch=p,m.detached=!1),m)):m}),"git.branch":a,"git.rev_parse":i,"git.remotes":(c,u)=>Kn(n(c,["config","--null","--get-regexp","^remote\\..*\\.url$"],u),d=>{if(o(d))return[];let p=r(d).split("\0");if(p.pop()!=="")throw Error("git: incomplete remote config");return p.map(f=>{let h=f.indexOf(`
|
|
510
511
|
`),g=f.slice(0,h).match(/^remote\.(.+)\.url$/);if(h<0||!g)throw Error("git: malformed remote config");return{name:g[1],url:f.slice(h+1)}})}),"git.log":(c,u,d)=>{if(typeof u!="number"||!Number.isInteger(u)||u<0||u>1e4)throw Error("git.log: n must be an integer from 0 to 10000");return Kn(n(c,["rev-parse","--verify","--quiet","--end-of-options","HEAD"],d),m=>o(m)?[]:(r(m),u===0?[]:Kn(s(c,["log","--no-show-signature","--encoding=UTF-8","-n",String(u),"--format=%H%x00%an%x00%aI%x00%B","-z","--"],d),ab)))}},globals:{},dispose(){}}}var Kn,Jl,HL,cb=L(()=>{"use strict";Kn=(t,e)=>t instanceof Promise?t.then(e):e(t),Jl=t=>t.endsWith(`
|
|
511
|
-
`)?t.slice(0,-1):t,HL=t=>t.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1<redacted>@").replace(/([?&](?:access_token|token|password|passwd|api_key)=)[^&\s"'<>]+/gi,"$1<redacted>")});var LV,Sr,Po,XL,GL,mp,JL,pp,he,dp,_n,Vl,Tr,Kl,Yl,li,ub,db,mb,ci,zl,VL,pb,fb,ht,zn=L(()=>{"use strict";LV=1,Sr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Sr(e);Object.freeze(t)}return t},Po=Sr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed","service_unavailable","outcome_unknown"]),XL=Sr({status:"string",error:"string|null",code:"ErrorCode?"}),GL=Sr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),mp=Sr(["Provider1.Provider","Provider1.Model1","Provider2.Provider","Provider2.Model1","Provider3.Provider","Provider3.Model1"]),JL=Sr(["Provider1","Provider2","Provider3"]),pp=Sr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),he={name:"ctx",type:"context"},dp={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},_n={name:"teamfile",type:"string"},Vl={name:"alias",type:"string"},Tr={name:"prompt",type:"string"},Kl={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"alias",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"},{name:"sessiondir",type:"string"},{name:"sessionid",type:"string"}]},Yl=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],li={name:"options",type:"map",optional:!0,keys:Yl},ub={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},db={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},mb={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},ci={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},zl={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},VL=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"}],pb={name:"options",type:"map",optional:!0,keys:VL},fb={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},ht=Sr([{name:"resolveProfilePath",implemented:!0,params:[he,dp],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[he,dp],statuses:["ok","error"],results:{error:"string|null",profile:"{path,raw,config}",values:"{Provider1..3,Model1..3,Directory,NonInteractive}",path:"string?",line:"number?",column:"number?"},effects:["file-read"],summary:"Read and validate the complete init profile without discovery or writes."},{name:"profileValues",implemented:!0,params:[{name:"config",type:"map"}],statuses:["ok","error"],results:{error:"string|null",Provider1:"string",Provider2:"string",Provider3:"string",Model1:"string",Model2:"string",Model3:"string"},effects:[],summary:"Validate and map slots to first-model environment values."},{name:"readPrompts",implemented:!0,params:[he,{name:"path",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"single",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",prompts:"string[]"},effects:["file-read"],summary:"Read prompt records without exiting the caller.",scriptBinding:{name:"lm_read_prompts",params:[{name:"batchfile",type:"string"},{name:"single",type:"boolean",optional:!0}]}},{name:"listMembers",implemented:!0,params:[he,_n],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[_n]}},{name:"resolveMember",implemented:!0,params:[he,_n,Vl],statuses:["ok","not_found","error"],results:{error:"string|null",member:"Member",isLead:"boolean",teamfile:"string"},effects:["file-read","db"],summary:"Resolve a team member with an explicit missing outcome.",scriptBinding:{name:"lm_member",params:[_n,Vl]}},{name:"lintTeam",implemented:!0,params:[he,_n],statuses:["ok","error"],results:{error:"string|null",errors:"list",warnings:"list",counts:"map"},effects:["file-read","db"],summary:"Return structured lint findings.",scriptBinding:{name:"lm_lint",params:[_n]}},{name:"seedTeam",implemented:!0,params:[he,_n,ub],statuses:["ok","error"],results:{error:"string|null",seeded:"SeededMember[]"},effects:["provider","db","file-write"],summary:"Seed a team with explicit optional preambles.",scriptBinding:{name:"lm_seed",params:[_n,ub]}},{name:"promptAgent",implemented:!0,params:[he,Kl,Tr,li],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...fb,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[Kl,Tr,li]}},{name:"promptMember",implemented:!0,params:[he,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"prompt",type:"string",required:!0},{name:"messageType",type:"string"},...Yl]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[_n,Vl,Tr,{name:"options",type:"map",optional:!0,keys:[...Yl,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[he,{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"workspace",type:"string"},{name:"all",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",sessions:"Session[]"},effects:["file-read"],summary:"List native sessions in an explicit workspace.",scriptBinding:{name:"lm_session_list",params:[{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"sessiondir",type:"string"},{name:"all",type:"boolean"}]}]}},{name:"deleteSession",implemented:!0,params:[he,ci,mb],statuses:["deleted","not_found","busy","error"],results:{error:"string|null"},effects:["provider","file-write"],summary:"Delete a session only with explicit force admission.",scriptBinding:{name:"lm_session_delete",params:[Kl,{...mb,optional:!0}]}},{name:"getSession",implemented:!0,params:[he,ci],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages.",scriptBinding:{name:"lm_session_get",params:[ci]}},{name:"reserveSession",implemented:!0,params:[he,ci],statuses:["ok","busy","error"],results:{error:"string|null",reservation:"SessionReservation"},effects:[],summary:"Reserve context-local handoff admission and return a capability."},{name:"releaseSession",implemented:!0,params:[he,ci,{name:"reservation",type:"SessionReservation",optional:!0}],statuses:["ok","error"],results:{error:"string|null"},effects:[],summary:"Release context-local handoff admission; an optional capability makes owned cleanup idempotent and replacement-safe."},{name:"openTeamBatch",returnsResource:!0,implemented:!0,params:[he,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"promptCount",type:"number",required:!0},{name:"legacy",type:"boolean"},...Yl]}],statuses:["ok","busy","error"],results:{error:"string|null",batch:"opaque context-bound BatchRef"},effects:["provider","db"],summary:"Open a managed team batch; member-map composition remains language-owned."},{name:"batchTurn",implemented:!0,params:[he,{name:"batch",type:"BatchRef"},Tr,{name:"index",type:"number"},{name:"total",type:"number"}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn an owned live batch reference."},{name:"closeBatch",implemented:!0,params:[he,{name:"batch",type:"BatchRef"},{name:"options",type:"map",keys:[{name:"status",type:"string",required:!0,values:["done","error","cancelled"]},{name:"error",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close an owned batch."},{name:"readRatelimits",implemented:!0,params:[he,db],statuses:["ok","error"],results:{error:"string|null",readings:"list"},effects:["file-read","network"],summary:"Read provider rate-limit data.",scriptBinding:{name:"lm_ratelimit_readings",params:[db]}},{name:"openTerminal",implemented:!0,params:[he,{name:"target",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0}]},{name:"streams",type:"map",keys:[{name:"stdin",type:"stream",required:!0},{name:"stdout",type:"stream",required:!0},{name:"stderr",type:"stream",required:!0}]}],statuses:["ok","error"],results:{error:"string|null",code:"number|null",signal:"string|null"},effects:["provider","db","tty"],summary:"Open a native terminal with caller-supplied streams.",scriptBinding:{name:"lm_terminal",params:[_n,Vl]}},{name:"sessionAdmission",implemented:!0,params:[he,ci],statuses:["ok","busy","error"],results:{error:"string|null",busyReason:"turn|handoff?"},effects:[],summary:"Query context-local session admission without exposing mutable sets."},{name:"promptReservedAgent",implemented:!0,params:[he,{name:"reservation",type:"SessionReservation"},Kl,Tr,li],statuses:["ok","busy","stalled","empty","error"],results:{...fb,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[he,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Synchronously release one batch on a close deadline without cancelling unrelated batches."},{name:"inspectBatch",implemented:!0,params:[he,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null",id:"string",closed:"boolean",member:"Member",rootId:"number|null"},effects:[],summary:"Read batch metadata without exposing native transports or lease capabilities."},{name:"openNativeSession",returnsResource:!0,implemented:!0,params:[he,{name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},li],statuses:["ok","busy","error"],results:{error:"string|null",session:"opaque context-bound NativeSessionRef"},effects:["provider","db","file-read"],summary:"Open a script-owned native conversation with existing receiver admission."},{name:"nativeSessionTurn",implemented:!0,params:[he,{name:"session",type:"NativeSessionRef"},Tr],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Record one unframed conversational turn through the existing recorder."},{name:"closeNativeSession",implemented:!0,params:[he,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close a script-owned native conversation and release its lease."},{name:"finalizeNativeSessionSync",implemented:!0,params:[he,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Critical synchronous native conversation lease release."},{name:"nativeSessionRequest",implemented:!0,params:[he,zl,Tr,li],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Send a stateless native-id turn to a qualified conversation in the configured running lmbee service.",scriptBinding:{name:"lm_session_turn",params:[zl,Tr,li]}},{name:"nativeSessionClose",implemented:!0,params:[he,zl],statuses:["ok","busy","error"],results:{error:"string|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Close an idle service-hosted native conversation; an absent entry is already closed.",scriptBinding:{name:"lm_session_close",params:[zl]}},{name:"loadProperties",implemented:!0,params:[he,dp],statuses:["ok","error"],results:{error:"string|null",path:"string",properties:"map",flat:"map",line:"number?",column:"number?"},effects:["file-read"],summary:"Read the complete hierarchical init.toml properties document through the canonical reader."},{name:"listRunning",implemented:!0,params:[he,pb],statuses:["ok","error"],results:{error:"string|null",running:"RunningRow[]",dead:"DeadRow[]",idle:"IdleRow[]"},effects:["db"],summary:"DB-wide view of tracked invocation activity. Observation only; dispatch and branch on status busy, never gate on this.",scriptBinding:{name:"lm_running",params:[pb]}}])});var gb,hb=L(()=>{"use strict";gb=[{name:"lm_session_turn",category:"lmctl Automation",signature:"lm_session_turn(member, prompt, options = {})",description:"Sends one stateless turn to a service-hosted conversation addressed by provider and native sessionid. Qualified providers require the already-running lmbee endpoint in LMCTL_SERVICE_ENDPOINT. idleTimeoutMs controls idle retention (default 300000 ms; zero disables expiry). An accepted turn finishes and is recorded after the caller disconnects. World failures never throw. This is an effect and is skipped in dry-run with a map dummy; one-shot providers stay local.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid; optional sessiondir, model, effort"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode and idleTimeoutMs"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id, code?, outcome?, service_epoch?, connection_epoch?, connection_state? }"},example:'res = lm_session_turn({ provider: "kimi", sessionid: "native-1" }, "Continue");'},{name:"lm_session_close",category:"lmctl Automation",signature:"lm_session_close(member)",description:"Requests closure of the service-owned conversation addressed by provider and native sessionid. Idle conversations close, active conversations return busy, and an absent entry is already closed. World failures never throw; dry-run returns a map dummy.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid"}],returns:{type:"map",description:'{ status: "ok"|"busy"|"error", error: string|null, code?: string }'},example:'closed = lm_session_close({ provider: "kimi", sessionid: "native-1" });'},{name:"prompt_human",category:"lmctl Automation",signature:"prompt_human([question|session])",description:"Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. A handoff reservation is host-owned and released on EOF, provider failure, cancellation, context finalization or signal; the returned outcome is an ordinary map. Core prompt options apply only without this binding."},{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens the only returned production resource: an async-only opaque read-only id handle. The first receiving lexical binding owns it until scope exit; aliases borrow, and returning/storing/coercing the handle is refused at runtime. Teamfile batches keep existing admission. A member map with provider and sessionid locks an existing native session: one known owner uses its teamfile and alias lease, otherwise the native address is the lease key. Native handles reuse one persistent conversation when supported, or one provider process per turn, and record each turn. A member map without sessionid retains the fresh-agent batch path. Dry-run simulates these resource operations without provider or lease activity.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"ResourceHandle|null",description:"Opaque id-only handle, or null on admission refusal; no mutable map or transferable authority"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index?, total?)",description:"Native handles accept handle and prompt only for dependent conversational turns; teamfile and fresh-member batches still require index and total. Each native turn uses the existing transcript and usage recorder.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Same-run live owner/borrower handle or authorized id reference"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"Teamfile or fresh-member form only: 1-based prompt index"},{name:"total",type:"number",description:"Teamfile or fresh-member form only: total prompts"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'empty'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch resource. Native handles close their conversation and release the owned lease; scope exit, script error, exit, and signals also close them. Teamfile batches retain tracked-invocation and bundle cleanup.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Authorized handle/id; repeat close joins the same operation"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns an ordinary result map. The host owns its pending per-turn lease and critical release; no returned resource or script closer.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_agent_message",category:"lmctl Automation",signature:"lm_agent_message(member, prompt, options = {})",description:"Like lm_agent, and also returns the completed turn as lmctl stores and prices it: model, token buckets and the lmprice cost of that turn. Cost is null (with costUnavailableReason) when the provider does not record enough accounting.",parameters:[{name:"member",type:"map",description:"As for lm_agent"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) As for lm_agent"}],returns:{type:"map",description:"lm_agent's { status, reply, error, message_id, team_chat_log_id } plus message: null | { role, content, provider, sessionid, model, usage: { input, cachedInput, cacheWrite, output }, costUsd, costUnavailableReason, priceRoute, priceDataSource }"},example:'agent = { provider: "miniplayer", model: "deepseek/deepseek-flash" }; res = lm_agent_message(agent, "Say hi"); println(res.message.costUsd);'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, sessions: [{ provider, sessionid, sessiondir, modifiedAt }] }'},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_get",category:"lmctl Automation",signature:"lm_session_get(target)",description:"Reads native session messages. Returns messages in chronological order, or not_found if the session does not exist.",parameters:[{name:"target",type:"map",description:"Session target map with required provider and sessionid strings"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, messages?: [{ role: string, content: string }] }'},example:'session = lm_session_get({ provider: "codex", sessionid: "sess-123" }); if (session.status == "ok") { println(len(session.messages)); }'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_running",category:"lmctl Automation",signature:"lm_running(options = {})",description:'Returns active tracked-invocation snapshot. Options: since (e.g. "1h", "2d"). observation only; dispatch and branch on status busy, never gate on this.',parameters:[{name:"options",type:"map",description:'(optional) Query options: since (duration string like "1h", "2d")'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, running: map[], dead: map[], idle: map[] }'},example:'snapshot = lm_running(); if (snapshot.status == "ok") { println(len(snapshot.running)); }'},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, seeded: [{ alias, provider, sessionid, sessiondir, model }] }'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. The host attempts checked lock/invocation release on completion, failure, cancellation or signal and reports unresolved failures, including a busy database; the returned outcome is an ordinary map. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, exit_code: number, signal: string|null, code?: string }'},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", error: null, readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, members: [{ alias, provider, model, sessionid, sessiondir }] }'},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, member?: { alias, provider, model, sessionid, sessiondir }, isLead?: bool, teamfile?: string }'},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}]});function G(t){try{if(t instanceof Error){let e=t.message;if(typeof e=="string")return e}return String(t)}catch{return"Unprintable error"}}function ge(t){return{...t,status:"ok",error:null}}function H(t,e,n){return{...n,status:"error",code:t,error:e}}var yt=L(()=>{"use strict"});function _b(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?Do:yb}var yb,Do,fp=L(()=>{"use strict";yb="root_teamfile <> '(direct)'",Do=yb+" AND COALESCE(accounting_only,0)=0"});import{existsSync as KL}from"node:fs";import{createRequire as zL}from"node:module";function YL(){return gp===null&&(gp=zL(import.meta.url)("node:sqlite").DatabaseSync),gp}function eM(t){let e=ZL[t];if(e!==void 0)return e;let n=QL[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function bs(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=eM(t.errcode)),t}function tM(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function nM(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function hp(t){return t.length===1&&rM(t[0])?[t[0]]:t}function rM(t){if(!vp(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function vp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var gp,QL,ZL,yp,ws,_p,Fo=L(()=>{"use strict";gp=null;QL={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",25:"SQLITE_RANGE",26:"SQLITE_NOTADB"},ZL={275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE",261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB"};yp=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!KL(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(YL())(e,{readOnly:n.readonly===!0})}catch(r){bs(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new _p(this.handle.prepare(e))}catch(n){bs(n)}}exec(e){try{this.handle.exec(e)}catch(n){bs(n)}}pragma(e,n){let r=`PRAGMA ${e}`;if(e.includes("=")){this.exec(r);return}if(n?.simple===!0){let s=this.prepare(r).get();return s===void 0?void 0:Object.values(s)[0]}return this.prepare(r).all()}transaction(e){let n=(...r)=>this.runTransaction("BEGIN",e,r);return n.immediate=(...r)=>this.runTransaction("BEGIN IMMEDIATE",e,r),n}get inTransaction(){return this.handle.isTransaction}close(){try{this.handle.close()}catch(e){bs(e)}}runTransaction(e,n,r){if(!this.inTransaction){this.exec(e);try{let i=n(...r);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!tM(o))throw o}throw i}}let s=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=n(...r);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!nM(o))throw o}throw i}}};ws=yp,_p=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...hp(e));return this.normalizeRow(n)}catch(n){bs(n)}}all(...e){try{return this.handle.all(...hp(e)).map(n=>this.normalizeRow(n))}catch(n){bs(n)}}run(...e){try{let n=this.handle.run(...hp(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){bs(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&vp(e)?Object.values(e):vp(e)?{...e}:e}}});function Ql(t){return new ws(t,{readonly:!0,fileMustExist:!0})}var bp=L(()=>{"use strict";Fo()});import{createHash as sM}from"node:crypto";import{lstat as iM,readFile as oM,realpath as vb,stat as bb}from"node:fs/promises";import{isAbsolute as wb,relative as aM,resolve as lM,sep as cM}from"node:path";function J(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function re(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function $o(t){return re(t)}function Bt(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function _e(t){if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t.maxRows)||t.maxRows<=0)throw new Error("maxRows must be a positive safe integer");t.signal.throwIfAborted()}function Te(t,e){return t<e?-1:t>e?1:0}function _t(t,e,n){if(t===null||e===null)return null;let r=n==="written"?"write":"read",s=0;for(let i of t){if(i.bytes===null)return null;s+=i.bytes}for(let i of e)if(i.direction===r){if(i.bytes===null)return null;s+=i.bytes}return s}function vn(t,e,n){let r={},s=$o(t.cacheWrite5m),i=$o(t.cacheWrite1h),o=$o(t.reasoning),a=$o(t.webSearch),l=$o(t.webFetch);o!==null&&(e===null||o<=e)&&(r.reasoning_output_tokens=o);let c=(s??0)+(i??0),u=n===null||c<=n;return s!==null&&u&&(r.cache_write_5m_tokens=s),i!==null&&u&&(r.cache_write_1h_tokens=i),a!==null&&(r.web_search_requests=a),l!==null&&(r.web_fetch_requests=l),Object.keys(r).length>0?r:null}function kr(t){return typeof t=="string"&&dM.has(t.toLowerCase())}function $e(t,e){t.record({direction:"read",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"}),t.record({direction:"write",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"})}function ui(t){let e=J(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function Ye(t,e){if(!wb(t))return null;let n=await iM(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await vb(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await vb(s).catch(()=>lM(s)),o=aM(i,r);if(o===""||!o.startsWith(`..${cM}`)&&o!==".."&&!wb(o))return r}return null}async function It(t,e){_e(e);let n=await bb(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await oM(t,{signal:e.signal});e.signal.throwIfAborted();let s=await bb(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${jo}:sha256:${sM("sha256").update(r).digest("hex")}`,data:r}}function Zl(t,e){if(t.length>0&&t[t.length-1]!==10)return null;let n=t.toString("utf8"),r=n.length===0?[]:n.slice(0,-1).split(`
|
|
512
|
-
`),s=[];for(let i of r)if(e.signal.throwIfAborted(),!!i.trim())try{let o=
|
|
513
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function Q(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function zt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ae,Xe=L(()=>{"use strict";ae=fM()});import{readdir as gM}from"node:fs/promises";import{join as mi,resolve as hM}from"node:path";function tc(t){return hM(t||process.env.XDG_DATA_HOME||mi(ae,".local","share"))}function yM(t){return mi(tc(t),"muse","sessions")}function _M(t,e,n,r){let s=r?.input_tokens,i=r?.cache_read_tokens??r?.input_cache_read_tokens,o=r?.cache_write_tokens??r?.input_cache_write_tokens,a=typeof r?.promptTokens=="number"?r.promptTokens:typeof r?.prompt_tokens=="number"?r.prompt_tokens:void 0,l=typeof s=="number"&&typeof i=="number"&&i>s||typeof a=="number"&&typeof i=="number"&&i>a||typeof a=="number"&&typeof o=="number"&&o>a||typeof a=="number"&&typeof i=="number"&&typeof o=="number"&&i+o>a,c=l?null:typeof i=="number"?i:null,u=l?null:typeof o=="number"?o:null,d=null;return l||(typeof r?.input_uncached_tokens=="number"?d=r.input_uncached_tokens:typeof a=="number"&&typeof i=="number"&&typeof o=="number"&&a>=i+o&&(d=a-i-o)),{response_id:t,timestamp:e.toISOString(),model:typeof n=="string"&&n.length>0?n:null,tokens:{input_uncached:typeof d=="number"?d:null,input_cached:typeof c=="number"?c:null,input_cache_write:typeof u=="number"?u:null,output:typeof r?.output_tokens=="number"?r.output_tokens:null},files_read:null,files_written:null}}function Ab(t,e){let n,r,s,i,o,a=[],l=new Map,c=new Map,u=new Set,d,m,p=()=>{m="partial"},f=y=>{if(typeof y!="string"||y.length===0){p();return}let b=l.get(y);return b||(b={id:y,turn:{id:y,status:"unknown"},responseIds:[]},l.set(y,b)),b},h=y=>{if(y.retained_frame&&Array.isArray(y.children)){for(let S of y.children)try{if(typeof S?.record_json!="string")throw new Error("missing record_json");h(JSON.parse(S.record_json))}catch{p()}return}if(y.stream?.kind!=="session"||y.stream?.id!==t)return;if(y.schema_version!==1){p();return}if(y.payload_type?.startsWith("runtime.session")&&y.payload_schema_version!==1){p();return}let b=y.payload?.source_run_record_id;for(let S of[y.id,b])if(!(typeof S!="string"||S.length===0)&&u.has(S))return;for(let S of[y.id,b])typeof S=="string"&&S.length>0&&u.add(S);let _=typeof y.recorded_at=="number"&&Number.isFinite(y.recorded_at)?new Date(y.recorded_at/1e3):void 0;if(y.recorded_at!==void 0&&(!_||!Number.isFinite(_.getTime()))){p();return}_&&Number.isFinite(_.getTime())&&((!s||_<s)&&(s=_),(!i||_>i)&&(i=_));let v=y.payload;if(y.payload_type==="runtime.session.metadata"&&(typeof v?.record?.workspace_root=="string"&&(n=v.record.workspace_root),typeof v?.record?.model_id=="string"&&(r=v.record.model_id)),y.payload_type!=="runtime.session"||v?.kind!=="run")return;let E=v.event,x=f(v.run_id);if(!E||!_||!x){E||p();return}if(E.kind==="started"&&typeof E.prompt=="string")a.push({role:"user",content:E.prompt,timestamp:_}),x.turn.startedAt=_,x.turn.prompt=E.prompt,x.turn.status="in_progress",o="in_progress";else if(E.kind==="assistant_message_committed"&&typeof E.text=="string")a.push({role:"assistant",content:E.text,timestamp:_});else if(E.kind==="terminal")x.turn.completedAt=_,x.turn.status=E.terminal==="completed"?"complete":"aborted",o=x.turn.status;else if(E.kind==="model_completed"){typeof E.model=="string"&&E.model.length>0&&(r=E.model,x.turn.model=E.model);let S=typeof b=="string"&&b.length>0?b:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(!S)p();else{x.responseIds.push(S);let j={};if(E.usage&&typeof E.usage=="object")for(let F of["input_tokens","output_tokens","cached_tokens","reasoning_tokens","input_uncached_tokens","cache_read_tokens","input_cache_read_tokens","cache_write_tokens","input_cache_write_tokens","promptTokens","prompt_tokens"]){let Z=E.usage[F];typeof Z=="number"&&Number.isSafeInteger(Z)&&Z>=0&&(j[F]=Z)}Object.keys(j).length>0&&(x.turn.rawUsage=[...x.turn.rawUsage??[],{responseId:S,values:j}]),c.set(S,_M(S,_,E.model,j))}if(!E.usage)return;let R={},N=E.usage.input_tokens,O=E.usage.cache_read_tokens??E.usage.input_cache_read_tokens,A=E.usage.cache_write_tokens??E.usage.input_cache_write_tokens,w=typeof E.usage.promptTokens=="number"?E.usage.promptTokens:typeof E.usage.prompt_tokens=="number"?E.usage.prompt_tokens:void 0,T=typeof N=="number"&&typeof O=="number"&&O>N||typeof w=="number"&&typeof O=="number"&&O>w||typeof w=="number"&&typeof A=="number"&&A>w||typeof w=="number"&&typeof O=="number"&&typeof A=="number"&&O+A>w,k=T?void 0:typeof O=="number"?O:void 0,I=T?void 0:typeof A=="number"?A:void 0,C;T||(typeof E.usage.input_uncached_tokens=="number"?C=E.usage.input_uncached_tokens:typeof w=="number"&&typeof O=="number"&&typeof A=="number"&&w>=O+A&&(C=w-O-A)),C!==void 0&&C<0&&(C=void 0);let M=E.usage.output_tokens,D=E.usage.reasoning_tokens;typeof C=="number"&&Number.isSafeInteger(C)&&C>=0&&(R.inputTokens=C),typeof k=="number"&&Number.isSafeInteger(k)&&k>=0&&(R.cachedInputTokens=k),typeof I=="number"&&Number.isSafeInteger(I)&&I>=0&&(R.cacheWriteInputTokens=I),typeof M=="number"&&Number.isSafeInteger(M)&&M>=0&&(R.outputTokens=M),typeof D=="number"&&Number.isSafeInteger(D)&&D>=0&&(R.reasoningOutputTokens=D),d=R}};return{visit:h,finish:()=>{if(!n||!s||!i)return null;let y=a.filter(E=>E.role==="user").map(E=>E.content),b=[...l.values()].map(E=>({...E.turn,...E.responseIds.length>0?{responseIds:[...E.responseIds]}:{}})),_=[...c.values()],v=Rr(_,m!=="partial");return{provider:"muse",sessionId:t,filePath:e,cwd:n,createdAt:s,modifiedAt:i,model:r,messages:a,messageCount:a.length,firstUserMessage:y[0],lastUserMessage:y.at(-1),userPrompts:y,turnStatus:o,totalInputTokens:v.input_uncached??void 0,totalCachedInputTokens:v.input_cached??void 0,totalCacheWriteInputTokens:v.input_cache_write??void 0,totalOutputTokens:v.output??void 0,lastTokenUsage:d,turns:b,responses:_,...m?{captureStatus:m}:{}}},markPartial:p}}function vM(t,e,n){let r=Ab(e,n);for(let s of t)r.visit(s);return r.finish()}function bM(t,e,n,r){r.signal.throwIfAborted();let s=Math.max(0,r.maxBytes),i=t.length<=s?t:t.subarray(0,Math.max(0,t.subarray(0,s).lastIndexOf(10))),o=i.length!==t.length,a=[],l=o,c=0,u=m=>{if(!m||typeof m!="object"||Array.isArray(m)){l=!0;return}let p=m;if(p.retained_frame&&Array.isArray(p.children)){for(let f of p.children){if(c>=r.maxRows){l=!0;return}let h;try{if(typeof f?.record_json!="string")throw new Error("missing record_json");h=JSON.parse(f.record_json)}catch{l=!0;continue}u(h)}return}if(c>=r.maxRows){l=!0;return}a.push(p),c++};for(let m of i.toString("utf8").split(/\r?\n/u)){if(r.signal.throwIfAborted(),m.trim()==="")continue;let p;try{p=JSON.parse(m)}catch{l=!0;continue}u(p)}let d=vM(a,e,n);return d&&l&&(d.captureStatus="partial"),d}function Cb(t){return{provider:"muse",root:yM(t),revision:"muse-session-v2",sessionId:n=>n.replaceAll("\\","/").match(/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/session\.jsonl$/iu)?.[1]??null,decode:bM}}async function Ib(t,e){let n=Ab(t,e);for await(let r of Ce(e,n.markPartial))n.visit(r);return n.finish()}var xb,ec,Ep=L(()=>{"use strict";Uo();Xe();xb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ec=class{name="muse";dataHome;constructor(e={}){this.dataHome=tc(e.museDataHome)}get root(){return mi(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,n=0){let r;try{r=await gM(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of r)i.isFile()&&i.name==="session.jsonl"?s.push(mi(e,i.name)):i.isDirectory()&&n<4&&s.push(...await this.files(mi(e,i.name),n+1));return s}async resolveSessionPath(e){return xb.test(e)?(await this.files()).find(n=>n.endsWith(mi(e,"session.jsonl")))??null:null}async loadSession(e){let n=await this.resolveSessionPath(e);return n?Ib(e,n):null}async discoverSessions(){let e=[];for(let n of await this.files())try{let r=n.split(/[\\/]/).at(-2);if(!xb.test(r))continue;let s=await Ib(r,n);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});import{readFile as Nb,readdir as wM,rm as EM,stat as Ob}from"node:fs/promises";import{basename as TM,join as pi,resolve as SM}from"node:path";function sc(t){return SM(t||process.env.MINIPLAYER_HOME||pi(process.env.XDG_DATA_HOME||pi(ae,".local","share"),"miniplayer"))}function nc(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function Tp(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function Lb(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Mb(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Pb(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return null}}function Db(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},n={};for(let[l,c]of Object.entries(e))re(c)!==null&&(n[l]=c);let r=re(e.inputTokens),s=re(e.cachedInputTokens),i=re(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=re(e.outputTokens),a=null;return t.usageConvention==="input-includes-cache"&&r!==null&&s!==null&&s<=r&&(a=r-s),t.usageConvention==="input-excludes-cache"&&r!==null&&i!==null&&(a=r+i),t.usageConvention==="synthetic"&&r===0&&s===0&&(i===0||i===null)&&o===0&&(a=0),{tokens:{input_uncached:a,input_cached:s,input_cache_write:i,output:o},rawUsage:n,pricingFacts:re(e.reasoningTokens)===null?null:{reasoning_output_tokens:re(e.reasoningTokens)}}}function $b(t,e,n){if(!t||typeof t!="object")return null;let r=t;if(![1,2].includes(r.version)||r.id!==e||typeof r.cwd!="string")return null;let s=f=>{if(typeof f!="string")return;let h=new Date(f);return Number.isFinite(h.getTime())?h:void 0},i=s(r.createdAt),o=s(r.updatedAt);if(!i||!o)return null;let a=[],l=[],c=[],u=r.version===1,d="complete";if(r.version===1){if(!Array.isArray(r.messages))return null;for(let f of r.messages){if(!f||!["user","assistant"].includes(f.role)||typeof f.content!="string")return null;a.push({role:f.role,content:f.content,timestamp:s(f.timestamp)??o})}}else{if(!Array.isArray(r.turns))return null;let f=new Set,h=new Set;for(let g of r.turns){if(!g||typeof g.responseId!="string"||!g.responseId||typeof g.input?.text!="string")return null;if(f.has(g.responseId)){u=!0;continue}f.add(g.responseId);let y=s(g.startedAt),b=s(g.completedAt??g.endedAt);if(!y)return null;let _=typeof g.model=="string"?g.model:void 0;["complete","running","failed","aborted"].includes(g.status)||(u=!0);let v=g.status==="complete"?"complete":g.status==="running"?"in_progress":g.status==="failed"?"failed":g.status==="aborted"?"aborted":"unknown";d=v==="failed"||v==="unknown"?"aborted":v,(v!=="complete"||g.partial===!0)&&(u=!0);let E=Array.isArray(g.modelResponses),x=E?g.modelResponses:[],S=[];l.push({id:g.responseId,startedAt:y,completedAt:b,model:_,prompt:g.input.text,status:v,responseIds:S}),a.push({role:"user",timestamp:y,content:g.input.text});let R=Array.isArray(g.toolEvents)&&g.toolEvents.length>0;if(!E&&!R){let T=g.usage??{},k=Db({...g,usage:T});Object.keys(k.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:g.responseId,values:k.rawUsage}]),S.push(g.responseId),c.push({response_id:g.responseId,timestamp:(b??y).toISOString(),model:_??null,model_provider:typeof g.provider=="string"?g.provider:null,tokens:k.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(g.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"}],pricing_facts:k.pricingFacts}),v!=="complete"&&!g.usage&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:g.output.text,model:_});continue}let N=new Map,O=new Map,A=new Set,w=[];for(let T of x){if(!T||typeof T!="object"||typeof T.responseId!="string"||!T.responseId){u=!0;continue}if(S.includes(T.responseId)){u=!0;continue}let k=T,I=w.length;w.push({response:k,index:I,filesRead:[],filesWritten:[],io:[]}),S.push(T.responseId),h.has(T.responseId)&&(u=!0),h.add(T.responseId),k.toolCalls!==void 0&&!Array.isArray(k.toolCalls)&&(u=!0,w[I].io.push({direction:"read",kind:"unattributed",id:T.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:T.responseId,ref:null,bytes:null,basis:"unknown"}));for(let C of Array.isArray(k.toolCalls)?k.toolCalls:[]){let M=Lb(C),D=Tp(C);if(M)N.set(M,I),O.set(M,D);else{u=!0;let j=D==="list_directory"||D==="read_file"||D==="webget"||D==="shell"||D==="tool",F=D==="write_file"||D==="shell"||D==="tool";j&&w[I].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),F&&w[I].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}S.length===0&&x.length>0&&(u=!0);for(let T of Array.isArray(g.toolEvents)?g.toolEvents:[]){let k=T&&typeof T=="object"?T:{},I=Lb(k),C=I?N.get(I):void 0,M=Tp(k),D=Mb(k.result),j=k.status==="failed"||k.error!==void 0;if(k.type==="tool_call"?a.push({role:"tool_use",timestamp:s(k?.timestamp)??y,content:nc(k?.input??k?.args),toolName:M,toolInput:nc(k?.input??k?.args),toolInputData:Mb(k?.input??k?.args)??void 0,...I?{toolCallId:I}:{}}):a.push({role:"tool_result",timestamp:s(k?.timestamp)??b??y,content:nc(j?k?.error:k?.result),toolName:M,...I?{toolCallId:I}:{}}),C===void 0){u=!0;continue}let F=w[C];(k.type==="tool_result"||j||k.result!==void 0)&&A.add(I);let Z=D?.path,q=re(D?.bytesRead??D?.bytesWritten);k.type!=="tool_call"&&(M==="read_file"&&!j&&typeof Z=="string"&&q!==null?F.filesRead.push({path:Z,bytes:q}):M==="write_file"&&!j&&typeof Z=="string"&&q!==null?F.filesWritten.push({path:Z,bytes:q}):M==="webget"&&!j&&q!==null?F.io.push({direction:"read",kind:"web",id:I,ref:Pb(D?.finalUrl??D?.url),bytes:q,basis:"certified_counter"}):M==="shell"||j?(M!=="write_file"&&F.io.push({direction:"read",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}),(M==="shell"||M==="write_file")&&F.io.push({direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"})):M==="list_directory"||M==="read_file"||M==="webget"?F.io.push({direction:"read",kind:M==="webget"?"web":"unattributed",id:I,ref:M==="webget"?Pb(D?.finalUrl??D?.url):null,bytes:null,basis:"unknown"}):M==="write_file"?F.io.push({direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}):F.io.push({direction:"read",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}))}for(let[T,k]of O)if(!A.has(T)){let I=w[N.get(T)],C=k==="list_directory"||k==="read_file"||k==="webget"||k==="shell",M=k==="write_file"||k==="shell";C&&I.io.push({direction:"read",kind:"unattributed",id:T,ref:null,bytes:null,basis:"unknown"}),M&&I.io.push({direction:"write",kind:"unattributed",id:T,ref:null,bytes:null,basis:"unknown"}),u=!0}for(let T of w){let k=T.response,I=Db(k),C=s(k.completedAt??k.startedAt)??b??y;new Set((Array.isArray(k.toolCalls)?k.toolCalls:[]).map(F=>Tp(F))).has("shell")&&!T.io.some(F=>F.kind==="unattributed"&&F.direction==="read")&&T.io.push({direction:"read",kind:"unattributed",id:k.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:k.responseId,ref:null,bytes:null,basis:"unknown"}),T.index===0&&T.io.unshift({direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"});let D=T.io.some(F=>F.direction==="read"&&F.bytes===null),j=T.io.some(F=>F.direction==="write"&&F.bytes===null);if(c.push({response_id:k.responseId,timestamp:C.toISOString(),model:typeof k.model=="string"?k.model:null,model_provider:typeof k.provider=="string"?k.provider:typeof g.provider=="string"?g.provider:null,tokens:I.tokens,files_read:D?null:T.filesRead,files_written:j?null:T.filesWritten,read_bytes:D?null:T.filesRead.reduce((F,Z)=>F+(Z.bytes??0),0)+T.io.filter(F=>F.direction==="read").reduce((F,Z)=>F+(Z.bytes??0),0),write_bytes:j?null:T.filesWritten.reduce((F,Z)=>F+(Z.bytes??0),0)+T.io.filter(F=>F.direction==="write").reduce((F,Z)=>F+(Z.bytes??0),0),external_io:T.io,pricing_facts:I.pricingFacts}),Object.keys(I.rawUsage).length){let F=l.at(-1);F.rawUsage=[...F.rawUsage??[],{responseId:k.responseId,values:I.rawUsage}]}}l.at(-1).responseIds=S,S.length!==x.length&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:g.output.text,model:_})}}let m=a.filter(f=>f.role==="user").map(f=>f.content),p=Rr(c,!u);return{provider:"miniplayer",sessionId:e,cwd:r.cwd,filePath:n,createdAt:i,modifiedAt:o,model:typeof r.model=="string"?r.model:void 0,messages:a,messageCount:a.length,userPrompts:m,firstUserMessage:m[0],lastUserMessage:m.at(-1),turns:l,responses:c,turnStatus:d,...u?{captureStatus:"partial"}:{},totalInputTokens:p.input_uncached??void 0,totalCachedInputTokens:p.input_cached??void 0,totalCacheWriteInputTokens:p.input_cache_write??void 0,totalOutputTokens:p.output??void 0}}function ic(t){return{provider:"miniplayer",root:pi(sc(t),"sessions"),revision:"miniplayer-data-v3",sessionId(e){let n=TM(e,".json");return e.endsWith(".json")&&Fb.test(n)?n:null},decode(e,n,r,s){s.signal.throwIfAborted();try{let i=JSON.parse(e.toString("utf8"));return(Array.isArray(i.turns)?i.turns.reduce((a,l)=>a+1+(Array.isArray(l?.modelResponses)?l.modelResponses.length:0)+(Array.isArray(l?.toolEvents)?l.toolEvents.length:0),0):Array.isArray(i.messages)?i.messages.length:0)>s.maxRows?null:$b(i,n,r)}catch{return null}}}}var Fb,rc,oc=L(()=>{"use strict";Uo();Xe();Yn();Fb=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;rc=class{name="miniplayer";home;constructor(e={}){this.home=sc(e.miniplayerHome)}getWatchPaths(){return[{directory:pi(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await wM(pi(this.home,"sessions"))}catch{return[]}return(await Promise.all(e.filter(r=>r.endsWith(".json")).map(r=>this.loadSession(r.slice(0,-5))))).filter(r=>r!==null)}async resolveSessionPath(e){if(!Fb.test(e))return null;let n=pi(this.home,"sessions",`${e}.json`);try{return(await Ob(n)).isFile()?n:null}catch{return null}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;try{let r=$b(JSON.parse(await Nb(n,"utf8")),e,n);if(!r)return null;let s="complete";try{let i=JSON.parse(await Nb(`${n}.lock`,"utf8"));if(Number.isInteger(i.pid)&&i.pid>0)try{process.kill(i.pid,0),s="in_progress"}catch{s="aborted"}}catch{}return{...r,...s!=="complete"?{turnStatus:s}:{}}}catch{return null}}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;try{throw await Ob(`${n}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(r){if(r.code!=="ENOENT")throw r}return await EM(n),!0}}});import{createHash as kM}from"node:crypto";import{createRequire as RM}from"node:module";import{readdir as xM,realpath as IM}from"node:fs/promises";import{basename as jb,dirname as AM,join as Ub,resolve as Bb}from"node:path";function NM(){return CM("node:sqlite").DatabaseSync}function OM(){return process.env.HOME||process.env.USERPROFILE||""}function Es(t){let e=[],n=0,r=()=>{let s=0n,i=0n;for(;;){if(n>=t.length||i>63n)return null;let o=t[n++];if(s|=BigInt(o&127)<<i,i+=7n,!(o&128))break}return s<=BigInt(Number.MAX_SAFE_INTEGER)?Number(s):null};for(;n<t.length;){let s=r();if(s===null)return e;let i=s>>>3,o=s&7;if(i===0)return e;if(o===0){let a=r();if(a===null)return e;e.push({field:i,wire:o,varint:a})}else if(o===1){if(n+8>t.length)return e;n+=8,e.push({field:i,wire:o})}else if(o===5){if(n+4>t.length)return e;n+=4,e.push({field:i,wire:o})}else if(o===2){let a=r();if(a===null||n+a>t.length)return e;e.push({field:i,wire:o,bytes:t.subarray(n,n+a)}),n+=a}else return e}return e}function bn(t,e){return t.find(n=>n.field===e)}function LM(t){let e=new Map;for(let n of t){if(n.field!==20||n.bytes===void 0)continue;let r=Es(n.bytes),s=bn(r,1)?.bytes,i=bn(r,2)?.bytes;if(s===void 0||i===void 0)continue;let o=s.toString("utf8");e.has(o)||e.set(o,i.toString("utf8"))}return e}function MM(t){let e=bn(Es(t),5)?.bytes;if(e===void 0)return null;let n=bn(Es(e),1)?.bytes;if(n===void 0)return null;let r=Es(n),s=bn(r,1)?.varint;if(s===void 0)return null;let i=bn(r,2)?.varint??0,o=s*1e3+Math.floor(i/1e6),a=new Date(o);return Number.isFinite(a.getTime())?a.toISOString():null}function PM(t){let e=bn(t,4)?.bytes,n=e!==void 0?Es(e):[],r=s=>{let i=bn(n,s)?.varint;return i===void 0?null:re(i)};return{tokens:{input_uncached:r(2),input_cached:r(5),input_cache_write:r(4),output:r(3)},thinkingOutputTokens:r(9)}}function DM(t){let e=bn(Es(t),1)?.bytes;if(e===void 0)return null;let n=Es(e),r=LM(n),s=r.get("request_id");if(s===void 0||s.length===0)return null;let i=bn(n,19)?.bytes,o=i!==void 0&&i.length>0?i.toString("utf8"):null,a=r.get("last_step_index"),l=a===void 0?Number.NaN:Number(a),c=Number.isSafeInteger(l)&&l>=0?l:null,{tokens:u,thinkingOutputTokens:d}=PM(n);return{requestId:s,model:o,lastStepIndex:c,tokens:u,thinkingOutputTokens:d}}function Hb(t,e){_e(e);let n=t.prepare("SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) AS total FROM gen_metadata").get(),r=re(n?.total);if(r===null||r>e.maxBytes)return null;let s=t.prepare("SELECT idx, data FROM gen_metadata ORDER BY idx LIMIT ?").all(e.maxRows+1);if(s.length>e.maxRows)return null;let i=kM("sha256");i.update("rev:").update(ac).update(`
|
|
512
|
+
`)?t.slice(0,-1):t,HL=t=>t.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1<redacted>@").replace(/([?&](?:access_token|token|password|passwd|api_key)=)[^&\s"'<>]+/gi,"$1<redacted>")});var LV,Sr,Po,XL,GL,mp,JL,pp,he,dp,_n,Vl,Tr,Kl,Yl,li,ub,db,mb,ci,zl,VL,pb,fb,ht,zn=L(()=>{"use strict";LV=1,Sr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))Sr(e);Object.freeze(t)}return t},Po=Sr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed","service_unavailable","outcome_unknown"]),XL=Sr({status:"string",error:"string|null",code:"ErrorCode?"}),GL=Sr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),mp=Sr(["Provider1.Provider","Provider1.Model1","Provider2.Provider","Provider2.Model1","Provider3.Provider","Provider3.Model1"]),JL=Sr(["Provider1","Provider2","Provider3"]),pp=Sr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),he={name:"ctx",type:"context"},dp={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},_n={name:"teamfile",type:"string"},Vl={name:"alias",type:"string"},Tr={name:"prompt",type:"string"},Kl={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"alias",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"},{name:"sessiondir",type:"string"},{name:"sessionid",type:"string"}]},Yl=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],li={name:"options",type:"map",optional:!0,keys:Yl},ub={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},db={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},mb={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},ci={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},zl={name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},VL=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"}],pb={name:"options",type:"map",optional:!0,keys:VL},fb={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},ht=Sr([{name:"resolveProfilePath",implemented:!0,params:[he,dp],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[he,dp],statuses:["ok","error"],results:{error:"string|null",profile:"{path,raw,config}",values:"{Provider1..3,Model1..3,Directory,NonInteractive}",path:"string?",line:"number?",column:"number?"},effects:["file-read"],summary:"Read and validate the complete init profile without discovery or writes."},{name:"profileValues",implemented:!0,params:[{name:"config",type:"map"}],statuses:["ok","error"],results:{error:"string|null",Provider1:"string",Provider2:"string",Provider3:"string",Model1:"string",Model2:"string",Model3:"string"},effects:[],summary:"Validate and map slots to first-model environment values."},{name:"readPrompts",implemented:!0,params:[he,{name:"path",type:"string"},{name:"options",type:"map",optional:!0,keys:[{name:"single",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",prompts:"string[]"},effects:["file-read"],summary:"Read prompt records without exiting the caller.",scriptBinding:{name:"lm_read_prompts",params:[{name:"batchfile",type:"string"},{name:"single",type:"boolean",optional:!0}]}},{name:"listMembers",implemented:!0,params:[he,_n],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[_n]}},{name:"resolveMember",implemented:!0,params:[he,_n,Vl],statuses:["ok","not_found","error"],results:{error:"string|null",member:"Member",isLead:"boolean",teamfile:"string"},effects:["file-read","db"],summary:"Resolve a team member with an explicit missing outcome.",scriptBinding:{name:"lm_member",params:[_n,Vl]}},{name:"lintTeam",implemented:!0,params:[he,_n],statuses:["ok","error"],results:{error:"string|null",errors:"list",warnings:"list",counts:"map"},effects:["file-read","db"],summary:"Return structured lint findings.",scriptBinding:{name:"lm_lint",params:[_n]}},{name:"seedTeam",implemented:!0,params:[he,_n,ub],statuses:["ok","error"],results:{error:"string|null",seeded:"SeededMember[]"},effects:["provider","db","file-write"],summary:"Seed a team with explicit optional preambles.",scriptBinding:{name:"lm_seed",params:[_n,ub]}},{name:"promptAgent",implemented:!0,params:[he,Kl,Tr,li],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...fb,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[Kl,Tr,li]}},{name:"promptMember",implemented:!0,params:[he,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"prompt",type:"string",required:!0},{name:"messageType",type:"string"},...Yl]}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn a team member through native team admission.",scriptBinding:{name:"lm_prompt",params:[_n,Vl,Tr,{name:"options",type:"map",optional:!0,keys:[...Yl,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[he,{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"workspace",type:"string"},{name:"all",type:"boolean"}]}],statuses:["ok","error"],results:{error:"string|null",sessions:"Session[]"},effects:["file-read"],summary:"List native sessions in an explicit workspace.",scriptBinding:{name:"lm_session_list",params:[{name:"options",type:"map",optional:!0,keys:[{name:"provider",type:"string"},{name:"sessiondir",type:"string"},{name:"all",type:"boolean"}]}]}},{name:"deleteSession",implemented:!0,params:[he,ci,mb],statuses:["deleted","not_found","busy","error"],results:{error:"string|null"},effects:["provider","file-write"],summary:"Delete a session only with explicit force admission.",scriptBinding:{name:"lm_session_delete",params:[Kl,{...mb,optional:!0}]}},{name:"getSession",implemented:!0,params:[he,ci],statuses:["ok","not_found","error"],results:{error:"string|null",messages:"{role,content}[]"},effects:["provider","file-read"],summary:"Read native session messages.",scriptBinding:{name:"lm_session_get",params:[ci]}},{name:"reserveSession",implemented:!0,params:[he,ci],statuses:["ok","busy","error"],results:{error:"string|null",reservation:"SessionReservation"},effects:[],summary:"Reserve context-local handoff admission and return a capability."},{name:"releaseSession",implemented:!0,params:[he,ci,{name:"reservation",type:"SessionReservation",optional:!0}],statuses:["ok","error"],results:{error:"string|null"},effects:[],summary:"Release context-local handoff admission; an optional capability makes owned cleanup idempotent and replacement-safe."},{name:"openTeamBatch",returnsResource:!0,implemented:!0,params:[he,{name:"request",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0},{name:"label",type:"string",required:!0},{name:"promptCount",type:"number",required:!0},{name:"legacy",type:"boolean"},...Yl]}],statuses:["ok","busy","error"],results:{error:"string|null",batch:"opaque context-bound BatchRef"},effects:["provider","db"],summary:"Open a managed team batch; member-map composition remains language-owned."},{name:"batchTurn",implemented:!0,params:[he,{name:"batch",type:"BatchRef"},Tr,{name:"index",type:"number"},{name:"total",type:"number"}],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Turn an owned live batch reference."},{name:"closeBatch",implemented:!0,params:[he,{name:"batch",type:"BatchRef"},{name:"options",type:"map",keys:[{name:"status",type:"string",required:!0,values:["done","error","cancelled"]},{name:"error",type:"string"}]}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close an owned batch."},{name:"readRatelimits",implemented:!0,params:[he,db],statuses:["ok","error"],results:{error:"string|null",readings:"list"},effects:["file-read","network"],summary:"Read provider rate-limit data.",scriptBinding:{name:"lm_ratelimit_readings",params:[db]}},{name:"openTerminal",implemented:!0,params:[he,{name:"target",type:"map",keys:[{name:"teamfile",type:"string",required:!0},{name:"alias",type:"string",required:!0}]},{name:"streams",type:"map",keys:[{name:"stdin",type:"stream",required:!0},{name:"stdout",type:"stream",required:!0},{name:"stderr",type:"stream",required:!0}]}],statuses:["ok","error"],results:{error:"string|null",code:"number|null",signal:"string|null"},effects:["provider","db","tty"],summary:"Open a native terminal with caller-supplied streams.",scriptBinding:{name:"lm_terminal",params:[_n,Vl]}},{name:"sessionAdmission",implemented:!0,params:[he,ci],statuses:["ok","busy","error"],results:{error:"string|null",busyReason:"turn|handoff?"},effects:[],summary:"Query context-local session admission without exposing mutable sets."},{name:"promptReservedAgent",implemented:!0,params:[he,{name:"reservation",type:"SessionReservation"},Kl,Tr,li],statuses:["ok","busy","stalled","empty","error"],results:{...fb,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[he,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Synchronously release one batch on a close deadline without cancelling unrelated batches."},{name:"inspectBatch",implemented:!0,params:[he,{name:"batch",type:"BatchRef"}],statuses:["ok","error"],results:{error:"string|null",id:"string",closed:"boolean",member:"Member",rootId:"number|null"},effects:[],summary:"Read batch metadata without exposing native transports or lease capabilities."},{name:"openNativeSession",returnsResource:!0,implemented:!0,params:[he,{name:"member",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0},{name:"sessiondir",type:"string"},{name:"model",type:"string"},{name:"effort",type:"string"}]},li],statuses:["ok","busy","error"],results:{error:"string|null",session:"opaque context-bound NativeSessionRef"},effects:["provider","db","file-read"],summary:"Open a script-owned native conversation with existing receiver admission."},{name:"nativeSessionTurn",implemented:!0,params:[he,{name:"session",type:"NativeSessionRef"},Tr],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null"},effects:["provider","db"],summary:"Record one unframed conversational turn through the existing recorder."},{name:"closeNativeSession",implemented:!0,params:[he,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["provider","db"],summary:"Idempotently close a script-owned native conversation and release its lease."},{name:"finalizeNativeSessionSync",implemented:!0,params:[he,{name:"session",type:"NativeSessionRef"}],statuses:["ok","error"],results:{error:"string|null"},effects:["db"],summary:"Critical synchronous native conversation lease release."},{name:"nativeSessionRequest",implemented:!0,params:[he,zl,Tr,li],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Send a stateless native-id turn to a qualified conversation in the configured running lmbee service.",scriptBinding:{name:"lm_session_turn",params:[zl,Tr,li]}},{name:"nativeSessionClose",implemented:!0,params:[he,zl],statuses:["ok","busy","error"],results:{error:"string|null",code:"ErrorCode?",outcome:"not_sent|completed|unknown?",service_epoch:"string|null?",connection_epoch:"number|null?",connection_state:"new|reused|reinitialized|null?"},effects:["provider","db","network"],summary:"Close an idle service-hosted native conversation; an absent entry is already closed.",scriptBinding:{name:"lm_session_close",params:[zl]}},{name:"loadProperties",implemented:!0,params:[he,dp],statuses:["ok","error"],results:{error:"string|null",path:"string",properties:"map",flat:"map",line:"number?",column:"number?"},effects:["file-read"],summary:"Read the complete hierarchical init.toml properties document through the canonical reader."},{name:"listRunning",implemented:!0,params:[he,pb],statuses:["ok","error"],results:{error:"string|null",running:"RunningRow[]",dead:"DeadRow[]",idle:"IdleRow[]"},effects:["db"],summary:"DB-wide view of tracked invocation activity. Observation only; dispatch and branch on status busy, never gate on this.",scriptBinding:{name:"lm_running",params:[pb]}}])});var gb,hb=L(()=>{"use strict";gb=[{name:"lm_session_turn",category:"lmctl Automation",signature:"lm_session_turn(member, prompt, options = {})",description:"Sends one stateless turn to a service-hosted conversation addressed by provider and native sessionid. Qualified providers require the already-running lmbee endpoint in LMCTL_SERVICE_ENDPOINT. idleTimeoutMs controls idle retention (default 300000 ms; zero disables expiry). An accepted turn finishes and is recorded after the caller disconnects. World failures never throw. This is an effect and is skipped in dry-run with a map dummy; one-shot providers stay local.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid; optional sessiondir, model, effort"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode and idleTimeoutMs"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id, code?, outcome?, service_epoch?, connection_epoch?, connection_state? }"},example:'res = lm_session_turn({ provider: "kimi", sessionid: "native-1" }, "Continue");'},{name:"lm_session_close",category:"lmctl Automation",signature:"lm_session_close(member)",description:"Requests closure of the service-owned conversation addressed by provider and native sessionid. Idle conversations close, active conversations return busy, and an absent entry is already closed. World failures never throw; dry-run returns a map dummy.",parameters:[{name:"member",type:"map",description:"Required provider and native sessionid"}],returns:{type:"map",description:'{ status: "ok"|"busy"|"error", error: string|null, code?: string }'},example:'closed = lm_session_close({ provider: "kimi", sessionid: "native-1" });'},{name:"prompt_human",category:"lmctl Automation",signature:"prompt_human([question|session])",description:"Reads an operator answer or hands off a session. Accepts one optional question/session value; non-interactive mode refuses the operation. A handoff reservation is host-owned and released on EOF, provider failure, cancellation, context finalization or signal; the returned outcome is an ordinary map. Core prompt options apply only without this binding."},{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens the only returned production resource: an async-only opaque read-only id handle. The first receiving lexical binding owns it until scope exit; aliases borrow, and returning/storing/coercing the handle is refused at runtime. Teamfile batches keep existing admission. A member map with provider and sessionid locks an existing native session: one known owner uses its teamfile and alias lease, otherwise the native address is the lease key. Native handles reuse one persistent conversation when supported, or one provider process per turn, and record each turn. A member map without sessionid retains the fresh-agent batch path. Dry-run simulates these resource operations without provider or lease activity.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"ResourceHandle|null",description:"Opaque id-only handle, or null on admission refusal; no mutable map or transferable authority"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index?, total?)",description:"Native handles accept handle and prompt only for dependent conversational turns; teamfile and fresh-member batches still require index and total. Each native turn uses the existing transcript and usage recorder.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Same-run live owner/borrower handle or authorized id reference"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"Teamfile or fresh-member form only: 1-based prompt index"},{name:"total",type:"number",description:"Teamfile or fresh-member form only: total prompts"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'empty'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch resource. Native handles close their conversation and release the owned lease; scope exit, script error, exit, and signals also close them. Teamfile batches retain tracked-invocation and bundle cleanup.",parameters:[{name:"handle",type:"ResourceHandle|string|{id}",description:"Authorized handle/id; repeat close joins the same operation"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns an ordinary result map. The host owns its pending per-turn lease and critical release; no returned resource or script closer.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_agent_message",category:"lmctl Automation",signature:"lm_agent_message(member, prompt, options = {})",description:"Like lm_agent, and also returns the completed turn as lmctl stores and prices it: model, token buckets and the lmprice cost of that turn. Cost is null (with costUnavailableReason) when the provider does not record enough accounting.",parameters:[{name:"member",type:"map",description:"As for lm_agent"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) As for lm_agent"}],returns:{type:"map",description:"lm_agent's { status, reply, error, message_id, team_chat_log_id } plus message: null | { role, content, provider, sessionid, model, usage: { input, cachedInput, cacheWrite, output }, costUsd, costUnavailableReason, priceRoute, priceDataSource }"},example:'agent = { provider: "miniplayer", model: "deepseek/deepseek-flash" }; res = lm_agent_message(agent, "Say hi"); println(res.message.costUsd);'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, sessions: [{ provider, sessionid, sessiondir, modifiedAt }] }'},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_get",category:"lmctl Automation",signature:"lm_session_get(target)",description:"Reads native session messages. Returns messages in chronological order, or not_found if the session does not exist.",parameters:[{name:"target",type:"map",description:"Session target map with required provider and sessionid strings"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, messages?: [{ role: string, content: string }] }'},example:'session = lm_session_get({ provider: "codex", sessionid: "sess-123" }); if (session.status == "ok") { println(len(session.messages)); }'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_running",category:"lmctl Automation",signature:"lm_running(options = {})",description:'Returns active tracked-invocation snapshot. Options: since (e.g. "1h", "2d"). observation only; dispatch and branch on status busy, never gate on this.',parameters:[{name:"options",type:"map",description:'(optional) Query options: since (duration string like "1h", "2d")'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, running: map[], dead: map[], idle: map[] }'},example:'snapshot = lm_running(); if (snapshot.status == "ok") { println(len(snapshot.running)); }'},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, code?: string, seeded: [{ alias, provider, sessionid, sessiondir, model }] }'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. The host attempts checked lock/invocation release on completion, failure, cancellation or signal and reports unresolved failures, including a busy database; the returned outcome is an ordinary map. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, exit_code: number, signal: string|null, code?: string }'},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", error: null, readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, prompts: string[] }'},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map",description:'{ status: "ok"|"error", error: string|null, members: [{ alias, provider, model, sessionid, sessiondir }] }'},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map",description:'{ status: "ok"|"not_found"|"error", error: string|null, member?: { alias, provider, model, sessionid, sessiondir }, isLead?: bool, teamfile?: string }'},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}]});function V(t){try{if(t instanceof Error){let e=t.message;if(typeof e=="string")return e}return String(t)}catch{return"Unprintable error"}}function ge(t){return{...t,status:"ok",error:null}}function H(t,e,n){return{...n,status:"error",code:t,error:e}}var yt=L(()=>{"use strict"});function _b(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?Do:yb}var yb,Do,fp=L(()=>{"use strict";yb="root_teamfile <> '(direct)'",Do=yb+" AND COALESCE(accounting_only,0)=0"});import{existsSync as KL}from"node:fs";import{createRequire as zL}from"node:module";function YL(){return gp===null&&(gp=zL(import.meta.url)("node:sqlite").DatabaseSync),gp}function eM(t){let e=ZL[t];if(e!==void 0)return e;let n=QL[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function bs(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=eM(t.errcode)),t}function tM(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function nM(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function hp(t){return t.length===1&&rM(t[0])?[t[0]]:t}function rM(t){if(!vp(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function vp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var gp,QL,ZL,yp,ws,_p,Fo=L(()=>{"use strict";gp=null;QL={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",25:"SQLITE_RANGE",26:"SQLITE_NOTADB"},ZL={275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE",261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB"};yp=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!KL(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(YL())(e,{readOnly:n.readonly===!0})}catch(r){bs(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new _p(this.handle.prepare(e))}catch(n){bs(n)}}exec(e){try{this.handle.exec(e)}catch(n){bs(n)}}pragma(e,n){let r=`PRAGMA ${e}`;if(e.includes("=")){this.exec(r);return}if(n?.simple===!0){let s=this.prepare(r).get();return s===void 0?void 0:Object.values(s)[0]}return this.prepare(r).all()}transaction(e){let n=(...r)=>this.runTransaction("BEGIN",e,r);return n.immediate=(...r)=>this.runTransaction("BEGIN IMMEDIATE",e,r),n}get inTransaction(){return this.handle.isTransaction}close(){try{this.handle.close()}catch(e){bs(e)}}runTransaction(e,n,r){if(!this.inTransaction){this.exec(e);try{let i=n(...r);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!tM(o))throw o}throw i}}let s=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=n(...r);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!nM(o))throw o}throw i}}};ws=yp,_p=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...hp(e));return this.normalizeRow(n)}catch(n){bs(n)}}all(...e){try{return this.handle.all(...hp(e)).map(n=>this.normalizeRow(n))}catch(n){bs(n)}}run(...e){try{let n=this.handle.run(...hp(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){bs(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&vp(e)?Object.values(e):vp(e)?{...e}:e}}});function Ql(t){return new ws(t,{readonly:!0,fileMustExist:!0})}var bp=L(()=>{"use strict";Fo()});import{createHash as sM}from"node:crypto";import{lstat as iM,readFile as oM,realpath as vb,stat as bb}from"node:fs/promises";import{isAbsolute as wb,relative as aM,resolve as lM,sep as cM}from"node:path";function K(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function re(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function $o(t){return re(t)}function Bt(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function _e(t){if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t.maxRows)||t.maxRows<=0)throw new Error("maxRows must be a positive safe integer");t.signal.throwIfAborted()}function Te(t,e){return t<e?-1:t>e?1:0}function _t(t,e,n){if(t===null||e===null)return null;let r=n==="written"?"write":"read",s=0;for(let i of t){if(i.bytes===null)return null;s+=i.bytes}for(let i of e)if(i.direction===r){if(i.bytes===null)return null;s+=i.bytes}return s}function vn(t,e,n){let r={},s=$o(t.cacheWrite5m),i=$o(t.cacheWrite1h),o=$o(t.reasoning),a=$o(t.webSearch),l=$o(t.webFetch);o!==null&&(e===null||o<=e)&&(r.reasoning_output_tokens=o);let c=(s??0)+(i??0),u=n===null||c<=n;return s!==null&&u&&(r.cache_write_5m_tokens=s),i!==null&&u&&(r.cache_write_1h_tokens=i),a!==null&&(r.web_search_requests=a),l!==null&&(r.web_fetch_requests=l),Object.keys(r).length>0?r:null}function kr(t){return typeof t=="string"&&dM.has(t.toLowerCase())}function $e(t,e){t.record({direction:"read",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"}),t.record({direction:"write",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"})}function ui(t){let e=K(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function Ye(t,e){if(!wb(t))return null;let n=await iM(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await vb(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await vb(s).catch(()=>lM(s)),o=aM(i,r);if(o===""||!o.startsWith(`..${cM}`)&&o!==".."&&!wb(o))return r}return null}async function It(t,e){_e(e);let n=await bb(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await oM(t,{signal:e.signal});e.signal.throwIfAborted();let s=await bb(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${jo}:sha256:${sM("sha256").update(r).digest("hex")}`,data:r}}function Zl(t,e){if(t.length>0&&t[t.length-1]!==10)return null;let n=t.toString("utf8"),r=n.length===0?[]:n.slice(0,-1).split(`
|
|
513
|
+
`),s=[];for(let i of r)if(e.signal.throwIfAborted(),!!i.trim())try{let o=K(JSON.parse(i));if(!o)return null;s.push(o)}catch{return null}return s}var jo,xt,jt,uM,Ut,dM,Yn=L(()=>{"use strict";jo="bx3",xt={input_uncached:null,input_cached:null,input_cache_write:null,output:null};jt=class{map=new Map;record(e,n,r,s){if(typeof r!="string"||r.length===0||r.includes("\0"))return;let i=`${e}\0${n}\0${r}`;this.map.has(i)||this.map.set(i,{direction:n,path:r,bytes:s})}files(e){let n=[];for(let r of this.map.values())r.direction===e&&n.push({path:r.path,bytes:r.bytes});return n}},uM=0,Ut=class{map=new Map;record(e){let n;e.id!==null?n=`id\0${e.id}\0${e.direction}\0${e.kind}`:e.bytes===null?n=`mark\0${e.direction}\0${e.kind}\0${e.basis}\0${e.ref??""}`:n=`seq\0${uM++}`,this.map.has(n)||this.map.set(n,e)}entries(){return[...this.map.values()]}};dM=new Set(["schedulewakeup","taskcreate","taskupdate","taskoutput","taskstop","todowrite","todoread","croncreate","crondelete","cronlist","monitor","listagents","toolsearch","askuserquestion","exitplanmode","agent","skill","job"])});import{readdir as mM}from"node:fs/promises";import{join as Eb,sep as Tb}from"node:path";var di,wp=L(()=>{"use strict";Yn();di=class{constructor(e){this.format=e}async discover(e,n,r){_e(e);let s=[],i=0,o=!1,a=async(l,c)=>{if(e.signal.throwIfAborted(),c>8||i>e.maxRows){o=!0;return}let u=await mM(l,{withFileTypes:!0}).catch(m=>(m.code!=="ENOENT"&&(o=!0),[])),d=m=>Eb(l,m.name)+(m.isDirectory()?Tb:"");for(let m of u.sort((p,f)=>Te(d(p),d(f)))){e.signal.throwIfAborted();let p=Eb(l,m.name),f=m.isDirectory()&&r?.startsWith(p+Tb);if(!(r&&!f&&Te(d(m),r)<=0)){if(!f&&++i>e.maxRows){o=!0;break}if(m.isDirectory())await a(p,c+1);else if(m.isFile()){let h=this.format.sessionId(p);h&&s.push({provider:this.format.provider,sessionid:h,source_id:p})}if(s.length>=n){o=!0;break}}}};return await a(this.format.root,0),s.sort((l,c)=>Te(l.source_id,c.source_id)),{sources:s.slice(0,n),truncated:o||s.length>n}}async bytes(e,n){if(_e(n),e.provider!==this.format.provider||this.format.sessionId(e.source_id)!==e.sessionid)return null;let r=await Ye(e.source_id,[this.format.root]);if(!r)return null;let s=await It(r,n).catch(()=>(n.signal.throwIfAborted(),null));return s&&{...s,revision:`${this.format.revision}:${s.revision}`}}async inspect(e,n){let r=await this.bytes(e,n);return r?{status:"ready",revision:r.revision}:{status:"partial"}}async read(e,n,r){let s=await this.bytes(e,r);if(!s||s.revision!==n)return{status:"partial"};let i=this.format.decode(s.data,e.sessionid,e.source_id,r);return!i||!i.responses?{status:"partial"}:{status:"complete",source:e,revision:n,checkpoint:null,responses:i.responses,...i.captureStatus?{capture_status:i.captureStatus}:{}}}}});function Rr(t,e=!0){let n={input_uncached:null,input_cached:null,input_cache_write:null,output:null};if(!e||!t.length||new Set(t.map(r=>r.response_id)).size!==t.length)return n;for(let r of Object.keys(n)){let s=t.map(o=>o.tokens[r]);if(s.some(o=>o===null||!Number.isSafeInteger(o)||o<0))continue;let i=s.reduce((o,a)=>o+a,0);Number.isSafeInteger(i)&&(n[r]=i)}return n}var Uo=L(()=>{"use strict"});import{createReadStream as Sb}from"node:fs";import{createInterface as kb}from"node:readline";import{stat as pM}from"node:fs/promises";import{homedir as fM}from"node:os";function Rb(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*Ce(t,e){let n=Sb(t,{encoding:"utf-8"}),r=kb({input:n,crlfDelay:1/0});try{for await(let s of r){let i=s.trim();if(!i)continue;let o=Rb(i);o!==void 0?yield o:e?.()}}finally{n.destroy()}}async function Ht(t,e){let n=[],r=Sb(t,{encoding:"utf-8"}),s=kb({input:r,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=Rb(o);if(a!==void 0&&n.push(a),n.length>=e)break}}finally{s.close(),r.destroy()}return n}async function je(t){let e=await pM(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function ke(t){return t.replace(/\\n/g,`
|
|
514
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function Q(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function zt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ae,Xe=L(()=>{"use strict";ae=fM()});import{readdir as gM}from"node:fs/promises";import{join as mi,resolve as hM}from"node:path";function tc(t){return hM(t||process.env.XDG_DATA_HOME||mi(ae,".local","share"))}function yM(t){return mi(tc(t),"muse","sessions")}function _M(t,e,n,r){let s=r?.input_tokens,i=r?.cache_read_tokens??r?.input_cache_read_tokens,o=r?.cache_write_tokens??r?.input_cache_write_tokens,a=typeof r?.promptTokens=="number"?r.promptTokens:typeof r?.prompt_tokens=="number"?r.prompt_tokens:void 0,l=typeof s=="number"&&typeof i=="number"&&i>s||typeof a=="number"&&typeof i=="number"&&i>a||typeof a=="number"&&typeof o=="number"&&o>a||typeof a=="number"&&typeof i=="number"&&typeof o=="number"&&i+o>a,c=l?null:typeof i=="number"?i:null,u=l?null:typeof o=="number"?o:null,d=null;return l||(typeof r?.input_uncached_tokens=="number"?d=r.input_uncached_tokens:typeof a=="number"&&typeof i=="number"&&typeof o=="number"&&a>=i+o&&(d=a-i-o)),{response_id:t,timestamp:e.toISOString(),model:typeof n=="string"&&n.length>0?n:null,tokens:{input_uncached:typeof d=="number"?d:null,input_cached:typeof c=="number"?c:null,input_cache_write:typeof u=="number"?u:null,output:typeof r?.output_tokens=="number"?r.output_tokens:null},files_read:null,files_written:null}}function Ab(t,e){let n,r,s,i,o,a=[],l=new Map,c=new Map,u=new Set,d,m,p=()=>{m="partial"},f=y=>{if(typeof y!="string"||y.length===0){p();return}let b=l.get(y);return b||(b={id:y,turn:{id:y,status:"unknown"},responseIds:[]},l.set(y,b)),b},h=y=>{if(y.retained_frame&&Array.isArray(y.children)){for(let S of y.children)try{if(typeof S?.record_json!="string")throw new Error("missing record_json");h(JSON.parse(S.record_json))}catch{p()}return}if(y.stream?.kind!=="session"||y.stream?.id!==t)return;if(y.schema_version!==1){p();return}if(y.payload_type?.startsWith("runtime.session")&&y.payload_schema_version!==1){p();return}let b=y.payload?.source_run_record_id;for(let S of[y.id,b])if(!(typeof S!="string"||S.length===0)&&u.has(S))return;for(let S of[y.id,b])typeof S=="string"&&S.length>0&&u.add(S);let _=typeof y.recorded_at=="number"&&Number.isFinite(y.recorded_at)?new Date(y.recorded_at/1e3):void 0;if(y.recorded_at!==void 0&&(!_||!Number.isFinite(_.getTime()))){p();return}_&&Number.isFinite(_.getTime())&&((!s||_<s)&&(s=_),(!i||_>i)&&(i=_));let v=y.payload;if(y.payload_type==="runtime.session.metadata"&&(typeof v?.record?.workspace_root=="string"&&(n=v.record.workspace_root),typeof v?.record?.model_id=="string"&&(r=v.record.model_id)),y.payload_type!=="runtime.session"||v?.kind!=="run")return;let E=v.event,x=f(v.run_id);if(!E||!_||!x){E||p();return}if(E.kind==="started"&&typeof E.prompt=="string")a.push({role:"user",content:E.prompt,timestamp:_}),x.turn.startedAt=_,x.turn.prompt=E.prompt,x.turn.status="in_progress",o="in_progress";else if(E.kind==="assistant_message_committed"&&typeof E.text=="string")a.push({role:"assistant",content:E.text,timestamp:_});else if(E.kind==="terminal")x.turn.completedAt=_,x.turn.status=E.terminal==="completed"?"complete":"aborted",o=x.turn.status;else if(E.kind==="model_completed"){typeof E.model=="string"&&E.model.length>0&&(r=E.model,x.turn.model=E.model);let S=typeof b=="string"&&b.length>0?b:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(!S)p();else{x.responseIds.push(S);let j={};if(E.usage&&typeof E.usage=="object")for(let $ of["input_tokens","output_tokens","cached_tokens","reasoning_tokens","input_uncached_tokens","cache_read_tokens","input_cache_read_tokens","cache_write_tokens","input_cache_write_tokens","promptTokens","prompt_tokens"]){let Z=E.usage[$];typeof Z=="number"&&Number.isSafeInteger(Z)&&Z>=0&&(j[$]=Z)}Object.keys(j).length>0&&(x.turn.rawUsage=[...x.turn.rawUsage??[],{responseId:S,values:j}]),c.set(S,_M(S,_,E.model,j))}if(!E.usage)return;let R={},N=E.usage.input_tokens,O=E.usage.cache_read_tokens??E.usage.input_cache_read_tokens,A=E.usage.cache_write_tokens??E.usage.input_cache_write_tokens,w=typeof E.usage.promptTokens=="number"?E.usage.promptTokens:typeof E.usage.prompt_tokens=="number"?E.usage.prompt_tokens:void 0,T=typeof N=="number"&&typeof O=="number"&&O>N||typeof w=="number"&&typeof O=="number"&&O>w||typeof w=="number"&&typeof A=="number"&&A>w||typeof w=="number"&&typeof O=="number"&&typeof A=="number"&&O+A>w,k=T?void 0:typeof O=="number"?O:void 0,I=T?void 0:typeof A=="number"?A:void 0,C;T||(typeof E.usage.input_uncached_tokens=="number"?C=E.usage.input_uncached_tokens:typeof w=="number"&&typeof O=="number"&&typeof A=="number"&&w>=O+A&&(C=w-O-A)),C!==void 0&&C<0&&(C=void 0);let M=E.usage.output_tokens,D=E.usage.reasoning_tokens;typeof C=="number"&&Number.isSafeInteger(C)&&C>=0&&(R.inputTokens=C),typeof k=="number"&&Number.isSafeInteger(k)&&k>=0&&(R.cachedInputTokens=k),typeof I=="number"&&Number.isSafeInteger(I)&&I>=0&&(R.cacheWriteInputTokens=I),typeof M=="number"&&Number.isSafeInteger(M)&&M>=0&&(R.outputTokens=M),typeof D=="number"&&Number.isSafeInteger(D)&&D>=0&&(R.reasoningOutputTokens=D),d=R}};return{visit:h,finish:()=>{if(!n||!s||!i)return null;let y=a.filter(E=>E.role==="user").map(E=>E.content),b=[...l.values()].map(E=>({...E.turn,...E.responseIds.length>0?{responseIds:[...E.responseIds]}:{}})),_=[...c.values()],v=Rr(_,m!=="partial");return{provider:"muse",sessionId:t,filePath:e,cwd:n,createdAt:s,modifiedAt:i,model:r,messages:a,messageCount:a.length,firstUserMessage:y[0],lastUserMessage:y.at(-1),userPrompts:y,turnStatus:o,totalInputTokens:v.input_uncached??void 0,totalCachedInputTokens:v.input_cached??void 0,totalCacheWriteInputTokens:v.input_cache_write??void 0,totalOutputTokens:v.output??void 0,lastTokenUsage:d,turns:b,responses:_,...m?{captureStatus:m}:{}}},markPartial:p}}function vM(t,e,n){let r=Ab(e,n);for(let s of t)r.visit(s);return r.finish()}function bM(t,e,n,r){r.signal.throwIfAborted();let s=Math.max(0,r.maxBytes),i=t.length<=s?t:t.subarray(0,Math.max(0,t.subarray(0,s).lastIndexOf(10))),o=i.length!==t.length,a=[],l=o,c=0,u=m=>{if(!m||typeof m!="object"||Array.isArray(m)){l=!0;return}let p=m;if(p.retained_frame&&Array.isArray(p.children)){for(let f of p.children){if(c>=r.maxRows){l=!0;return}let h;try{if(typeof f?.record_json!="string")throw new Error("missing record_json");h=JSON.parse(f.record_json)}catch{l=!0;continue}u(h)}return}if(c>=r.maxRows){l=!0;return}a.push(p),c++};for(let m of i.toString("utf8").split(/\r?\n/u)){if(r.signal.throwIfAborted(),m.trim()==="")continue;let p;try{p=JSON.parse(m)}catch{l=!0;continue}u(p)}let d=vM(a,e,n);return d&&l&&(d.captureStatus="partial"),d}function Cb(t){return{provider:"muse",root:yM(t),revision:"muse-session-v2",sessionId:n=>n.replaceAll("\\","/").match(/\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/session\.jsonl$/iu)?.[1]??null,decode:bM}}async function Ib(t,e){let n=Ab(t,e);for await(let r of Ce(e,n.markPartial))n.visit(r);return n.finish()}var xb,ec,Ep=L(()=>{"use strict";Uo();Xe();xb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ec=class{name="muse";dataHome;constructor(e={}){this.dataHome=tc(e.museDataHome)}get root(){return mi(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,n=0){let r;try{r=await gM(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of r)i.isFile()&&i.name==="session.jsonl"?s.push(mi(e,i.name)):i.isDirectory()&&n<4&&s.push(...await this.files(mi(e,i.name),n+1));return s}async resolveSessionPath(e){return xb.test(e)?(await this.files()).find(n=>n.endsWith(mi(e,"session.jsonl")))??null:null}async loadSession(e){let n=await this.resolveSessionPath(e);return n?Ib(e,n):null}async discoverSessions(){let e=[];for(let n of await this.files())try{let r=n.split(/[\\/]/).at(-2);if(!xb.test(r))continue;let s=await Ib(r,n);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});import{readFile as Nb,readdir as wM,rm as EM,stat as Ob}from"node:fs/promises";import{basename as TM,join as pi,resolve as SM}from"node:path";function sc(t){return SM(t||process.env.MINIPLAYER_HOME||pi(process.env.XDG_DATA_HOME||pi(ae,".local","share"),"miniplayer"))}function nc(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function Tp(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function Lb(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Mb(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Pb(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return null}}function Db(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},n={};for(let[l,c]of Object.entries(e))re(c)!==null&&(n[l]=c);let r=re(e.inputTokens),s=re(e.cachedInputTokens),i=re(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=re(e.outputTokens),a=null;return t.usageConvention==="input-includes-cache"&&r!==null&&s!==null&&s<=r&&(a=r-s),t.usageConvention==="input-excludes-cache"&&r!==null&&i!==null&&(a=r+i),t.usageConvention==="synthetic"&&r===0&&s===0&&(i===0||i===null)&&o===0&&(a=0),{tokens:{input_uncached:a,input_cached:s,input_cache_write:i,output:o},rawUsage:n,pricingFacts:re(e.reasoningTokens)===null?null:{reasoning_output_tokens:re(e.reasoningTokens)}}}function $b(t,e,n){if(!t||typeof t!="object")return null;let r=t;if(![1,2].includes(r.version)||r.id!==e||typeof r.cwd!="string")return null;let s=f=>{if(typeof f!="string")return;let h=new Date(f);return Number.isFinite(h.getTime())?h:void 0},i=s(r.createdAt),o=s(r.updatedAt);if(!i||!o)return null;let a=[],l=[],c=[],u=r.version===1,d="complete";if(r.version===1){if(!Array.isArray(r.messages))return null;for(let f of r.messages){if(!f||!["user","assistant"].includes(f.role)||typeof f.content!="string")return null;a.push({role:f.role,content:f.content,timestamp:s(f.timestamp)??o})}}else{if(!Array.isArray(r.turns))return null;let f=new Set,h=new Set;for(let g of r.turns){if(!g||typeof g.responseId!="string"||!g.responseId||typeof g.input?.text!="string")return null;if(f.has(g.responseId)){u=!0;continue}f.add(g.responseId);let y=s(g.startedAt),b=s(g.completedAt??g.endedAt);if(!y)return null;let _=typeof g.model=="string"?g.model:void 0;["complete","running","failed","aborted"].includes(g.status)||(u=!0);let v=g.status==="complete"?"complete":g.status==="running"?"in_progress":g.status==="failed"?"failed":g.status==="aborted"?"aborted":"unknown";d=v==="failed"||v==="unknown"?"aborted":v,(v!=="complete"||g.partial===!0)&&(u=!0);let E=Array.isArray(g.modelResponses),x=E?g.modelResponses:[],S=[];l.push({id:g.responseId,startedAt:y,completedAt:b,model:_,prompt:g.input.text,status:v,responseIds:S}),a.push({role:"user",timestamp:y,content:g.input.text});let R=Array.isArray(g.toolEvents)&&g.toolEvents.length>0;if(!E&&!R){let T=g.usage??{},k=Db({...g,usage:T});Object.keys(k.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:g.responseId,values:k.rawUsage}]),S.push(g.responseId),c.push({response_id:g.responseId,timestamp:(b??y).toISOString(),model:_??null,model_provider:typeof g.provider=="string"?g.provider:null,tokens:k.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(g.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"}],pricing_facts:k.pricingFacts}),v!=="complete"&&!g.usage&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:g.output.text,model:_});continue}let N=new Map,O=new Map,A=new Set,w=[];for(let T of x){if(!T||typeof T!="object"||typeof T.responseId!="string"||!T.responseId){u=!0;continue}if(S.includes(T.responseId)){u=!0;continue}let k=T,I=w.length;w.push({response:k,index:I,filesRead:[],filesWritten:[],io:[]}),S.push(T.responseId),h.has(T.responseId)&&(u=!0),h.add(T.responseId),k.toolCalls!==void 0&&!Array.isArray(k.toolCalls)&&(u=!0,w[I].io.push({direction:"read",kind:"unattributed",id:T.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:T.responseId,ref:null,bytes:null,basis:"unknown"}));for(let C of Array.isArray(k.toolCalls)?k.toolCalls:[]){let M=Lb(C),D=Tp(C);if(M)N.set(M,I),O.set(M,D);else{u=!0;let j=D==="list_directory"||D==="read_file"||D==="webget"||D==="shell"||D==="tool",$=D==="write_file"||D==="shell"||D==="tool";j&&w[I].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),$&&w[I].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}S.length===0&&x.length>0&&(u=!0);for(let T of Array.isArray(g.toolEvents)?g.toolEvents:[]){let k=T&&typeof T=="object"?T:{},I=Lb(k),C=I?N.get(I):void 0,M=Tp(k),D=Mb(k.result),j=k.status==="failed"||k.error!==void 0;if(k.type==="tool_call"?a.push({role:"tool_use",timestamp:s(k?.timestamp)??y,content:nc(k?.input??k?.args),toolName:M,toolInput:nc(k?.input??k?.args),toolInputData:Mb(k?.input??k?.args)??void 0,...I?{toolCallId:I}:{}}):a.push({role:"tool_result",timestamp:s(k?.timestamp)??b??y,content:nc(j?k?.error:k?.result),toolName:M,...I?{toolCallId:I}:{}}),C===void 0){u=!0;continue}let $=w[C];(k.type==="tool_result"||j||k.result!==void 0)&&A.add(I);let Z=D?.path,q=re(D?.bytesRead??D?.bytesWritten);k.type!=="tool_call"&&(M==="read_file"&&!j&&typeof Z=="string"&&q!==null?$.filesRead.push({path:Z,bytes:q}):M==="write_file"&&!j&&typeof Z=="string"&&q!==null?$.filesWritten.push({path:Z,bytes:q}):M==="webget"&&!j&&q!==null?$.io.push({direction:"read",kind:"web",id:I,ref:Pb(D?.finalUrl??D?.url),bytes:q,basis:"certified_counter"}):M==="shell"||j?(M!=="write_file"&&$.io.push({direction:"read",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}),(M==="shell"||M==="write_file")&&$.io.push({direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"})):M==="list_directory"||M==="read_file"||M==="webget"?$.io.push({direction:"read",kind:M==="webget"?"web":"unattributed",id:I,ref:M==="webget"?Pb(D?.finalUrl??D?.url):null,bytes:null,basis:"unknown"}):M==="write_file"?$.io.push({direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}):$.io.push({direction:"read",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:I,ref:null,bytes:null,basis:"unknown"}))}for(let[T,k]of O)if(!A.has(T)){let I=w[N.get(T)],C=k==="list_directory"||k==="read_file"||k==="webget"||k==="shell",M=k==="write_file"||k==="shell";C&&I.io.push({direction:"read",kind:"unattributed",id:T,ref:null,bytes:null,basis:"unknown"}),M&&I.io.push({direction:"write",kind:"unattributed",id:T,ref:null,bytes:null,basis:"unknown"}),u=!0}for(let T of w){let k=T.response,I=Db(k),C=s(k.completedAt??k.startedAt)??b??y;new Set((Array.isArray(k.toolCalls)?k.toolCalls:[]).map($=>Tp($))).has("shell")&&!T.io.some($=>$.kind==="unattributed"&&$.direction==="read")&&T.io.push({direction:"read",kind:"unattributed",id:k.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:k.responseId,ref:null,bytes:null,basis:"unknown"}),T.index===0&&T.io.unshift({direction:"read",kind:"prompt",id:g.responseId,ref:null,bytes:Buffer.byteLength(g.input.text,"utf8"),basis:"input_text"});let D=T.io.some($=>$.direction==="read"&&$.bytes===null),j=T.io.some($=>$.direction==="write"&&$.bytes===null);if(c.push({response_id:k.responseId,timestamp:C.toISOString(),model:typeof k.model=="string"?k.model:null,model_provider:typeof k.provider=="string"?k.provider:typeof g.provider=="string"?g.provider:null,tokens:I.tokens,files_read:D?null:T.filesRead,files_written:j?null:T.filesWritten,read_bytes:D?null:T.filesRead.reduce(($,Z)=>$+(Z.bytes??0),0)+T.io.filter($=>$.direction==="read").reduce(($,Z)=>$+(Z.bytes??0),0),write_bytes:j?null:T.filesWritten.reduce(($,Z)=>$+(Z.bytes??0),0)+T.io.filter($=>$.direction==="write").reduce(($,Z)=>$+(Z.bytes??0),0),external_io:T.io,pricing_facts:I.pricingFacts}),Object.keys(I.rawUsage).length){let $=l.at(-1);$.rawUsage=[...$.rawUsage??[],{responseId:k.responseId,values:I.rawUsage}]}}l.at(-1).responseIds=S,S.length!==x.length&&(u=!0),typeof g.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:g.output.text,model:_})}}let m=a.filter(f=>f.role==="user").map(f=>f.content),p=Rr(c,!u);return{provider:"miniplayer",sessionId:e,cwd:r.cwd,filePath:n,createdAt:i,modifiedAt:o,model:typeof r.model=="string"?r.model:void 0,messages:a,messageCount:a.length,userPrompts:m,firstUserMessage:m[0],lastUserMessage:m.at(-1),turns:l,responses:c,turnStatus:d,...u?{captureStatus:"partial"}:{},totalInputTokens:p.input_uncached??void 0,totalCachedInputTokens:p.input_cached??void 0,totalCacheWriteInputTokens:p.input_cache_write??void 0,totalOutputTokens:p.output??void 0}}function ic(t){return{provider:"miniplayer",root:pi(sc(t),"sessions"),revision:"miniplayer-data-v3",sessionId(e){let n=TM(e,".json");return e.endsWith(".json")&&Fb.test(n)?n:null},decode(e,n,r,s){s.signal.throwIfAborted();try{let i=JSON.parse(e.toString("utf8"));return(Array.isArray(i.turns)?i.turns.reduce((a,l)=>a+1+(Array.isArray(l?.modelResponses)?l.modelResponses.length:0)+(Array.isArray(l?.toolEvents)?l.toolEvents.length:0),0):Array.isArray(i.messages)?i.messages.length:0)>s.maxRows?null:$b(i,n,r)}catch{return null}}}}var Fb,rc,oc=L(()=>{"use strict";Uo();Xe();Yn();Fb=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;rc=class{name="miniplayer";home;constructor(e={}){this.home=sc(e.miniplayerHome)}getWatchPaths(){return[{directory:pi(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await wM(pi(this.home,"sessions"))}catch{return[]}return(await Promise.all(e.filter(r=>r.endsWith(".json")).map(r=>this.loadSession(r.slice(0,-5))))).filter(r=>r!==null)}async resolveSessionPath(e){if(!Fb.test(e))return null;let n=pi(this.home,"sessions",`${e}.json`);try{return(await Ob(n)).isFile()?n:null}catch{return null}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;try{let r=$b(JSON.parse(await Nb(n,"utf8")),e,n);if(!r)return null;let s="complete";try{let i=JSON.parse(await Nb(`${n}.lock`,"utf8"));if(Number.isInteger(i.pid)&&i.pid>0)try{process.kill(i.pid,0),s="in_progress"}catch{s="aborted"}}catch{}return{...r,...s!=="complete"?{turnStatus:s}:{}}}catch{return null}}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;try{throw await Ob(`${n}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(r){if(r.code!=="ENOENT")throw r}return await EM(n),!0}}});import{createHash as kM}from"node:crypto";import{createRequire as RM}from"node:module";import{readdir as xM,realpath as IM}from"node:fs/promises";import{basename as jb,dirname as AM,join as Ub,resolve as Bb}from"node:path";function NM(){return CM("node:sqlite").DatabaseSync}function OM(){return process.env.HOME||process.env.USERPROFILE||""}function Es(t){let e=[],n=0,r=()=>{let s=0n,i=0n;for(;;){if(n>=t.length||i>63n)return null;let o=t[n++];if(s|=BigInt(o&127)<<i,i+=7n,!(o&128))break}return s<=BigInt(Number.MAX_SAFE_INTEGER)?Number(s):null};for(;n<t.length;){let s=r();if(s===null)return e;let i=s>>>3,o=s&7;if(i===0)return e;if(o===0){let a=r();if(a===null)return e;e.push({field:i,wire:o,varint:a})}else if(o===1){if(n+8>t.length)return e;n+=8,e.push({field:i,wire:o})}else if(o===5){if(n+4>t.length)return e;n+=4,e.push({field:i,wire:o})}else if(o===2){let a=r();if(a===null||n+a>t.length)return e;e.push({field:i,wire:o,bytes:t.subarray(n,n+a)}),n+=a}else return e}return e}function bn(t,e){return t.find(n=>n.field===e)}function LM(t){let e=new Map;for(let n of t){if(n.field!==20||n.bytes===void 0)continue;let r=Es(n.bytes),s=bn(r,1)?.bytes,i=bn(r,2)?.bytes;if(s===void 0||i===void 0)continue;let o=s.toString("utf8");e.has(o)||e.set(o,i.toString("utf8"))}return e}function MM(t){let e=bn(Es(t),5)?.bytes;if(e===void 0)return null;let n=bn(Es(e),1)?.bytes;if(n===void 0)return null;let r=Es(n),s=bn(r,1)?.varint;if(s===void 0)return null;let i=bn(r,2)?.varint??0,o=s*1e3+Math.floor(i/1e6),a=new Date(o);return Number.isFinite(a.getTime())?a.toISOString():null}function PM(t){let e=bn(t,4)?.bytes,n=e!==void 0?Es(e):[],r=s=>{let i=bn(n,s)?.varint;return i===void 0?null:re(i)};return{tokens:{input_uncached:r(2),input_cached:r(5),input_cache_write:r(4),output:r(3)},thinkingOutputTokens:r(9)}}function DM(t){let e=bn(Es(t),1)?.bytes;if(e===void 0)return null;let n=Es(e),r=LM(n),s=r.get("request_id");if(s===void 0||s.length===0)return null;let i=bn(n,19)?.bytes,o=i!==void 0&&i.length>0?i.toString("utf8"):null,a=r.get("last_step_index"),l=a===void 0?Number.NaN:Number(a),c=Number.isSafeInteger(l)&&l>=0?l:null,{tokens:u,thinkingOutputTokens:d}=PM(n);return{requestId:s,model:o,lastStepIndex:c,tokens:u,thinkingOutputTokens:d}}function Hb(t,e){_e(e);let n=t.prepare("SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) AS total FROM gen_metadata").get(),r=re(n?.total);if(r===null||r>e.maxBytes)return null;let s=t.prepare("SELECT idx, data FROM gen_metadata ORDER BY idx LIMIT ?").all(e.maxRows+1);if(s.length>e.maxRows)return null;let i=kM("sha256");i.update("rev:").update(ac).update(`
|
|
514
515
|
`);let o=[],a=[],l=0;for(let d of s){if(e.signal.throwIfAborted(),!(d.data instanceof Uint8Array))return null;let m=Buffer.from(d.data);if(l+=m.length,l>e.maxBytes)return null;i.update("g").update(String(d.idx)).update("\0").update(m).update(`
|
|
515
516
|
`);let p=DM(m);p!==null&&(o.push(p),p.lastStepIndex!==null&&a.push(p.lastStepIndex))}let c=new Map,u=[...new Set(a)].sort((d,m)=>d-m);for(let d of u){e.signal.throwIfAborted();let p=t.prepare("SELECT idx, step_payload FROM steps WHERE idx = ?").get(d)?.step_payload;if(!(p instanceof Uint8Array))continue;let f=Buffer.from(p);if(l+=f.length,l>e.maxBytes)return null;i.update("s").update(String(d)).update("\0").update(f).update(`
|
|
516
|
-
`);let h=MM(f);h!==null&&c.set(d,h)}return{revision:`${jo}+${ac}:sha256:${i.digest("hex")}`,generations:o,timestamps:c}}function FM(t){return t.generations.map(e=>({response_id:e.requestId,timestamp:e.lastStepIndex===null?null:t.timestamps.get(e.lastStepIndex)??null,model:e.model,tokens:e.tokens,files_read:null,files_written:null,external_io:null,read_bytes:null,write_bytes:null,model_provider:null,pricing_facts:vn({reasoning:e.thinkingOutputTokens},e.tokens.output,e.tokens.input_cache_write)}))}function Wb(t={}){return new Bo(t)}var xr,ac,CM,Bo,Sp=L(()=>{"use strict";Yn();xr="agy",ac="agy-tokens-v1",CM=RM(import.meta.url);Bo=class{conversationsDir;sqliteBusyTimeoutMs;constructor(e={}){this.conversationsDir=Bb(e.agyConversationsDir??Ub(OM(),".gemini","antigravity-cli","conversations")),this.sqliteBusyTimeoutMs=e.sqliteBusyTimeoutMs??5e3}async discover(e,n,r=null){_e(e);let s=await xM(this.conversationsDir,{withFileTypes:!0}).catch(()=>[]),i=[];for(let o of s){if(e.signal.throwIfAborted(),!o.isFile()||o.isSymbolicLink()||!o.name.endsWith(".db"))continue;let a=await IM(Ub(this.conversationsDir,o.name)).catch(()=>null);a!==null&&(r!==null&&Te(a,r)<=0||i.push(a))}return i.sort(Te),{sources:i.slice(0,n).map(o=>({provider:xr,sessionid:jb(o,".db"),source_id:o})),truncated:!1}}async open(e){let n=await Ye(e.source_id,[this.conversationsDir]);if(n===null||jb(n,".db")!==e.sessionid||Bb(AM(n))!==this.conversationsDir)return null;try{let r=new(NM())(n,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.sqliteBusyTimeoutMs}`),r}catch{return null}}async inspect(e,n){if(_e(n),e.provider!==xr)return{status:"unsupported"};let r=await this.open(e);if(r===null)return{status:"unavailable"};try{let s=Hb(r,n);return s?{status:"ready",revision:s.revision}:{status:"partial"}}catch{return{status:"unsupported"}}finally{r.close()}}async read(e,n,r){if(_e(r),e.provider!==xr)return{status:"unsupported"};let s=await this.open(e);if(s===null)return{status:"unavailable"};try{s.exec("BEGIN");let i=Hb(s,r);if(i===null||i.revision!==n)return s.exec("ROLLBACK"),{status:"partial"};let o=FM(i);return s.exec("COMMIT"),{status:"complete",source:e,revision:n,checkpoint:n,responses:o}}catch{try{s.exec("ROLLBACK")}catch{}return{status:"unsupported"}}finally{s.close()}}}});import $M from"node:zlib";function JM(t,e){return t[e]===UM&&t[e+1]===BM&&t[e+2]===HM&&t[e+3]===WM}function qb(t,e){return(t[e]&240)===80&&t[e+1]===qM&&t[e+2]===XM&&t[e+3]===GM}function VM(t,e){if(qb(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!JM(t,e))return;let n=e+4;if(n+1>t.length)return;let r=t[n];n+=1;let s=r>>6,i=(r&32)!==0,o=(r&4)!==0,a=r&3;i||(n+=1),n+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(n+=l,!(n>t.length)){for(;;){if(n+3>t.length)return;let c=t[n]|t[n+1]<<8|t[n+2]<<16,u=(c&1)!==0,d=c>>1&3,m=c>>3;if(n+=3,d===3||(n+=d===1?1:m,n>t.length))return;if(u)break}if(o&&(n+=4),!(n>t.length))return n-e}}function Ho(t){let e=[],n=0;for(;n+4<=t.length;){let r=VM(t,n);if(r===void 0||r<=0)break;e.push(t.subarray(n,n+r)),n+=r}return e}function lc(t){let e=[];for(let n of Ho(t))qb(n,0)||e.push(jM(n).toString("utf8"));return e.join("")}var jM,UM,BM,HM,WM,qM,XM,GM,cc=L(()=>{"use strict";jM=$M.zstdDecompressSync,UM=40,BM=181,HM=47,WM=253,qM=42,XM=77,GM=24});import{readdir as KM,realpath as zM}from"node:fs/promises";import{basename as kp,dirname as Xb,join as Vb,resolve as Kb}from"node:path";import YM from"node:zlib";function zb(t){return/^session(\.v\d+)?\.jsonl\.zstd$/.test(t)}function rP(t){return nP.has(t)||kr(t)}function sP(){return process.env.HOME||process.env.USERPROFILE||""}function iP(t){if(typeof t=="string")return Buffer.byteLength(t,"utf8");if(!Array.isArray(t))return null;let e=0,n=!1;for(let r of t){let s=
|
|
517
|
-
`)){if(!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}let s=typeof r.type=="string"?r.type:"";s.endsWith("-chunks")||s==="assistant/chunk"&&J(J(r.data)?.chunk)?.type!=="usage"||e.push(r)}return e}function cP(t){if(typeof t=="string")try{return J(JSON.parse(t))}catch{return null}return J(t)}function Jb(t,e){return typeof t!="number"||typeof e!="number"?null:`${t}\0${e}`}function uP(t,e,n,r){let s=new Map,i=[],o=new Set,a=new Map,l=null,c=null,u=null;for(let m of t){r.signal.throwIfAborted();let p=J(m.data);if(m.type==="assistant/chunk"){let f=J(p?.chunk),h=J(f?.usage),g=Jb(p?.turn,p?.step);h&&g!==null&&typeof p?.turn=="number"&&typeof p?.step=="number"&&a.set(g,{turn:p.turn,step:p.step,usage:h,time:m.time});continue}if(m.type==="request/header"){let f=J(J(p?.header)?.config);typeof f?.provider=="string"&&f.provider&&(l=f.provider),typeof f?.model=="string"&&f.model&&(c=f.model);continue}if(m.type==="user/message"){if(J(p?.source)?.kind!=="user")continue;let h=typeof p?.id=="string"&&p.id?p.id:null;i.push({id:h,bytes:iP(p?.content)});continue}if(m.type==="assistant/message"){let f=J(p?.message),h=J(f?.source),g=typeof f?.id=="string"&&f.id?f.id:null,y=Jb(p?.turn,p?.step),b;if(y!==null)o.add(y),b=`dsh:turn-step:${p.turn}/${p.step}`;else{if(J(p?.usage))return{status:"partial"};b=g}if(b===null)return{status:"partial"};let _=Gb(J(p?.usage)),v=s.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Bt(typeof m.time=="number"?m.time:null),model:(typeof h?.model=="string"&&h.model?h.model:null)??c,tokens:_??{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,reasoning:null,provider:typeof h?.provider=="string"&&h.provider?h.provider:null},s.set(b,v),s.size>r.maxRows)return{status:"partial"};for(let E of i)v.io.record({direction:"read",kind:"prompt",id:E.id,ref:null,bytes:E.bytes,basis:E.bytes===null?"unknown":"input_text"});i.length=0}if(_){v.meta.tokens=_;let E=re(J(p?.usage)?.reasoningTokens);E!==null&&(v.reasoning=E)}u=b;continue}if(m.type==="tool/call"){let f=u!==null?s.get(u):void 0;if(!f)continue;let h=typeof p?.callId=="string"&&p.callId?p.callId:null,g=typeof p?.name=="string"?p.name.toLowerCase():"",y=cP(p?.arguments),b=(typeof y?.file_path=="string"&&y.file_path?y.file_path:null)??(typeof y?.path=="string"&&y.path?y.path:null);eP.has(g)?b!==null?f.obs.record(h??"","read",b,null):$e(f.io,h):tP.has(g)?b!==null?f.obs.record(h??"","written",b,ui(y)):$e(f.io,h):rP(g)||$e(f.io,h);continue}}for(let[m,{turn:p,step:f,usage:h,time:g}]of a){if(o.has(m))continue;r.signal.throwIfAborted();let y=Gb(h),b=new Ut;$e(b,null);let _={meta:{response_id:`dsh:turn-step:${p}/${f}`,timestamp:Bt(typeof g=="number"?g:null),model:c,tokens:y??{...xt},files_read:[],files_written:[]},obs:new jt,io:b,reasoning:re(h.reasoningTokens),provider:l};if(s.set(_.meta.response_id,_),s.size>r.maxRows)return{status:"partial"}}let d=[];for(let{meta:m,obs:p,io:f,reasoning:h,provider:g}of s.values()){let y=p.files("read"),b=p.files("written"),_=f.entries();d.push({...m,files_read:y,files_written:b,external_io:_,read_bytes:_t(y,_,"read"),write_bytes:_t(b,_,"written"),model_provider:l??g,pricing_facts:vn({reasoning:h??void 0},m.tokens.output,m.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:d}}async function dP(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c,u){r.signal.throwIfAborted();let d=await KM(c,{withFileTypes:!0}).catch(()=>[]);d.sort((m,p)=>Te(m.name,p.name));for(let m of d){if(r.signal.throwIfAborted(),i.length>=e)return;if(o+=1,o>n){a=!0;return}let p=Vb(c,m.name);if(m.isDirectory()&&!m.isSymbolicLink()&&u<2){if(await l(p,u+1),a||i.length>=e)return}else if(m.isFile()&&zb(m.name)){let f=await zM(p).catch(()=>Kb(p));(s===null||Te(f,s)>0)&&i.push(f)}}}return await l(t,0),{paths:i.sort(Te),truncated:a}}function Yb(t={}){return new Rp(t)}var Ir,QM,ZM,eP,tP,nP,Rp,Qb=L(()=>{"use strict";Yn();cc();Ir="dsh",QM=YM.zstdDecompressSync;ZM=5e5,eP=new Set(["read","read_image"]),tP=new Set(["write","edit"]),nP=new Set(["create_goal","get_goal","update_goal","todo_write","ask_user_question","exit_plan_mode","list_agents","interrupt_agent","job_list","job_kill","job_output"]);Rp=class{sessionsDir;maxDiscoveryTraversalVisits;constructor(e={}){let n=e.dshHome??process.env.DSH_HOME??Vb(sP(),".dsh");this.sessionsDir=Kb(n,"sessions"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):ZM}async discover(e,n,r=null){_e(e);let{paths:s,truncated:i}=await dP(this.sessionsDir,n,this.maxDiscoveryTraversalVisits,e,r);return{sources:s.map(o=>({provider:Ir,sessionid:kp(Xb(o)),source_id:o})),truncated:i}}matches(e,n){return zb(kp(n))&&kp(Xb(n))===e.sessionid}async inspect(e,n){if(_e(n),e.provider!==Ir)return{status:"unsupported"};let r=await Ye(e.source_id,[this.sessionsDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(_e(r),e.provider!==Ir)return{status:"unsupported"};let s=await Ye(e.source_id,[this.sessionsDir]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await It(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let{text:o,truncated:a}=aP(i.data,r);return a?{status:"partial"}:uP(lP(o),e,n,r)}}});import{readdir as mP,realpath as pP}from"node:fs/promises";import{basename as uc,dirname as fP,join as xp,resolve as Zb}from"node:path";function bP(){return process.env.HOME||process.env.USERPROFILE||""}function wP(){let t=bP();return[xp(t,".qwen","projects"),xp(t,".qwen.bk1","projects")]}function EP(t){return t.type!=="system"||t.subtype!=="ui_telemetry"?null:J(J(t.systemPayload)?.uiEvent)}function TP(t){let e=t["event.name"];return typeof e=="string"&&e.length>0?e:null}function SP(t){let e=re(t.input_token_count),n=re(t.output_token_count),r=re(t.cached_content_token_count),s=re(t.total_token_count);if(e===null||n===null||r===null||s===null||r>e||e+n!==s)return null;let i=t.thoughts_token_count===void 0?null:re(t.thoughts_token_count);return t.thoughts_token_count!==void 0&&(i===null||i>n)?null:{input_uncached:e-r,input_cached:r,input_cache_write:null,output:n}}function kP(t){let e=J(t)?.parts;if(!Array.isArray(e))return null;let n=0,r=!1;for(let s of e){let i=J(s);!i||i.thought===!0||typeof i.text=="string"&&(n+=Buffer.byteLength(i.text,"utf8"),r=!0)}return r?n:null}function RP(t){let e=new Map,n=new Set,r=new Map;for(let o of t){let a=typeof o.uuid=="string"&&o.uuid?o.uuid:null;if(a!==null&&(e.set(a,typeof o.parentUuid=="string"&&o.parentUuid?o.parentUuid:null),o.type==="user")){n.add(a);let l=kP(o.message);l!==null&&r.set(a,l)}}let s=new Map;return{promptBytes:r,resolve:o=>{let a=[],l=new Set,c=o,u;for(;;){let d=s.get(c);if(d){u=d;break}if(n.has(c)){u={kind:"found",uuid:c};break}if(!e.has(c)){u={kind:"broken"};break}if(l.has(c)){u={kind:"broken"};break}l.add(c),a.push(c);let m=e.get(c)??null;if(m===null){u={kind:"clean"};break}c=m}for(let d of a)s.set(d,u);return u}}}function xP(t,e,n,r){let{promptBytes:s,resolve:i}=RP(t),o=new Set,a=new Map,l=0;for(let u of t){r.signal.throwIfAborted();let d=EP(u);if(d===null)continue;let m=TP(d);if(m===gP){let b=typeof d.response_id=="string"&&d.response_id?d.response_id:null;if(b===null)return{status:"unsupported"};let _=SP(d);if(_===null)return{status:"partial"};let v=a.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Bt(d["event.timestamp"]??u.timestamp),model:typeof d.model=="string"&&d.model?d.model:null,tokens:{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,thoughts:null},a.set(b,v),a.size>r.maxRows)return{status:"partial"};let x=typeof u.uuid=="string"&&u.uuid?u.uuid:null,S=x===null?{kind:"broken"}:i(x);if(S.kind==="broken")v.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"});else if(S.kind==="found"&&!o.has(S.uuid)){o.add(S.uuid);let R=s.get(S.uuid)??null;v.io.record({direction:"read",kind:"prompt",id:S.uuid,ref:null,bytes:R,basis:R===null?"unknown":"input_text"})}}v.meta.tokens=_,typeof d.model=="string"&&d.model&&(v.meta.model=d.model);let E=re(d.thoughts_token_count);E!==null&&(v.thoughts=E);continue}if(m!==hP)continue;let p=typeof d.response_id=="string"&&d.response_id?d.response_id:null;if(p===null)continue;let f=a.get(p);if(f===void 0)return{status:"partial"};let h=typeof d.function_name=="string"?d.function_name.toLowerCase():"",g=J(d.function_args),y=`tool-${l++}`;if(yP.has(h)){let b=typeof g?.file_path=="string"?g.file_path:null;b!==null?f.obs.record(y,"read",b,null):$e(f.io,y)}else if(_P.has(h)){let b=typeof g?.file_path=="string"?g.file_path:null;b!==null?f.obs.record(y,"written",b,ui(g)):$e(f.io,y)}else kr(h)||$e(f.io,y)}let c=[];for(let{meta:u,obs:d,io:m,thoughts:p}of a.values()){let f=d.files("read"),h=d.files("written"),g=m.entries();c.push({...u,files_read:f,files_written:h,external_io:g,read_bytes:_t(f,g,"read"),write_bytes:_t(h,g,"written"),model_provider:null,pricing_facts:vn({reasoning:p??void 0},u.tokens.output,u.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:c}}async function IP(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c){r.signal.throwIfAborted();let u=await mP(c,{withFileTypes:!0}).catch(()=>[]);u.sort((d,m)=>Te(d.name,m.name));for(let d of u){if(r.signal.throwIfAborted(),i.length>=e)return;if(o+=1,o>n){a=!0;return}let m=xp(c,d.name);if(d.isDirectory()&&!d.isSymbolicLink()){if(await l(m),a||i.length>=e)return}else if(d.isFile()&&d.name.endsWith(".jsonl")&&uc(c)===ew){let p=await pP(m).catch(()=>Zb(m));(s===null||Te(p,s)>0)&&i.push(p)}}}return await l(t),{paths:i.sort(Te),truncated:a}}function AP(t,e){for(let n of t){let r=n.sessionId;if(typeof r=="string"&&r.length>0&&r!==e)return!1}return!0}function tw(t={}){return new Ip(t)}var Ar,gP,hP,ew,yP,_P,vP,Ip,nw=L(()=>{"use strict";Yn();Ar="qwen",gP="qwen-code.api_response",hP="qwen-code.tool_call",ew="chats",yP=new Set(["read_file"]),_P=new Set(["write_file"]),vP=5e5;Ip=class{roots;maxDiscoveryTraversalVisits;constructor(e={}){this.roots=(e.qwenProjectsDirs??wP()).map(n=>Zb(n)),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):vP}async discover(e,n,r=null){_e(e);let s=new Map,i=!1;for(let a of this.roots){e.signal.throwIfAborted();let l=await IP(a,n,this.maxDiscoveryTraversalVisits,e,r);l.truncated&&(i=!0);for(let c of l.paths)s.set(c,c)}return{sources:[...s.keys()].sort(Te).slice(0,n).map(a=>({provider:Ar,sessionid:uc(a,".jsonl"),source_id:a})),truncated:i}}matches(e,n){return uc(n,".jsonl")===e.sessionid&&uc(fP(n))===ew}async inspect(e,n){if(_e(n),e.provider!==Ar)return{status:"unsupported"};let r=await Ye(e.source_id,[...this.roots]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(_e(r),e.provider!==Ar)return{status:"unsupported"};let s=await Ye(e.source_id,[...this.roots]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await It(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let o=Zl(i.data,r);return o?AP(o,e.sessionid)?xP(o,e,n,r):{status:"unavailable"}:{status:"partial"}}}});import{createHash as CP}from"node:crypto";import{createRequire as NP}from"node:module";import{join as Wo,resolve as Ap}from"node:path";function LP(){return OP("node:sqlite").DatabaseSync}function rw(){return process.env.HOME||process.env.USERPROFILE||""}function MP(){let t=process.env.XDG_DATA_HOME||Wo(rw(),".local","share"),e=process.env.XDG_CONFIG_HOME||Wo(rw(),".config");return[Wo(t,"opencode","opencode.db"),Wo(t,"opencode","opencode-local.db"),Wo(e,"opencode","opencode.db")]}function jP(t){if(typeof t!="string")return null;let e=t.toLowerCase();return e==="apply_patch"?"apply_patch":PP.includes(e)?"read":DP.includes(e)?"written":null}function sw(t,e=FP){let n=J(t);if(!n)return null;for(let r of e){let s=n[r];if(typeof s=="string"&&s.length>0)return s;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.length>0)return i}}return null}function UP(t){let e=J(t);if(!e)return null;if(typeof e.content=="string")return Buffer.byteLength(e.content,"utf8");if(typeof e.newString=="string")return Buffer.byteLength(e.newString,"utf8");if(typeof e.new_string=="string")return Buffer.byteLength(e.new_string,"utf8");if(typeof e.newSource=="string")return Buffer.byteLength(e.newSource,"utf8");if(Array.isArray(e.edits)){let n=0;for(let r of e.edits){let s=J(r),i=s?.newString??s?.new_string;if(typeof i!="string")return null;n+=Buffer.byteLength(i,"utf8")}return n}return null}function BP(t){let e=new Map,n=null,r=()=>{n&&(e.set(n.path,(e.get(n.path)??0)+n.bytes),n=null)};for(let s of t.split(`
|
|
518
|
-
`)){let i=s.replace(/\r$/,""),o=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(i);if(o){r(),n={path:o[1].trim(),bytes:0};continue}let a=/^\*\*\* Move to: (.+)$/.exec(i);if(a){n&&(n.path=a[1].trim());continue}if(i.startsWith("*** ")){r();continue}n&&i.startsWith("+")&&(n.bytes+=Buffer.byteLength(i.slice(1),"utf8")+1)}return r(),[...e].map(([s,i])=>({path:s,bytes:i}))}function HP(t){if(typeof t!="string"||t.length===0)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:`${e.origin}${e.pathname}`}catch{return null}}function WP(t,e=!1){let n=
|
|
519
|
-
`)}return{revision:`${jo}:sha256:${c.digest("hex")}`,messages:o,parts:a}}function qP(t){let e=0,n=!1,r=!1;for(let s of t){let i;try{i=
|
|
520
|
-
`)){let i=s.replace(/\r$/,""),o=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(i);if(o){r(),n={path:o[1].trim(),bytes:0};continue}let a=/^\*\*\* Move to: (.+)$/.exec(i);if(a){n&&(n.path=a[1].trim());continue}if(i.startsWith("*** ")){r();continue}n&&i.startsWith("+")&&(n.bytes+=Buffer.byteLength(i.slice(1),"utf8")+1)}return r(),[...e].map(([s,i])=>({path:s,bytes:i}))}function ZP(t){let e=t?.content;return typeof e=="string"?Buffer.byteLength(e,"utf8"):null}function e0(t,e,n){let r=J(t);if(!r)return{entry:null,incomplete:t!=null};let s=[],i=!1;for(let[a,l]of Object.entries(r)){let c=J(l);if(!c){i=!0;continue}let u=J(c.usage),d=J(c.requests),m=J(c.tokenDetails),p=J(m?.input);s.push({model:a,requests_count:d?re(d.count):null,input_tokens:u?re(u.inputTokens):null,input_other_tokens:p?re(p.tokenCount):null,cache_read_tokens:u?re(u.cacheReadTokens):null,cache_write_tokens:u?re(u.cacheWriteTokens):null,output_tokens:u?re(u.outputTokens):null,reasoning_tokens:u?re(u.reasoningTokens):null})}s.sort((a,l)=>Te(a.model,l.model));let o=i||s.length>0;return e===null?{entry:null,incomplete:o}:{entry:{native_id:e,recorded_at:n,kind:"copilot_session_shutdown",semantics:"reported_scope_unknown",models:s},incomplete:i}}function t0(t,e,n,r){let s=new Map;for(let d of t){if(d.type!=="user.message")continue;let m=J(d.data),p=typeof m?.interactionId=="string"?m.interactionId:null;if(p===null)continue;let f=ZP(m);s.has(p)?s.get(p)===null&&f!==null&&s.set(p,f):s.set(p,f)}let i=new Map,o=new Set,a=new Map,l=!1,c=1e3;for(let d of t){if(r.signal.throwIfAborted(),d.type==="session.shutdown"){let y=typeof d.id=="string"&&d.id?d.id:null,b=Bt(d.timestamp),{entry:_,incomplete:v}=e0(J(d.data)?.modelMetrics,y,b);if(v&&(l=!0),_){let E=a.get(_.native_id);if(E&&JSON.stringify(E)!==JSON.stringify(_))l=!0;else if(a.set(_.native_id,_),a.size>c)return{snapshot:{status:"partial"},sessionUsage:null}}continue}if(d.type!=="assistant.message")continue;let m=J(d.data);if(!m)continue;let p=typeof m.messageId=="string"&&m.messageId?m.messageId:typeof d.id=="string"&&d.id?d.id:null;if(p===null)continue;let f=typeof m.interactionId=="string"?m.interactionId:null,h=i.get(p);if(!h){if(h={meta:{response_id:p,timestamp:Bt(d.timestamp),model:typeof m.model=="string"&&m.model?m.model:null,tokens:{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,promptRecorded:!1},i.set(p,h),i.size>r.maxRows)return{snapshot:{status:"partial"},sessionUsage:null};if(f!==null&&s.has(f)){if(!o.has(f)){o.add(f);let y=s.get(f);h.io.record({direction:"read",kind:"prompt",id:f,ref:null,bytes:y,basis:y===null?"unknown":"input_text"}),h.promptRecorded=!0}}else h.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"})}let g=re(m.outputTokens);if(g!==null&&(h.meta.tokens.output=(h.meta.tokens.output??0)+g),h.meta.model===null&&typeof m.model=="string"&&m.model&&(h.meta.model=m.model),Array.isArray(m.toolRequests))for(let y of m.toolRequests){let b=J(y);if(!b)continue;let _=typeof b.name=="string"?b.name.toLowerCase():"",v=typeof b.toolCallId=="string"&&b.toolCallId?b.toolCallId:null,E=b.arguments;if(_==="create"){let x=J(E),S=typeof x?.path=="string"?x.path:null,R=typeof x?.file_text=="string"?Buffer.byteLength(x.file_text,"utf8"):null;S!==null?h.obs.record(v??p,"written",S,R):$e(h.io,v)}else if(_==="apply_patch")if(typeof E=="string"){let x=QP(E);if(x.length>0)for(let S of x)h.obs.record(v??p,"written",S.path,S.bytes);else $e(h.io,v)}else $e(h.io,v);else if(YP.has(_)){let x=J(E),S=typeof x?.path=="string"?x.path:null;S!==null?h.obs.record(v??p,"read",S,null):$e(h.io,v)}else zP.has(_)||$e(h.io,v)}}let u=[];for(let{meta:d,obs:m,io:p}of i.values()){let f=m.files("read"),h=m.files("written"),g=p.entries();u.push({...d,files_read:f,files_written:h,external_io:g,read_bytes:_t(f,g,"read"),write_bytes:_t(h,g,"written"),model_provider:null,pricing_facts:null})}return l?{snapshot:{status:"partial"},sessionUsage:null}:{snapshot:{status:"complete",source:e,revision:n,checkpoint:n,responses:u},sessionUsage:a.size>0?[...a.values()]:null}}function n0(){return process.env.HOME||process.env.USERPROFILE||""}function dw(t={}){return new Np(t)}var Cr,uw,zP,YP,Np,mw=L(()=>{"use strict";Yn();Cr="copilot",uw="events.jsonl",zP=new Set(["report_intent"]),YP=new Set(["view"]);Np=class{sessionStateDir;constructor(e={}){this.sessionStateDir=cw(e.copilotSessionStateDir??lw(n0(),".copilot","session-state"))}async discover(e,n,r=null){_e(e);let s;try{s=await GP(this.sessionStateDir)}catch{return{sources:[],truncated:!1}}let i=[];for(let o of s.sort(Te)){e.signal.throwIfAborted();let a=lw(this.sessionStateDir,o,uw);if(!(await VP(a).catch(()=>null))?.isFile())continue;let c=await JP(a).catch(()=>cw(a)),u={provider:Cr,sessionid:o,source_id:c};r!==null&&Te(`${c}\0${o}`,r)<=0||i.push(u)}return i.sort((o,a)=>Te(`${o.source_id}\0${o.sessionid}`,`${a.source_id}\0${a.sessionid}`)),{sources:i.slice(0,n),truncated:!1}}matches(e,n){return aw(n)===uw&&aw(KP(n))===e.sessionid}async inspect(e,n){if(_e(n),e.provider!==Cr)return{status:"unsupported"};let r=await Ye(e.source_id,[this.sessionStateDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){return(await this.readWithUsage(e,n,r)).snapshot}async readWithUsage(e,n,r){if(_e(r),e.provider!==Cr)return{snapshot:{status:"unsupported"},sessionUsage:null};let s=await Ye(e.source_id,[this.sessionStateDir]);if(!s||!this.matches(e,s))return{snapshot:{status:"unavailable"},sessionUsage:null};let i=await It(s,r).catch(()=>null);if(!i||i.revision!==n)return{snapshot:{status:"partial"},sessionUsage:null};let o=Zl(i.data,r);return o?t0(o,e,n,r):{snapshot:{status:"partial"},sessionUsage:null}}}});import{readdir as pw,readFile as r0,realpath as Op,stat as fw}from"node:fs/promises";import{basename as Go,dirname as gi,isAbsolute as Mp,join as fi,relative as yw,resolve as Xo,sep as _w}from"node:path";function u0(t){return c0.has(t)||kr(t)}function d0(){return process.env.HOME||process.env.USERPROFILE||""}function m0(t,e){if(t.length>0&&t[t.length-1]!==10)return null;let n=[],r=0;for(;r<t.length;){e.signal.throwIfAborted();let s=t.indexOf(10,r);s===-1&&(s=t.length);let i=t.toString("utf8",r,s);if(r=s+1,!!i.trim())try{let o=J(JSON.parse(i));if(!o)return null;n.push(o)}catch{return null}}return n}function gw(t){let e=J(t);if(!e)return null;let n=re(e.inputOther),r=re(e.inputCacheRead),s=re(e.inputCacheCreation),i=re(e.output);return n===null||r===null||s===null||i===null?null:{input_uncached:n+s,input_cached:r,input_cache_write:s,output:i}}function p0(t){if(!Array.isArray(t))return null;let e=0,n=!1;for(let r of t){let s=J(r);s?.type==="text"&&typeof s.text=="string"&&(e+=Buffer.byteLength(s.text,"utf8"),n=!0)}return n?e:null}function g0(t,e,n,r){let s=t.find(b=>b.type==="metadata"),i=s&&typeof s.protocol_version=="string"?s.protocol_version:null;if(i!==null&&!s0.has(i))return{status:"unsupported"};let o=h0(e.source_id),a=new Map,l=new Map,c=[],u=new Set,d=new Set,m=null,p=!1,f=b=>`${o}/${b}`,h=(b,_)=>{let v=f(b),E=a.get(v);return E||(E={meta:{response_id:v,timestamp:Bt(typeof _=="number"?_:null),model:null,tokens:{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,turnStepKey:null,tokensSource:"none"},a.set(v,E)),E},g=(b,_)=>{if(b.turnStepKey!==null)return;let v=_.turnId===void 0?null:String(_.turnId),E=_.step===void 0?null:String(_.step);v!==null&&E!==null&&(b.turnStepKey=`${v}.${E}`)};for(let b of t){if(r.signal.throwIfAborted(),b.type==="turn.prompt"){let v=J(b.origin),E=typeof v?.kind=="string"?v.kind:null,x=typeof b.promptId=="string"&&b.promptId?b.promptId:null;if(E!==null&&f0.has(E))continue;if(x!==null){if(u.has(x))continue;u.add(x)}E==="user"?c.push({bytes:p0(b.input),id:x}):c.push({bytes:null,id:x});continue}if(b.type==="usage.record"){if(d.size>1){p=!0;continue}if(d.size===0){m===null&&(p=!0);continue}let[v]=d,E=a.get(f(v));if(!E){p=!0;continue}if(E.tokensSource==="record"){p=!0;continue}let x=gw(b.usage);x&&(E.meta.tokens=x,E.tokensSource="record");continue}if(b.type==="llm.request"){let v=typeof b.turnStep=="string"?b.turnStep:null,E=(typeof b.modelAlias=="string"&&b.modelAlias?b.modelAlias:null)??(typeof b.model=="string"&&b.model?b.model:null);v!==null&&E!==null&&(l.has(v)?l.get(v)!==E&&l.set(v,null):l.set(v,E));continue}if(b.type!=="context.append_loop_event")continue;let _=J(b.event);if(_){if(_.type==="step.begin"){let v=typeof _.uuid=="string"&&_.uuid?_.uuid:null;if(v===null)continue;let E=h(v,b.time);if(a.size>r.maxRows)return{status:"partial"};if(d.add(v),g(E,_),c.length>0){for(let x of c)E.io.record({direction:"read",kind:"prompt",id:x.id,ref:null,bytes:x.bytes,basis:x.bytes===null?"unknown":"input_text"});c.length=0}continue}if(_.type==="step.end"){let v=typeof _.uuid=="string"&&_.uuid?_.uuid:null;if(v===null)continue;let E=h(v,b.time);if(a.size>r.maxRows)return{status:"partial"};d.delete(v),m=v,g(E,_);let x=gw(_.usage);x&&(E.meta.tokens=x),E.tokensSource="end",E.meta.timestamp===null&&(E.meta.timestamp=Bt(typeof b.time=="number"?b.time:null));continue}if(_.type==="tool.call"){let v=typeof _.stepUuid=="string"&&_.stepUuid?_.stepUuid:null;if(v===null)continue;let E=h(v,b.time);if(a.size>r.maxRows)return{status:"partial"};let x=typeof _.name=="string"?_.name.toLowerCase():"",S=typeof _.toolCallId=="string"&&_.toolCallId?_.toolCallId:null,R=J(_.args),N=typeof R?.path=="string"&&R.path?R.path:typeof R?.file_path=="string"&&R.file_path?R.file_path:null;a0.has(x)?N!==null?E.obs.record(S??"","read",N,null):$e(E.io,S):l0.has(x)?N!==null?E.obs.record(S??"","written",N,ui(R)):$e(E.io,S):u0(x)||$e(E.io,S);continue}}}let y=[];for(let{meta:b,obs:_,io:v,turnStepKey:E}of a.values()){b.model===null&&E!==null&&(b.model=l.get(E)??null);let x=_.files("read"),S=_.files("written"),R=v.entries();y.push({...b,files_read:x,files_written:S,external_io:R,read_bytes:_t(x,R,"read"),write_bytes:_t(S,R,"written"),model_provider:null,pricing_facts:vn({},b.tokens.output,b.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:y,...p?{capture_status:"partial"}:{}}}function Lp(t){return Go(t)===Pp&&Go(gi(gi(t)))===vw}function hw(t){return Go(gi(gi(gi(t))))}function h0(t){return Go(gi(t))}function y0(t,e){let n=yw(e,t);return n===""||!n.startsWith(`..${_w}`)&&n!==".."&&!Mp(n)}function _0(t){if(t instanceof Error&&t.name==="AbortError")throw t}function bw(t={}){return new Jo(t)}var Nr,Pp,vw,s0,i0,o0,a0,l0,c0,f0,Jo,Dp=L(()=>{"use strict";Yn();Nr="kimi",Pp="wire.jsonl",vw="agents",s0=new Set(["1.4","1.5"]),i0=5e5,o0=8*1024*1024,a0=new Set(["read"]),l0=new Set(["write","edit"]),c0=new Set(["todolist","tasklist","taskoutput","taskstop","waitfor","creategoal","updategoal","getgoal","enterplanmode","exitplanmode","agentswarm","agent","skill","croncreate","crondelete","cronlist"]);f0=new Set(["system_trigger","cron_job","task"]);Jo=class{home;sessionsDir;indexPath;maxDiscoveryTraversalVisits;constructor(e={}){this.home=Xo(e.kimiHome??process.env.KIMI_CODE_HOME??fi(d0(),".kimi-code")),this.sessionsDir=fi(this.home,"sessions"),this.indexPath=fi(this.home,"session_index.jsonl"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):i0}async discover(e,n,r=null){_e(e);let s=new Set,i=!1,o=await Op(this.sessionsDir).catch(()=>Xo(this.sessionsDir)),a=m=>{Lp(m)&&y0(m,o)&&s.add(m)},l=0,c=async(m,p)=>{if(e.signal.throwIfAborted(),i)return;let f=await pw(m,{withFileTypes:!0}).catch(()=>[]);f.sort((h,g)=>Te(h.name,g.name));for(let h of f){if(e.signal.throwIfAborted(),l+=1,l>this.maxDiscoveryTraversalVisits){i=!0;return}let g=fi(m,h.name);if(h.isDirectory()&&!h.isSymbolicLink()&&p<4){if(await c(g,p+1),i)return}else h.isFile()&&h.name===Pp&&Lp(g)&&a(await Op(g).catch(()=>Xo(g)))}};await c(this.sessionsDir,0);try{await this.unionIndex(a,e)}catch(m){_0(m)}let u=[...s].sort(Te);return{sources:(r===null?u:u.filter(m=>Te(m,r)>0)).slice(0,n).map(m=>({provider:Nr,sessionid:hw(m),source_id:m})),truncated:i}}async unionIndex(e,n){let r=await fw(this.indexPath).catch(()=>null);if(!r?.isFile()||r.size>o0)return;let s=await r0(this.indexPath,{signal:n.signal});for(let i of s.toString("utf8").split(`
|
|
521
|
-
`)){if(n.signal.throwIfAborted(),!i.trim())continue;let o;try{o=
|
|
517
|
+
`);let h=MM(f);h!==null&&c.set(d,h)}return{revision:`${jo}+${ac}:sha256:${i.digest("hex")}`,generations:o,timestamps:c}}function FM(t){return t.generations.map(e=>({response_id:e.requestId,timestamp:e.lastStepIndex===null?null:t.timestamps.get(e.lastStepIndex)??null,model:e.model,tokens:e.tokens,files_read:null,files_written:null,external_io:null,read_bytes:null,write_bytes:null,model_provider:null,pricing_facts:vn({reasoning:e.thinkingOutputTokens},e.tokens.output,e.tokens.input_cache_write)}))}function Wb(t={}){return new Bo(t)}var xr,ac,CM,Bo,Sp=L(()=>{"use strict";Yn();xr="agy",ac="agy-tokens-v1",CM=RM(import.meta.url);Bo=class{conversationsDir;sqliteBusyTimeoutMs;constructor(e={}){this.conversationsDir=Bb(e.agyConversationsDir??Ub(OM(),".gemini","antigravity-cli","conversations")),this.sqliteBusyTimeoutMs=e.sqliteBusyTimeoutMs??5e3}async discover(e,n,r=null){_e(e);let s=await xM(this.conversationsDir,{withFileTypes:!0}).catch(()=>[]),i=[];for(let o of s){if(e.signal.throwIfAborted(),!o.isFile()||o.isSymbolicLink()||!o.name.endsWith(".db"))continue;let a=await IM(Ub(this.conversationsDir,o.name)).catch(()=>null);a!==null&&(r!==null&&Te(a,r)<=0||i.push(a))}return i.sort(Te),{sources:i.slice(0,n).map(o=>({provider:xr,sessionid:jb(o,".db"),source_id:o})),truncated:!1}}async open(e){let n=await Ye(e.source_id,[this.conversationsDir]);if(n===null||jb(n,".db")!==e.sessionid||Bb(AM(n))!==this.conversationsDir)return null;try{let r=new(NM())(n,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.sqliteBusyTimeoutMs}`),r}catch{return null}}async inspect(e,n){if(_e(n),e.provider!==xr)return{status:"unsupported"};let r=await this.open(e);if(r===null)return{status:"unavailable"};try{let s=Hb(r,n);return s?{status:"ready",revision:s.revision}:{status:"partial"}}catch{return{status:"unsupported"}}finally{r.close()}}async read(e,n,r){if(_e(r),e.provider!==xr)return{status:"unsupported"};let s=await this.open(e);if(s===null)return{status:"unavailable"};try{s.exec("BEGIN");let i=Hb(s,r);if(i===null||i.revision!==n)return s.exec("ROLLBACK"),{status:"partial"};let o=FM(i);return s.exec("COMMIT"),{status:"complete",source:e,revision:n,checkpoint:n,responses:o}}catch{try{s.exec("ROLLBACK")}catch{}return{status:"unsupported"}}finally{s.close()}}}});import $M from"node:zlib";function JM(t,e){return t[e]===UM&&t[e+1]===BM&&t[e+2]===HM&&t[e+3]===WM}function qb(t,e){return(t[e]&240)===80&&t[e+1]===qM&&t[e+2]===XM&&t[e+3]===GM}function VM(t,e){if(qb(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!JM(t,e))return;let n=e+4;if(n+1>t.length)return;let r=t[n];n+=1;let s=r>>6,i=(r&32)!==0,o=(r&4)!==0,a=r&3;i||(n+=1),n+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(n+=l,!(n>t.length)){for(;;){if(n+3>t.length)return;let c=t[n]|t[n+1]<<8|t[n+2]<<16,u=(c&1)!==0,d=c>>1&3,m=c>>3;if(n+=3,d===3||(n+=d===1?1:m,n>t.length))return;if(u)break}if(o&&(n+=4),!(n>t.length))return n-e}}function Ho(t){let e=[],n=0;for(;n+4<=t.length;){let r=VM(t,n);if(r===void 0||r<=0)break;e.push(t.subarray(n,n+r)),n+=r}return e}function lc(t){let e=[];for(let n of Ho(t))qb(n,0)||e.push(jM(n).toString("utf8"));return e.join("")}var jM,UM,BM,HM,WM,qM,XM,GM,cc=L(()=>{"use strict";jM=$M.zstdDecompressSync,UM=40,BM=181,HM=47,WM=253,qM=42,XM=77,GM=24});import{readdir as KM,realpath as zM}from"node:fs/promises";import{basename as kp,dirname as Xb,join as Vb,resolve as Kb}from"node:path";import YM from"node:zlib";function zb(t){return/^session(\.v\d+)?\.jsonl\.zstd$/.test(t)}function rP(t){return nP.has(t)||kr(t)}function sP(){return process.env.HOME||process.env.USERPROFILE||""}function iP(t){if(typeof t=="string")return Buffer.byteLength(t,"utf8");if(!Array.isArray(t))return null;let e=0,n=!1;for(let r of t){let s=K(r);s?.type==="text"&&typeof s.text=="string"&&(e+=Buffer.byteLength(s.text,"utf8"),n=!0)}return n?e:null}function Gb(t){if(!t)return null;let e=re(t.inputTokens),n=re(t.outputTokens);if(e===null||n===null)return null;let r=t.cacheReadTokens===void 0?null:re(t.cacheReadTokens);return{input_uncached:e,input_cached:r,input_cache_write:null,output:n}}function oP(t){return t.length>=4&&(t[0]&240)===80&&t[1]===42&&t[2]===77&&t[3]===24}function aP(t,e){let n=Ho(t),r=0;for(let o of n)r+=o.length;if(r!==t.length)return{text:"",truncated:!0};let s=[],i=0;for(let o of n){if(e.signal.throwIfAborted(),oP(o))continue;if(o.length>e.maxBytes)return{text:s.join(""),truncated:!0};let a;try{a=QM(o)}catch{return{text:s.join(""),truncated:!0}}if(i+=a.length,i>e.maxBytes)return{text:s.join(""),truncated:!0};s.push(a.toString("utf8"))}return{text:s.join(""),truncated:!1}}function lP(t){let e=[];for(let n of t.split(`
|
|
518
|
+
`)){if(!n.trim())continue;let r;try{r=JSON.parse(n)}catch{continue}let s=typeof r.type=="string"?r.type:"";s.endsWith("-chunks")||s==="assistant/chunk"&&K(K(r.data)?.chunk)?.type!=="usage"||e.push(r)}return e}function cP(t){if(typeof t=="string")try{return K(JSON.parse(t))}catch{return null}return K(t)}function Jb(t,e){return typeof t!="number"||typeof e!="number"?null:`${t}\0${e}`}function uP(t,e,n,r){let s=new Map,i=[],o=new Set,a=new Map,l=null,c=null,u=null;for(let m of t){r.signal.throwIfAborted();let p=K(m.data);if(m.type==="assistant/chunk"){let f=K(p?.chunk),h=K(f?.usage),g=Jb(p?.turn,p?.step);h&&g!==null&&typeof p?.turn=="number"&&typeof p?.step=="number"&&a.set(g,{turn:p.turn,step:p.step,usage:h,time:m.time});continue}if(m.type==="request/header"){let f=K(K(p?.header)?.config);typeof f?.provider=="string"&&f.provider&&(l=f.provider),typeof f?.model=="string"&&f.model&&(c=f.model);continue}if(m.type==="user/message"){if(K(p?.source)?.kind!=="user")continue;let h=typeof p?.id=="string"&&p.id?p.id:null;i.push({id:h,bytes:iP(p?.content)});continue}if(m.type==="assistant/message"){let f=K(p?.message),h=K(f?.source),g=typeof f?.id=="string"&&f.id?f.id:null,y=Jb(p?.turn,p?.step),b;if(y!==null)o.add(y),b=`dsh:turn-step:${p.turn}/${p.step}`;else{if(K(p?.usage))return{status:"partial"};b=g}if(b===null)return{status:"partial"};let _=Gb(K(p?.usage)),v=s.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Bt(typeof m.time=="number"?m.time:null),model:(typeof h?.model=="string"&&h.model?h.model:null)??c,tokens:_??{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,reasoning:null,provider:typeof h?.provider=="string"&&h.provider?h.provider:null},s.set(b,v),s.size>r.maxRows)return{status:"partial"};for(let E of i)v.io.record({direction:"read",kind:"prompt",id:E.id,ref:null,bytes:E.bytes,basis:E.bytes===null?"unknown":"input_text"});i.length=0}if(_){v.meta.tokens=_;let E=re(K(p?.usage)?.reasoningTokens);E!==null&&(v.reasoning=E)}u=b;continue}if(m.type==="tool/call"){let f=u!==null?s.get(u):void 0;if(!f)continue;let h=typeof p?.callId=="string"&&p.callId?p.callId:null,g=typeof p?.name=="string"?p.name.toLowerCase():"",y=cP(p?.arguments),b=(typeof y?.file_path=="string"&&y.file_path?y.file_path:null)??(typeof y?.path=="string"&&y.path?y.path:null);eP.has(g)?b!==null?f.obs.record(h??"","read",b,null):$e(f.io,h):tP.has(g)?b!==null?f.obs.record(h??"","written",b,ui(y)):$e(f.io,h):rP(g)||$e(f.io,h);continue}}for(let[m,{turn:p,step:f,usage:h,time:g}]of a){if(o.has(m))continue;r.signal.throwIfAborted();let y=Gb(h),b=new Ut;$e(b,null);let _={meta:{response_id:`dsh:turn-step:${p}/${f}`,timestamp:Bt(typeof g=="number"?g:null),model:c,tokens:y??{...xt},files_read:[],files_written:[]},obs:new jt,io:b,reasoning:re(h.reasoningTokens),provider:l};if(s.set(_.meta.response_id,_),s.size>r.maxRows)return{status:"partial"}}let d=[];for(let{meta:m,obs:p,io:f,reasoning:h,provider:g}of s.values()){let y=p.files("read"),b=p.files("written"),_=f.entries();d.push({...m,files_read:y,files_written:b,external_io:_,read_bytes:_t(y,_,"read"),write_bytes:_t(b,_,"written"),model_provider:l??g,pricing_facts:vn({reasoning:h??void 0},m.tokens.output,m.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:d}}async function dP(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c,u){r.signal.throwIfAborted();let d=await KM(c,{withFileTypes:!0}).catch(()=>[]);d.sort((m,p)=>Te(m.name,p.name));for(let m of d){if(r.signal.throwIfAborted(),i.length>=e)return;if(o+=1,o>n){a=!0;return}let p=Vb(c,m.name);if(m.isDirectory()&&!m.isSymbolicLink()&&u<2){if(await l(p,u+1),a||i.length>=e)return}else if(m.isFile()&&zb(m.name)){let f=await zM(p).catch(()=>Kb(p));(s===null||Te(f,s)>0)&&i.push(f)}}}return await l(t,0),{paths:i.sort(Te),truncated:a}}function Yb(t={}){return new Rp(t)}var Ir,QM,ZM,eP,tP,nP,Rp,Qb=L(()=>{"use strict";Yn();cc();Ir="dsh",QM=YM.zstdDecompressSync;ZM=5e5,eP=new Set(["read","read_image"]),tP=new Set(["write","edit"]),nP=new Set(["create_goal","get_goal","update_goal","todo_write","ask_user_question","exit_plan_mode","list_agents","interrupt_agent","job_list","job_kill","job_output"]);Rp=class{sessionsDir;maxDiscoveryTraversalVisits;constructor(e={}){let n=e.dshHome??process.env.DSH_HOME??Vb(sP(),".dsh");this.sessionsDir=Kb(n,"sessions"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):ZM}async discover(e,n,r=null){_e(e);let{paths:s,truncated:i}=await dP(this.sessionsDir,n,this.maxDiscoveryTraversalVisits,e,r);return{sources:s.map(o=>({provider:Ir,sessionid:kp(Xb(o)),source_id:o})),truncated:i}}matches(e,n){return zb(kp(n))&&kp(Xb(n))===e.sessionid}async inspect(e,n){if(_e(n),e.provider!==Ir)return{status:"unsupported"};let r=await Ye(e.source_id,[this.sessionsDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(_e(r),e.provider!==Ir)return{status:"unsupported"};let s=await Ye(e.source_id,[this.sessionsDir]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await It(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let{text:o,truncated:a}=aP(i.data,r);return a?{status:"partial"}:uP(lP(o),e,n,r)}}});import{readdir as mP,realpath as pP}from"node:fs/promises";import{basename as uc,dirname as fP,join as xp,resolve as Zb}from"node:path";function bP(){return process.env.HOME||process.env.USERPROFILE||""}function wP(){let t=bP();return[xp(t,".qwen","projects"),xp(t,".qwen.bk1","projects")]}function EP(t){return t.type!=="system"||t.subtype!=="ui_telemetry"?null:K(K(t.systemPayload)?.uiEvent)}function TP(t){let e=t["event.name"];return typeof e=="string"&&e.length>0?e:null}function SP(t){let e=re(t.input_token_count),n=re(t.output_token_count),r=re(t.cached_content_token_count),s=re(t.total_token_count);if(e===null||n===null||r===null||s===null||r>e||e+n!==s)return null;let i=t.thoughts_token_count===void 0?null:re(t.thoughts_token_count);return t.thoughts_token_count!==void 0&&(i===null||i>n)?null:{input_uncached:e-r,input_cached:r,input_cache_write:null,output:n}}function kP(t){let e=K(t)?.parts;if(!Array.isArray(e))return null;let n=0,r=!1;for(let s of e){let i=K(s);!i||i.thought===!0||typeof i.text=="string"&&(n+=Buffer.byteLength(i.text,"utf8"),r=!0)}return r?n:null}function RP(t){let e=new Map,n=new Set,r=new Map;for(let o of t){let a=typeof o.uuid=="string"&&o.uuid?o.uuid:null;if(a!==null&&(e.set(a,typeof o.parentUuid=="string"&&o.parentUuid?o.parentUuid:null),o.type==="user")){n.add(a);let l=kP(o.message);l!==null&&r.set(a,l)}}let s=new Map;return{promptBytes:r,resolve:o=>{let a=[],l=new Set,c=o,u;for(;;){let d=s.get(c);if(d){u=d;break}if(n.has(c)){u={kind:"found",uuid:c};break}if(!e.has(c)){u={kind:"broken"};break}if(l.has(c)){u={kind:"broken"};break}l.add(c),a.push(c);let m=e.get(c)??null;if(m===null){u={kind:"clean"};break}c=m}for(let d of a)s.set(d,u);return u}}}function xP(t,e,n,r){let{promptBytes:s,resolve:i}=RP(t),o=new Set,a=new Map,l=0;for(let u of t){r.signal.throwIfAborted();let d=EP(u);if(d===null)continue;let m=TP(d);if(m===gP){let b=typeof d.response_id=="string"&&d.response_id?d.response_id:null;if(b===null)return{status:"unsupported"};let _=SP(d);if(_===null)return{status:"partial"};let v=a.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Bt(d["event.timestamp"]??u.timestamp),model:typeof d.model=="string"&&d.model?d.model:null,tokens:{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,thoughts:null},a.set(b,v),a.size>r.maxRows)return{status:"partial"};let x=typeof u.uuid=="string"&&u.uuid?u.uuid:null,S=x===null?{kind:"broken"}:i(x);if(S.kind==="broken")v.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"});else if(S.kind==="found"&&!o.has(S.uuid)){o.add(S.uuid);let R=s.get(S.uuid)??null;v.io.record({direction:"read",kind:"prompt",id:S.uuid,ref:null,bytes:R,basis:R===null?"unknown":"input_text"})}}v.meta.tokens=_,typeof d.model=="string"&&d.model&&(v.meta.model=d.model);let E=re(d.thoughts_token_count);E!==null&&(v.thoughts=E);continue}if(m!==hP)continue;let p=typeof d.response_id=="string"&&d.response_id?d.response_id:null;if(p===null)continue;let f=a.get(p);if(f===void 0)return{status:"partial"};let h=typeof d.function_name=="string"?d.function_name.toLowerCase():"",g=K(d.function_args),y=`tool-${l++}`;if(yP.has(h)){let b=typeof g?.file_path=="string"?g.file_path:null;b!==null?f.obs.record(y,"read",b,null):$e(f.io,y)}else if(_P.has(h)){let b=typeof g?.file_path=="string"?g.file_path:null;b!==null?f.obs.record(y,"written",b,ui(g)):$e(f.io,y)}else kr(h)||$e(f.io,y)}let c=[];for(let{meta:u,obs:d,io:m,thoughts:p}of a.values()){let f=d.files("read"),h=d.files("written"),g=m.entries();c.push({...u,files_read:f,files_written:h,external_io:g,read_bytes:_t(f,g,"read"),write_bytes:_t(h,g,"written"),model_provider:null,pricing_facts:vn({reasoning:p??void 0},u.tokens.output,u.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:c}}async function IP(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c){r.signal.throwIfAborted();let u=await mP(c,{withFileTypes:!0}).catch(()=>[]);u.sort((d,m)=>Te(d.name,m.name));for(let d of u){if(r.signal.throwIfAborted(),i.length>=e)return;if(o+=1,o>n){a=!0;return}let m=xp(c,d.name);if(d.isDirectory()&&!d.isSymbolicLink()){if(await l(m),a||i.length>=e)return}else if(d.isFile()&&d.name.endsWith(".jsonl")&&uc(c)===ew){let p=await pP(m).catch(()=>Zb(m));(s===null||Te(p,s)>0)&&i.push(p)}}}return await l(t),{paths:i.sort(Te),truncated:a}}function AP(t,e){for(let n of t){let r=n.sessionId;if(typeof r=="string"&&r.length>0&&r!==e)return!1}return!0}function tw(t={}){return new Ip(t)}var Ar,gP,hP,ew,yP,_P,vP,Ip,nw=L(()=>{"use strict";Yn();Ar="qwen",gP="qwen-code.api_response",hP="qwen-code.tool_call",ew="chats",yP=new Set(["read_file"]),_P=new Set(["write_file"]),vP=5e5;Ip=class{roots;maxDiscoveryTraversalVisits;constructor(e={}){this.roots=(e.qwenProjectsDirs??wP()).map(n=>Zb(n)),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):vP}async discover(e,n,r=null){_e(e);let s=new Map,i=!1;for(let a of this.roots){e.signal.throwIfAborted();let l=await IP(a,n,this.maxDiscoveryTraversalVisits,e,r);l.truncated&&(i=!0);for(let c of l.paths)s.set(c,c)}return{sources:[...s.keys()].sort(Te).slice(0,n).map(a=>({provider:Ar,sessionid:uc(a,".jsonl"),source_id:a})),truncated:i}}matches(e,n){return uc(n,".jsonl")===e.sessionid&&uc(fP(n))===ew}async inspect(e,n){if(_e(n),e.provider!==Ar)return{status:"unsupported"};let r=await Ye(e.source_id,[...this.roots]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(_e(r),e.provider!==Ar)return{status:"unsupported"};let s=await Ye(e.source_id,[...this.roots]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await It(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let o=Zl(i.data,r);return o?AP(o,e.sessionid)?xP(o,e,n,r):{status:"unavailable"}:{status:"partial"}}}});import{createHash as CP}from"node:crypto";import{createRequire as NP}from"node:module";import{join as Wo,resolve as Ap}from"node:path";function LP(){return OP("node:sqlite").DatabaseSync}function rw(){return process.env.HOME||process.env.USERPROFILE||""}function MP(){let t=process.env.XDG_DATA_HOME||Wo(rw(),".local","share"),e=process.env.XDG_CONFIG_HOME||Wo(rw(),".config");return[Wo(t,"opencode","opencode.db"),Wo(t,"opencode","opencode-local.db"),Wo(e,"opencode","opencode.db")]}function jP(t){if(typeof t!="string")return null;let e=t.toLowerCase();return e==="apply_patch"?"apply_patch":PP.includes(e)?"read":DP.includes(e)?"written":null}function sw(t,e=FP){let n=K(t);if(!n)return null;for(let r of e){let s=n[r];if(typeof s=="string"&&s.length>0)return s;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.length>0)return i}}return null}function UP(t){let e=K(t);if(!e)return null;if(typeof e.content=="string")return Buffer.byteLength(e.content,"utf8");if(typeof e.newString=="string")return Buffer.byteLength(e.newString,"utf8");if(typeof e.new_string=="string")return Buffer.byteLength(e.new_string,"utf8");if(typeof e.newSource=="string")return Buffer.byteLength(e.newSource,"utf8");if(Array.isArray(e.edits)){let n=0;for(let r of e.edits){let s=K(r),i=s?.newString??s?.new_string;if(typeof i!="string")return null;n+=Buffer.byteLength(i,"utf8")}return n}return null}function BP(t){let e=new Map,n=null,r=()=>{n&&(e.set(n.path,(e.get(n.path)??0)+n.bytes),n=null)};for(let s of t.split(`
|
|
519
|
+
`)){let i=s.replace(/\r$/,""),o=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(i);if(o){r(),n={path:o[1].trim(),bytes:0};continue}let a=/^\*\*\* Move to: (.+)$/.exec(i);if(a){n&&(n.path=a[1].trim());continue}if(i.startsWith("*** ")){r();continue}n&&i.startsWith("+")&&(n.bytes+=Buffer.byteLength(i.slice(1),"utf8")+1)}return r(),[...e].map(([s,i])=>({path:s,bytes:i}))}function HP(t){if(typeof t!="string"||t.length===0)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:`${e.origin}${e.pathname}`}catch{return null}}function WP(t,e=!1){let n=K(t);if(!n)return{...xt};let r=n.input===void 0?e?null:0:re(n.input),s=n.output===void 0?e?null:0:re(n.output),i=n.reasoning===void 0?e?null:0:re(n.reasoning),o=K(n.cache),a=o?.read===void 0?e?null:0:re(o.read),l=o?.write===void 0?e?null:0:re(o.write);return e&&r===0&&s===0&&i===0&&a===0&&l===0?{...xt}:e?{input_uncached:r!==null&&l!==null&&Number.isSafeInteger(r+l)?r+l:null,input_cached:a,input_cache_write:l,output:s!==null&&i!==null&&Number.isSafeInteger(s+i)?s+i:null}:r===null||s===null||i===null||a===null||l===null?{...xt}:r+s+i+a+l===0?{...xt}:{input_uncached:r+l,input_cached:a,input_cache_write:l,output:s+i}}function iw(t,e,n){_e(n);let r=n.maxRows*20,s=t.prepare("SELECT (SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) FROM message WHERE session_id=?) + (SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) FROM part WHERE session_id=?) AS total").get(e,e),i=re(s?.total);if(i===null||i>n.maxBytes)return null;let o=t.prepare("SELECT id,time_created,time_updated,data FROM message WHERE session_id=? ORDER BY time_created,id LIMIT ?").all(e,r+1),a=t.prepare("SELECT id,message_id,time_created,time_updated,data FROM part WHERE session_id=? ORDER BY time_created,id LIMIT ?").all(e,r+1);if(o.length+a.length>r)return null;let l=0,c=CP("sha256");for(let u of[...o,...a]){n.signal.throwIfAborted();let d=JSON.stringify(u);if(l+=Buffer.byteLength(d),l>n.maxBytes)return null;c.update(d).update(`
|
|
520
|
+
`)}return{revision:`${jo}:sha256:${c.digest("hex")}`,messages:o,parts:a}}function qP(t){let e=0,n=!1,r=!1;for(let s of t){let i;try{i=K(JSON.parse(s.data))}catch{continue}let o=typeof i?.type=="string"?i.type:"";i?.synthetic===!0||i?.ignored===!0||(o==="text"&&typeof i.text=="string"?(e+=Buffer.byteLength(i.text,"utf8"),n=!0):o&&!$P.has(o)&&(r=!0))}return n?e:r?"unknown":null}function XP(t,e,n,r){let s=new Map;for(let c of n.parts){let u=s.get(c.message_id)??[];u.push(c),s.set(c.message_id,u)}let i=new Map;for(let c of n.messages){let u;try{u=K(JSON.parse(c.data))}catch{continue}if(u?.role!=="user")continue;let d=qP(s.get(c.id)??[]);d==="unknown"?i.set(c.id,null):d!==null&&i.set(c.id,d)}let o=new Map,a=new Set;for(let c of n.messages){let u;try{u=K(JSON.parse(c.data))}catch{continue}if(u?.role!=="assistant")continue;let d=typeof u.parentID=="string"?u.parentID:null;d!==null&&i.has(d)&&!a.has(d)&&(a.add(d),o.set(c.id,{id:d,bytes:i.get(d)}))}let l=[];for(let c of n.messages){r.signal.throwIfAborted();let u;try{u=K(JSON.parse(c.data))}catch{return{status:"partial"}}if(r.requireBillingCounters&&u&&Object.hasOwn(u,"tokens")&&u.role!=="assistant")return{status:"partial"};if(!u||u.role!=="assistant")continue;let d=new jt,m=new Ut,p=0,f=o.get(c.id);f&&m.record({direction:"read",kind:"prompt",id:f.id,ref:null,bytes:f.bytes,basis:f.bytes===null?"unknown":"input_text"});for(let S of s.get(c.id)??[]){let R;try{R=K(JSON.parse(S.data))}catch{return{status:"partial"}}if(R?.type!=="tool")continue;let N=typeof R.tool=="string"?R.tool.toLowerCase():"",O=jP(R.tool),A=K(R.state),w=K(A?.input),T=typeof R.callID=="string"&&R.callID?R.callID:typeof A?.callID=="string"&&A.callID?A.callID:S.id;if(O==="written")d.record(T,"written",sw(w),UP(w));else if(O==="apply_patch"){let k=w?.patchText;if(typeof k=="string")for(let I of BP(k))d.record(T,"written",I.path,I.bytes);else $e(m,T)}else if(O==="read"){let k=sw(w,["filePath","path","file","file_path"]);if(k===null)continue;let I=null;if(A?.status==="completed"){let C=K(K(A.metadata)?.display);C?.type==="file"&&typeof C.text=="string"&&(I=Buffer.byteLength(C.text,"utf8"))}d.record(T,"read",k,I)}else if(N==="webfetch"){p+=1;let k=A?.status==="completed"?A.output:void 0;m.record({direction:"read",kind:"web",id:T,ref:HP(w?.url),bytes:typeof k=="string"?Buffer.byteLength(k,"utf8"):null,basis:typeof k=="string"?"normalized_content":"unknown"})}else kr(R.tool)||$e(m,T)}let h=K(u.time),g=K(u.model)?.modelID??u.modelID,y=WP(u.tokens,r.requireBillingCounters),b=K(u.tokens),_=d.files("read"),v=d.files("written"),E=m.entries(),x=vn({reasoning:b?.reasoning,webFetch:p>0?p:void 0},y.output,y.input_cache_write);if(l.push({response_id:c.id,timestamp:Bt(h?.created??c.time_created),model:typeof g=="string"&&g?g:null,tokens:y,files_read:_,files_written:v,external_io:E,read_bytes:_t(_,E,"read"),write_bytes:_t(v,E,"written"),model_provider:typeof u.providerID=="string"&&u.providerID?u.providerID:null,pricing_facts:x}),l.length>r.maxRows)return{status:"partial"}}return{status:"complete",source:t,revision:e,checkpoint:e,responses:l}}function ow(t={}){return new qo(t)}var Ts,OP,PP,DP,FP,$P,qo,Cp=L(()=>{"use strict";Yn();Ts="opencode",OP=NP(import.meta.url);PP=["read","read_file","view","view_file","view_image"],DP=["write","write_file","edit","edit_file","multiedit","notebookedit","notebook_edit"],FP=["filePath","path","file","file_path","filepath","notebook_path","paths"],$P=new Set(["session-job-notification"]);qo=class{dbPaths;sqliteBusyTimeoutMs;constructor(e={}){this.dbPaths=(e.dbPaths??MP()).map(n=>Ap(n)),this.sqliteBusyTimeoutMs=e.sqliteBusyTimeoutMs??5e3}openDb(e){if(!this.dbPaths.includes(Ap(e)))return null;try{let n=new(LP())(e,{open:!0,readOnly:!0});return n.exec(`PRAGMA busy_timeout = ${this.sqliteBusyTimeoutMs}`),n}catch{return null}}async discover(e,n,r=null){_e(e);let s=new Map;for(let o of this.dbPaths){e.signal.throwIfAborted();let a=await Ye(o,[Ap(o,"..")]);if(!a||r&&Te(a,r.source_id)<0)continue;let l=this.openDb(a);if(l)try{let c=r?.source_id===a?r.sessionid:"",u=l.prepare("SELECT id FROM session WHERE id > ? ORDER BY id LIMIT ?").all(c,n);for(let d of u)typeof d.id=="string"&&d.id&&!s.has(d.id)&&s.set(d.id,{provider:Ts,sessionid:d.id,source_id:a})}catch{}finally{l.close()}}return{sources:[...s.values()].sort((o,a)=>Te(`${o.source_id}\0${o.sessionid}`,`${a.source_id}\0${a.sessionid}`)).slice(0,n),truncated:!1}}inspect(e,n){if(_e(n),e.provider!==Ts)return{status:"unsupported"};let r=this.openDb(e.source_id);if(!r)return{status:"unavailable"};try{if(r.prepare("SELECT id FROM session WHERE id=?").get(e.sessionid)?.id!==e.sessionid)return{status:"unavailable"};let i=iw(r,e.sessionid,n);return i?{status:"ready",revision:i.revision}:{status:"partial"}}catch{return{status:"unsupported"}}finally{r.close()}}read(e,n,r){if(_e(r),e.provider!==Ts)return{status:"unsupported"};let s=this.openDb(e.source_id);if(!s)return{status:"unavailable"};try{if(s.exec("BEGIN"),s.prepare("SELECT id FROM session WHERE id=?").get(e.sessionid)?.id!==e.sessionid)return s.exec("ROLLBACK"),{status:"unavailable"};let o=iw(s,e.sessionid,r);if(!o||o.revision!==n)return s.exec("ROLLBACK"),{status:"partial"};let a=XP(e,n,o,r);return s.exec("COMMIT"),a}catch{try{s.exec("ROLLBACK")}catch{}return{status:"unsupported"}}finally{s.close()}}}});import{readdir as GP,realpath as JP,stat as VP}from"node:fs/promises";import{basename as aw,dirname as KP,join as lw,resolve as cw}from"node:path";function QP(t){let e=new Map,n=null,r=()=>{n&&(e.set(n.path,(e.get(n.path)??0)+n.bytes),n=null)};for(let s of t.split(`
|
|
521
|
+
`)){let i=s.replace(/\r$/,""),o=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(i);if(o){r(),n={path:o[1].trim(),bytes:0};continue}let a=/^\*\*\* Move to: (.+)$/.exec(i);if(a){n&&(n.path=a[1].trim());continue}if(i.startsWith("*** ")){r();continue}n&&i.startsWith("+")&&(n.bytes+=Buffer.byteLength(i.slice(1),"utf8")+1)}return r(),[...e].map(([s,i])=>({path:s,bytes:i}))}function ZP(t){let e=t?.content;return typeof e=="string"?Buffer.byteLength(e,"utf8"):null}function e0(t,e,n){let r=K(t);if(!r)return{entry:null,incomplete:t!=null};let s=[],i=!1;for(let[a,l]of Object.entries(r)){let c=K(l);if(!c){i=!0;continue}let u=K(c.usage),d=K(c.requests),m=K(c.tokenDetails),p=K(m?.input);s.push({model:a,requests_count:d?re(d.count):null,input_tokens:u?re(u.inputTokens):null,input_other_tokens:p?re(p.tokenCount):null,cache_read_tokens:u?re(u.cacheReadTokens):null,cache_write_tokens:u?re(u.cacheWriteTokens):null,output_tokens:u?re(u.outputTokens):null,reasoning_tokens:u?re(u.reasoningTokens):null})}s.sort((a,l)=>Te(a.model,l.model));let o=i||s.length>0;return e===null?{entry:null,incomplete:o}:{entry:{native_id:e,recorded_at:n,kind:"copilot_session_shutdown",semantics:"reported_scope_unknown",models:s},incomplete:i}}function t0(t,e,n,r){let s=new Map;for(let d of t){if(d.type!=="user.message")continue;let m=K(d.data),p=typeof m?.interactionId=="string"?m.interactionId:null;if(p===null)continue;let f=ZP(m);s.has(p)?s.get(p)===null&&f!==null&&s.set(p,f):s.set(p,f)}let i=new Map,o=new Set,a=new Map,l=!1,c=1e3;for(let d of t){if(r.signal.throwIfAborted(),d.type==="session.shutdown"){let y=typeof d.id=="string"&&d.id?d.id:null,b=Bt(d.timestamp),{entry:_,incomplete:v}=e0(K(d.data)?.modelMetrics,y,b);if(v&&(l=!0),_){let E=a.get(_.native_id);if(E&&JSON.stringify(E)!==JSON.stringify(_))l=!0;else if(a.set(_.native_id,_),a.size>c)return{snapshot:{status:"partial"},sessionUsage:null}}continue}if(d.type!=="assistant.message")continue;let m=K(d.data);if(!m)continue;let p=typeof m.messageId=="string"&&m.messageId?m.messageId:typeof d.id=="string"&&d.id?d.id:null;if(p===null)continue;let f=typeof m.interactionId=="string"?m.interactionId:null,h=i.get(p);if(!h){if(h={meta:{response_id:p,timestamp:Bt(d.timestamp),model:typeof m.model=="string"&&m.model?m.model:null,tokens:{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,promptRecorded:!1},i.set(p,h),i.size>r.maxRows)return{snapshot:{status:"partial"},sessionUsage:null};if(f!==null&&s.has(f)){if(!o.has(f)){o.add(f);let y=s.get(f);h.io.record({direction:"read",kind:"prompt",id:f,ref:null,bytes:y,basis:y===null?"unknown":"input_text"}),h.promptRecorded=!0}}else h.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"})}let g=re(m.outputTokens);if(g!==null&&(h.meta.tokens.output=(h.meta.tokens.output??0)+g),h.meta.model===null&&typeof m.model=="string"&&m.model&&(h.meta.model=m.model),Array.isArray(m.toolRequests))for(let y of m.toolRequests){let b=K(y);if(!b)continue;let _=typeof b.name=="string"?b.name.toLowerCase():"",v=typeof b.toolCallId=="string"&&b.toolCallId?b.toolCallId:null,E=b.arguments;if(_==="create"){let x=K(E),S=typeof x?.path=="string"?x.path:null,R=typeof x?.file_text=="string"?Buffer.byteLength(x.file_text,"utf8"):null;S!==null?h.obs.record(v??p,"written",S,R):$e(h.io,v)}else if(_==="apply_patch")if(typeof E=="string"){let x=QP(E);if(x.length>0)for(let S of x)h.obs.record(v??p,"written",S.path,S.bytes);else $e(h.io,v)}else $e(h.io,v);else if(YP.has(_)){let x=K(E),S=typeof x?.path=="string"?x.path:null;S!==null?h.obs.record(v??p,"read",S,null):$e(h.io,v)}else zP.has(_)||$e(h.io,v)}}let u=[];for(let{meta:d,obs:m,io:p}of i.values()){let f=m.files("read"),h=m.files("written"),g=p.entries();u.push({...d,files_read:f,files_written:h,external_io:g,read_bytes:_t(f,g,"read"),write_bytes:_t(h,g,"written"),model_provider:null,pricing_facts:null})}return l?{snapshot:{status:"partial"},sessionUsage:null}:{snapshot:{status:"complete",source:e,revision:n,checkpoint:n,responses:u},sessionUsage:a.size>0?[...a.values()]:null}}function n0(){return process.env.HOME||process.env.USERPROFILE||""}function dw(t={}){return new Np(t)}var Cr,uw,zP,YP,Np,mw=L(()=>{"use strict";Yn();Cr="copilot",uw="events.jsonl",zP=new Set(["report_intent"]),YP=new Set(["view"]);Np=class{sessionStateDir;constructor(e={}){this.sessionStateDir=cw(e.copilotSessionStateDir??lw(n0(),".copilot","session-state"))}async discover(e,n,r=null){_e(e);let s;try{s=await GP(this.sessionStateDir)}catch{return{sources:[],truncated:!1}}let i=[];for(let o of s.sort(Te)){e.signal.throwIfAborted();let a=lw(this.sessionStateDir,o,uw);if(!(await VP(a).catch(()=>null))?.isFile())continue;let c=await JP(a).catch(()=>cw(a)),u={provider:Cr,sessionid:o,source_id:c};r!==null&&Te(`${c}\0${o}`,r)<=0||i.push(u)}return i.sort((o,a)=>Te(`${o.source_id}\0${o.sessionid}`,`${a.source_id}\0${a.sessionid}`)),{sources:i.slice(0,n),truncated:!1}}matches(e,n){return aw(n)===uw&&aw(KP(n))===e.sessionid}async inspect(e,n){if(_e(n),e.provider!==Cr)return{status:"unsupported"};let r=await Ye(e.source_id,[this.sessionStateDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){return(await this.readWithUsage(e,n,r)).snapshot}async readWithUsage(e,n,r){if(_e(r),e.provider!==Cr)return{snapshot:{status:"unsupported"},sessionUsage:null};let s=await Ye(e.source_id,[this.sessionStateDir]);if(!s||!this.matches(e,s))return{snapshot:{status:"unavailable"},sessionUsage:null};let i=await It(s,r).catch(()=>null);if(!i||i.revision!==n)return{snapshot:{status:"partial"},sessionUsage:null};let o=Zl(i.data,r);return o?t0(o,e,n,r):{snapshot:{status:"partial"},sessionUsage:null}}}});import{readdir as pw,readFile as r0,realpath as Op,stat as fw}from"node:fs/promises";import{basename as Go,dirname as gi,isAbsolute as Mp,join as fi,relative as yw,resolve as Xo,sep as _w}from"node:path";function u0(t){return c0.has(t)||kr(t)}function d0(){return process.env.HOME||process.env.USERPROFILE||""}function m0(t,e){if(t.length>0&&t[t.length-1]!==10)return null;let n=[],r=0;for(;r<t.length;){e.signal.throwIfAborted();let s=t.indexOf(10,r);s===-1&&(s=t.length);let i=t.toString("utf8",r,s);if(r=s+1,!!i.trim())try{let o=K(JSON.parse(i));if(!o)return null;n.push(o)}catch{return null}}return n}function gw(t){let e=K(t);if(!e)return null;let n=re(e.inputOther),r=re(e.inputCacheRead),s=re(e.inputCacheCreation),i=re(e.output);return n===null||r===null||s===null||i===null?null:{input_uncached:n+s,input_cached:r,input_cache_write:s,output:i}}function p0(t){if(!Array.isArray(t))return null;let e=0,n=!1;for(let r of t){let s=K(r);s?.type==="text"&&typeof s.text=="string"&&(e+=Buffer.byteLength(s.text,"utf8"),n=!0)}return n?e:null}function g0(t,e,n,r){let s=t.find(b=>b.type==="metadata"),i=s&&typeof s.protocol_version=="string"?s.protocol_version:null;if(i!==null&&!s0.has(i))return{status:"unsupported"};let o=h0(e.source_id),a=new Map,l=new Map,c=[],u=new Set,d=new Set,m=null,p=!1,f=b=>`${o}/${b}`,h=(b,_)=>{let v=f(b),E=a.get(v);return E||(E={meta:{response_id:v,timestamp:Bt(typeof _=="number"?_:null),model:null,tokens:{...xt},files_read:[],files_written:[]},obs:new jt,io:new Ut,turnStepKey:null,tokensSource:"none"},a.set(v,E)),E},g=(b,_)=>{if(b.turnStepKey!==null)return;let v=_.turnId===void 0?null:String(_.turnId),E=_.step===void 0?null:String(_.step);v!==null&&E!==null&&(b.turnStepKey=`${v}.${E}`)};for(let b of t){if(r.signal.throwIfAborted(),b.type==="turn.prompt"){let v=K(b.origin),E=typeof v?.kind=="string"?v.kind:null,x=typeof b.promptId=="string"&&b.promptId?b.promptId:null;if(E!==null&&f0.has(E))continue;if(x!==null){if(u.has(x))continue;u.add(x)}E==="user"?c.push({bytes:p0(b.input),id:x}):c.push({bytes:null,id:x});continue}if(b.type==="usage.record"){if(d.size>1){p=!0;continue}if(d.size===0){m===null&&(p=!0);continue}let[v]=d,E=a.get(f(v));if(!E){p=!0;continue}if(E.tokensSource==="record"){p=!0;continue}let x=gw(b.usage);x&&(E.meta.tokens=x,E.tokensSource="record");continue}if(b.type==="llm.request"){let v=typeof b.turnStep=="string"?b.turnStep:null,E=(typeof b.modelAlias=="string"&&b.modelAlias?b.modelAlias:null)??(typeof b.model=="string"&&b.model?b.model:null);v!==null&&E!==null&&(l.has(v)?l.get(v)!==E&&l.set(v,null):l.set(v,E));continue}if(b.type!=="context.append_loop_event")continue;let _=K(b.event);if(_){if(_.type==="step.begin"){let v=typeof _.uuid=="string"&&_.uuid?_.uuid:null;if(v===null)continue;let E=h(v,b.time);if(a.size>r.maxRows)return{status:"partial"};if(d.add(v),g(E,_),c.length>0){for(let x of c)E.io.record({direction:"read",kind:"prompt",id:x.id,ref:null,bytes:x.bytes,basis:x.bytes===null?"unknown":"input_text"});c.length=0}continue}if(_.type==="step.end"){let v=typeof _.uuid=="string"&&_.uuid?_.uuid:null;if(v===null)continue;let E=h(v,b.time);if(a.size>r.maxRows)return{status:"partial"};d.delete(v),m=v,g(E,_);let x=gw(_.usage);x&&(E.meta.tokens=x),E.tokensSource="end",E.meta.timestamp===null&&(E.meta.timestamp=Bt(typeof b.time=="number"?b.time:null));continue}if(_.type==="tool.call"){let v=typeof _.stepUuid=="string"&&_.stepUuid?_.stepUuid:null;if(v===null)continue;let E=h(v,b.time);if(a.size>r.maxRows)return{status:"partial"};let x=typeof _.name=="string"?_.name.toLowerCase():"",S=typeof _.toolCallId=="string"&&_.toolCallId?_.toolCallId:null,R=K(_.args),N=typeof R?.path=="string"&&R.path?R.path:typeof R?.file_path=="string"&&R.file_path?R.file_path:null;a0.has(x)?N!==null?E.obs.record(S??"","read",N,null):$e(E.io,S):l0.has(x)?N!==null?E.obs.record(S??"","written",N,ui(R)):$e(E.io,S):u0(x)||$e(E.io,S);continue}}}let y=[];for(let{meta:b,obs:_,io:v,turnStepKey:E}of a.values()){b.model===null&&E!==null&&(b.model=l.get(E)??null);let x=_.files("read"),S=_.files("written"),R=v.entries();y.push({...b,files_read:x,files_written:S,external_io:R,read_bytes:_t(x,R,"read"),write_bytes:_t(S,R,"written"),model_provider:null,pricing_facts:vn({},b.tokens.output,b.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:y,...p?{capture_status:"partial"}:{}}}function Lp(t){return Go(t)===Pp&&Go(gi(gi(t)))===vw}function hw(t){return Go(gi(gi(gi(t))))}function h0(t){return Go(gi(t))}function y0(t,e){let n=yw(e,t);return n===""||!n.startsWith(`..${_w}`)&&n!==".."&&!Mp(n)}function _0(t){if(t instanceof Error&&t.name==="AbortError")throw t}function bw(t={}){return new Jo(t)}var Nr,Pp,vw,s0,i0,o0,a0,l0,c0,f0,Jo,Dp=L(()=>{"use strict";Yn();Nr="kimi",Pp="wire.jsonl",vw="agents",s0=new Set(["1.4","1.5"]),i0=5e5,o0=8*1024*1024,a0=new Set(["read"]),l0=new Set(["write","edit"]),c0=new Set(["todolist","tasklist","taskoutput","taskstop","waitfor","creategoal","updategoal","getgoal","enterplanmode","exitplanmode","agentswarm","agent","skill","croncreate","crondelete","cronlist"]);f0=new Set(["system_trigger","cron_job","task"]);Jo=class{home;sessionsDir;indexPath;maxDiscoveryTraversalVisits;constructor(e={}){this.home=Xo(e.kimiHome??process.env.KIMI_CODE_HOME??fi(d0(),".kimi-code")),this.sessionsDir=fi(this.home,"sessions"),this.indexPath=fi(this.home,"session_index.jsonl"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):i0}async discover(e,n,r=null){_e(e);let s=new Set,i=!1,o=await Op(this.sessionsDir).catch(()=>Xo(this.sessionsDir)),a=m=>{Lp(m)&&y0(m,o)&&s.add(m)},l=0,c=async(m,p)=>{if(e.signal.throwIfAborted(),i)return;let f=await pw(m,{withFileTypes:!0}).catch(()=>[]);f.sort((h,g)=>Te(h.name,g.name));for(let h of f){if(e.signal.throwIfAborted(),l+=1,l>this.maxDiscoveryTraversalVisits){i=!0;return}let g=fi(m,h.name);if(h.isDirectory()&&!h.isSymbolicLink()&&p<4){if(await c(g,p+1),i)return}else h.isFile()&&h.name===Pp&&Lp(g)&&a(await Op(g).catch(()=>Xo(g)))}};await c(this.sessionsDir,0);try{await this.unionIndex(a,e)}catch(m){_0(m)}let u=[...s].sort(Te);return{sources:(r===null?u:u.filter(m=>Te(m,r)>0)).slice(0,n).map(m=>({provider:Nr,sessionid:hw(m),source_id:m})),truncated:i}}async unionIndex(e,n){let r=await fw(this.indexPath).catch(()=>null);if(!r?.isFile()||r.size>o0)return;let s=await r0(this.indexPath,{signal:n.signal});for(let i of s.toString("utf8").split(`
|
|
522
|
+
`)){if(n.signal.throwIfAborted(),!i.trim())continue;let o;try{o=K(JSON.parse(i))}catch{continue}let a=typeof o?.sessionId=="string"?o.sessionId:null,l=typeof o?.sessionDir=="string"?o.sessionDir:null;if(!a||!l||!Mp(l)||Go(l)!==a)continue;let c=yw(this.sessionsDir,Xo(l));if(c.startsWith(`..${_w}`)||c===".."||Mp(c))continue;let u=fi(l,vw),d=await pw(u,{withFileTypes:!0}).catch(()=>[]);for(let m of d){if(!m.isDirectory())continue;let p=fi(u,m.name,Pp);(await fw(p).catch(()=>null))?.isFile()&&e(await Op(p).catch(()=>Xo(p)))}}}matches(e,n){return Lp(n)&&hw(n)===e.sessionid}async inspect(e,n){if(_e(n),e.provider!==Nr)return{status:"unsupported"};let r=await Ye(e.source_id,[this.sessionsDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await It(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(_e(r),e.provider!==Nr)return{status:"unsupported"};let s=await Ye(e.source_id,[this.sessionsDir]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await It(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let o=m0(i.data,r);return o?g0(o,e,n,r):{status:"partial"}}}});import{createHash as Hp}from"node:crypto";import{createRequire as v0}from"node:module";import{lstat as b0,readFile as w0,readdir as E0,realpath as Up,stat as ww}from"node:fs/promises";import{basename as dc,dirname as T0,isAbsolute as Ew,join as Ss,relative as S0,resolve as Qn,sep as k0}from"node:path";function Wp(t){return typeof t=="string"&&x0.has(t.toLowerCase())}function zo(t,e){t.record({direction:"read",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"}),t.record({direction:"write",kind:"unattributed",id:e,ref:null,bytes:null,basis:"unknown"})}function Iw(t){if(typeof t!="string"||t.length===0)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:`${e.origin}${e.pathname}`}catch{return null}}function _i(t,e,n){if(t===null)return null;let r=n==="written"?"write":"read",s=0;for(let i of t){if(i.bytes===null)return null;s+=i.bytes}for(let i of e)if(i.direction===r){if(i.bytes===null)return null;s+=i.bytes}return s}function yi(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function qp(t,e,n){let r={},s=yi(t.cacheWrite5m),i=yi(t.cacheWrite1h),o=yi(t.reasoning),a=yi(t.webSearch),l=yi(t.webFetch);o!==null&&(e===null||o<=e)&&(r.reasoning_output_tokens=o);let c=(s??0)+(i??0),u=n===null||c<=n;return s!==null&&u&&(r.cache_write_5m_tokens=s),i!==null&&u&&(r.cache_write_1h_tokens=i),a!==null&&(r.web_search_requests=a),l!==null&&(r.web_fetch_requests=l),Object.keys(r).length>0?r:null}function mc(){return process.env.HOME||process.env.USERPROFILE||""}function C0(){if(process.env.OPENCODE_DB)return[Qn(process.env.OPENCODE_DB)];let t=process.env.XDG_DATA_HOME||Ss(mc(),".local","share");return[Ss(t,"lmplayer","opencode-local.db"),Ss(t,"lmplayer","opencode-dev.db")]}function N0(){return A0("node:sqlite").DatabaseSync}function oe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function At(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Gp(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function Ko(t){if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("maxBytes must be a positive safe integer");if(!Number.isSafeInteger(t.maxRows)||t.maxRows<=0)throw new Error("maxRows must be a positive safe integer");t.signal.throwIfAborted()}function pc(t){return`${t.source_id}\0${t.sessionid}`}function Mr(t,e){return t<e?-1:t>e?1:0}function Fp(t,e){return Mr(pc(t),pc(e))}function O0(t){let e={version:2,pos:t.pos,done:t.done,rr:t.rr};return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Tw(t){let e=oe(t);if(!e||typeof e.source_id!="string"||typeof e.sessionid!="string"||e.source_id.includes("\0")||e.sessionid.includes("\0"))throw new Error("invalid passive session discovery cursor");return{source_id:e.source_id,sessionid:e.sessionid}}function L0(t){if(t===void 0)return null;let e;try{e=oe(JSON.parse(Buffer.from(t,"base64url").toString("utf8")))}catch{throw new Error("invalid passive session discovery cursor")}if(!e)throw new Error("invalid passive session discovery cursor");if(e.version===1){let i=e.provider;if(!Number.isSafeInteger(i)||i<0||i>=$p.length)throw new Error("invalid passive session discovery cursor");let o=i,a=Tw({source_id:e.source_id,sessionid:e.sessionid}),l=new Map([[$p[o],a]]),c=new Set($p.slice(0,o));return{pos:l,done:c,rr:0}}if(e.version!==2)throw new Error("invalid passive session discovery cursor");let n=oe(e.pos);if(!n||!Array.isArray(e.done)||!Number.isSafeInteger(e.rr)||e.rr<0)throw new Error("invalid passive session discovery cursor");let r=new Map;for(let[i,o]of Object.entries(n))r.set(i,Tw(o));let s=new Set;for(let i of e.done){if(typeof i!="string")throw new Error("invalid passive session discovery cursor");s.add(i)}return{pos:r,done:s,rr:e.rr}}function Aw(t){if(typeof t!="string")return null;let e=t.toLowerCase();return e==="apply_patch"?"apply_patch":M0.includes(e)?"read":P0.includes(e)?"written":null}function F0(t){return typeof t=="string"?(()=>{try{return JSON.parse(t)}catch{return t}})():t}function fc(t,e=D0){let n=oe(t);if(!n)return null;for(let r of e){let s=n[r];if(typeof s=="string"&&s.length>0)return s;if(Array.isArray(s)){for(let i of s)if(typeof i=="string"&&i.length>0)return i}}return null}function Cw(t){let e=oe(t);if(!e)return null;if(typeof e.content=="string")return Buffer.byteLength(e.content,"utf8");if(typeof e.new_string=="string")return Buffer.byteLength(e.new_string,"utf8");if(typeof e.newString=="string")return Buffer.byteLength(e.newString,"utf8");if(typeof e.new_source=="string")return Buffer.byteLength(e.new_source,"utf8");if(typeof e.newSource=="string")return Buffer.byteLength(e.newSource,"utf8");if(Array.isArray(e.edits)){let n=0;for(let r of e.edits){let s=oe(r),i=s?.new_string??s?.newString;if(typeof i!="string")return null;n+=Buffer.byteLength(i,"utf8")}return n}return null}function gc(t){let e=new Map,n=null,r=()=>{n&&(e.set(n.path,(e.get(n.path)??0)+n.bytes),n=null)};for(let s of t.split(`
|
|
522
523
|
`)){let i=s.replace(/\r$/,""),o=/^\*\*\* (?:Add|Update|Delete) File: (.+)$/.exec(i);if(o){r(),n={path:o[1].trim(),bytes:0};continue}let a=/^\*\*\* Move to: (.+)$/.exec(i);if(a){n&&(n.path=a[1].trim());continue}if(i.startsWith("*** ")){r();continue}n&&i.startsWith("+")&&(n.bytes+=Buffer.byteLength(i.slice(1),"utf8")+1)}return r(),[...e].map(([s,i])=>({path:s,bytes:i}))}function j0(t){let e=0,n=t.length,r=()=>{for(;e<n&&/\s/.test(t[e]);)e++};r();let s=0,i=!1;for(let[c,u]of $0)if(t.startsWith(c,e)){e+=c.length,s=u,i=!0;break}if(!i||t[e]!=='"')return null;let o=e;e++;let a=!1;for(;e<n;){let c=t[e];if(c==="\\"){e+=2;continue}if(c==='"'){e++,a=!0;break}e++}if(!a)return null;let l;try{l=JSON.parse(t.slice(o,e))}catch{return null}if(typeof l!="string")return null;for(let c=0;c<s;c++){if(r(),t[e]!==")")return null;e++}return r(),t[e]===";"&&e++,r(),e<n?null:l}function Sw(t){if(t.length===0||t.endsWith(`
|
|
523
524
|
`))return null;let e=[];for(let n of t.split(`
|
|
524
525
|
`)){let r=/^\s*\d+\t(.*)$/s.exec(n);if(r===null)return null;e.push(r[1])}return e.join(`
|
|
@@ -2207,7 +2208,7 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
2207
2208
|
AND ended_at >= ?
|
|
2208
2209
|
ORDER BY started_at ASC, id ASC
|
|
2209
2210
|
`).all(...e,n)}finishTrackedInvocation(e,n){return this.db.transaction(()=>{let r=n.ended_at??z();if(this.stmts.finishTrackedInvocation.run(n.status,r,n.exit_code??null,n.signal??null,Qt(n.result_summary),Qt(n.error),n.team_chat_log_id??null,Qt(n.meta),Qt(n.config_warnings),r,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Uc(this.db,i),i.status==="cancelled"&&i.signal!==null&&i.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(i.team_chat_log_id,i.error??`holder received ${i.signal}`),i})()}reclaimTrackedInvocationIfUnchanged(e,n,r){return this.db.transaction(()=>{let s=r.ended_at??z();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(r.status,s,r.exit_code??null,r.signal??null,Qt(r.result_summary),Qt(r.error),r.team_chat_log_id??null,Qt(r.meta),Qt(r.config_warnings),s,e,n.holder_pid,n.holder_host,n.started_at,n.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Uc(this.db,o),o})()}heartbeatTrackedInvocation(e,n=z()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(n,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return YE(this.db,s,n),s})()}updateTrackedInvocationRequestPayload(e,n){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(n,e).changes!==1?null:(QE(this.db,e,n),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,n){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(n,e).changes!==1?null:(ZE(this.db,e,nr(n)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,n,r){return this.db.transaction(()=>{let s=z();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Qt(r),e,n.holder_pid,n.holder_host,n.started_at,n.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Uc(this.db,o),o.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(o.team_chat_log_id,r),o})()}terminalizeLinkedChatMessage(e,n){let r=this.stmts.getTeamChatLogById.get(e);r===void 0||r.status!=="running"||this.stmts.terminalizeTeamChatLogIfRunning.run("error",n,e).changes!==1||$c(this.db,e,{root_teamfile:r.root_teamfile,sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,receiver_teamfile:r.receiver_teamfile,receiver_alias:r.receiver_alias,message:r.message,response:null,origin:r.origin,status:"error",error_detail:n,truncated:r.truncated,created_at:z()})}listClaimableTerminalTrackedInvocations(e){let n=["status IN ('done', 'error', 'busy', 'cancelled', 'aborted')","ended_at IS NOT NULL","notified_by IS NULL"],r=[];e.from!==void 0&&(n.push("from_identity = ?"),r.push(e.from)),e.scope_teamfile!==void 0&&(n.push("scope_teamfile = ?"),r.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return r.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${n.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...r)}claimTrackedInvocationNotification(e,n,r=z()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(n,r,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return zE(this.db,i,n,r),i})()}listTrackedInvocations(e={}){let n=[],r=[];e.from!==void 0&&(n.push("from_identity = ?"),r.push(e.from)),e.scope_teamfile!==void 0&&(n.push("scope_teamfile = ?"),r.push(e.scope_teamfile)),e.status!==void 0&&(n.push("status = ?"),r.push(e.status)),e.kind!==void 0&&(n.push("kind = ?"),r.push(e.kind)),e.origin!==void 0&&(n.push("origin = ?"),r.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));r.push(s);let i=n.length===0?"":` WHERE ${n.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...r)}maxTrackedInvocationId(e={}){let n=[],r=[];e.from!==void 0&&(n.push("from_identity = ?"),r.push(e.from)),e.scope_teamfile!==void 0&&(n.push("scope_teamfile = ?"),r.push(e.scope_teamfile));let s=n.length===0?"":` WHERE ${n.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...r);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}updateTeamChatLogResponse(e,n){this.stmts.updateTeamChatLogResponse.run(n.response,n.status,n.error_detail,n.truncated,e)}getAgentInflight(e,n){return this.stmts.getAgentInflight.get(e,n)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,n){return this.tryAcquireAgentInflightTxn(e,n)}tryAcquireNativeHolder(e,n){return this.tryAcquireAgentInflightTxn(e,{nativeHolder:n})}findNativeHolder(e,n){return this.stmts.getNativeHolder.get(e,n)??null}updateNativeHolderPhase(e,n,r,s){return this.stmts.updateNativeHolderPhase.run(s,e,n,r,r).changes===1}publishNativeHolder(e,n,r,s,i="ready"){return this.stmts.publishNativeHolder.run(s,i,e,n,r,r).changes===1}clearNativeHolder(e,n,r){return this.stmts.clearNativeHolderFenced.run(e,n,r,r).changes===1}heartbeatAgentInflight(e,n,r=z()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:WE(this.db,s,n,r)})()}clearAgentInflight(e,n){this.db.transaction(()=>{let s=this.getAgentInflight(e,n);if(s===null)return;this.stmts.clearAgentInflight.run(e,n).changes===1&&la(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,n,r){return this.db.transaction(()=>{let i=this.getAgentInflight(e,n),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:n,observed_sender_teamfile:r.sender_teamfile,observed_sender_alias:r.sender_alias,observed_started_at:r.started_at,observed_holder_pid:r.holder_pid});return o.changes===1&&i!==null&&la(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,n){this.db.exec("BEGIN IMMEDIATE");try{let r=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(r===null||r.sender_teamfile!==e.sender_teamfile||r.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(n!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
2210
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==n)return this.db.exec("COMMIT"),!1;if(r.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&la(this.db,r,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let r=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of r)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(la(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,n){let r=this.stmts.getRuntimeState.get(ia,aa(e,n),oa);return r===void 0?null:DE(r.data)}setTerminalLock(e){this.db.transaction(()=>{let r=this.getTerminalLock(e.teamfile,e.alias);r!==null&&r.lock_id!==e.lock_id&&uf(this.db,r,!0),this.stmts.upsertRuntimeState.run(ia,aa(e.teamfile,e.alias),oa,JSON.stringify(e),e.last_heartbeat),r?.lock_id!==e.lock_id&&qE(this.db,e)})()}heartbeatTerminalLock(e,n,r,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,n);if(i===null||i.lock_id!==r)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(ia,aa(e,n),oa,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,n,r){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,n);if(s===null||s.lock_id!==r)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(ia,aa(e,n),oa);return i.changes===1&&uf(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,n,r){let s=this.stmts.getRuntimeState.get(e,n,r);return s===void 0?null:YF(s.data)}tryAcquireRuntimeProcessLock(e,n,r,s,i=z()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,n,r);if(o!==null&&!QF(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:iT(),holder_pid:process.pid,holder_host:pf(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,n,r,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,n,r,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,n,r);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,n,r);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,n){return this.stmts.setRunCurrentState.run(n,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,n,r){return this.stmts.setRunPausedState.run(n,r,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,n){return this.stmts.setRunPendingEscalationDecision.run(n,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,n){return this.stmts.setRunTerminalState.run(n,z(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,n){return this.resumeRunTxn(e,n,z())}insertStep(e){let n=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,z());return this.stmts.getStep.get(n.lastInsertRowid)}finishStep(e,n,r){return this.stmts.finishStep.run(n??null,r??null,z(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let n=this.stmts.listLatestStepOutcomesByState.all(e),r={};for(let s of n)r[s.state_name]=s.outcome;return r}insertSubmittedPr(e){let n=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??z(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(n.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let n=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,z());return this.stmts.getStepArtifact.get(n.lastInsertRowid)}insertExternalObject(e){let r=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,z()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:r}}insertExternalSignal(e){let n=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,z()),r=n.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(n.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:r}}raiseAttention(e){let n=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,z());return this.stmts.getAttention.get(n.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(z(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let n=z();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,n,n),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,n){return this.stmts.getDurableMemoryByName.get(e,n)??null}deleteDurableMemory(e,n){return this.stmts.deleteDurableMemory.run(e,n).changes>0}listDurableMemory(e,n){return n!==void 0?this.stmts.listDurableMemoryByType.all(e,n):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,n){return n!==void 0&&n.length>0?this.stmts.listDurableMemory.all(e).filter(s=>n.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:r,description:s,type:i,updated_at:o})=>({name:r,description:s,type:i,updated_at:o}))}recordSessionSize(e){let n=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??z());return this.stmts.getSessionSize.get(n.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,n,r=20){return this.stmts.sessionSizeHistory.all(e,n,r)}insertSessionEvent(e){let n=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(n.lastInsertRowid)}listSessionEvents(e,n){return n!==void 0?this.stmts.listSessionEventsSince.all(e,n):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,n=1e3){return this.stmts.listAllEventsSince.all(e,n)}latestAgentCall(e){let n=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(n===void 0)return null;try{let r=JSON.parse(n.payload);return typeof r.alias!="string"||typeof r.provider!="string"?null:{alias:r.alias,provider:r.provider,...typeof r.model=="string"?{model:r.model}:{}}}catch{return null}}agentCallTokenTotals(e){let n=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),r=0,s=0,i=0;for(let o of n)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(r+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:r,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let n=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(n.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,n,r){return this.stmts.findUnackedDrift.get(e,n??null,r)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let n=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,n,n),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,n){return this.stmts.getInteractiveSessionByRunAndState.get(e,n)??null}setInteractiveAgentOutput(e,n,r){this.stmts.setInteractiveAgentOutput.run(n,r,Date.now(),e)}resumeInteractive(e,n,r){return this.resumeInteractiveTxn(e,n,r,z())}resumeEscalation(e,n){return this.resumeEscalationTxn(e,n,z())}}});import{homedir as t$}from"node:os";import{join as dT}from"node:path";function s$(t=process.env){let e=t.LMCTL_HOME;return e!==void 0&&e.length>0?e:dT(t.HOME||t$(),n$)}function mT(t=process.env){return dT(s$(t),r$)}function Ai(t,e=process.env){return t!==void 0&&t.length>0?t:e.LMCTL_DB!==void 0&&e.LMCTL_DB.length>0?e.LMCTL_DB:mT(e)}function pT(t,e=process.env){return e.LMCTL_DB!==void 0&&e.LMCTL_DB.length>0&&e.LMCTL_DB!==mT(e)?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}var n$,r$,Hc=L(()=>{"use strict";n$=".lmctl",r$="state.db"});import{isAbsolute as i$,resolve as fT,join as gT}from"node:path";function En(t,e){let n=ff.get(t);if(!n||t.closed)throw Error("Context is closed");return n.resources.add(e),()=>n.resources.delete(e)}function un(t){let e=ff.get(t);if(!e)throw Error("Unknown context");return e.dal()}function Br(t){let e=hT.get(t);if(!e)throw Error("Context state is unavailable");return e}function Ci(t){return t!==null&&typeof t=="object"&&yT.has(t)}function gf(t){try{if(!t||typeof t!="object"||Array.isArray(t))return H("invalid_argument","Context needs an explicit options map");let e={...t},n=["pid","env","cwd","dbPath","dal","onProgress","onWarning","clock","interactive"];if(Object.keys(e).some(h=>!n.includes(h)))return H("invalid_argument","Unknown context option");if(!e.env||typeof e.env!="object"||Array.isArray(e.env)||typeof e.cwd!="string"||!i$(e.cwd))return H("invalid_argument","Context needs an explicit env and absolute cwd");let r=Object.freeze({...e.env});if(Object.values(r).some(h=>h!==void 0&&typeof h!="string"))return H("invalid_argument","Environment values must be strings or undefined");for(let h of["onProgress","onWarning","clock"])if(e[h]!==void 0&&typeof e[h]!="function")return H("invalid_argument",h+" must be a function");if(e.interactive!==void 0&&typeof e.interactive!="boolean")return H("invalid_argument","interactive must be a boolean");if(e.dbPath!==void 0&&(typeof e.dbPath!="string"||!e.dbPath))return H("invalid_argument","dbPath must be a nonempty string");if(e.pid!==void 0&&(!Number.isInteger(e.pid)||e.pid<=0))return H("invalid_argument","pid must be a positive integer");let s=fT(e.cwd),i=r.LMCTL_HOME||(r.HOME?gT(r.HOME,".lmctl"):void 0);if(!(e.dbPath||r.LMCTL_DB||(i?gT(i,"state.db"):void 0)))return H("invalid_argument","Context needs dbPath, LMCTL_DB, LMCTL_HOME or HOME");let a=!1,l,c,u,d=new AbortController,m=new Set,p=h=>{if(l){try{l.close()}catch(g){h.push(G(g))}l=void 0}},f=Object.freeze({status:"ok",error:null,pid:e.pid,signal:d.signal,env:r,cwd:s,dbPath:fT(s,Ai(e.dbPath,r)),dal:e.dal,interactive:e.interactive??r.LMCTL_NON_INTERACTIVE!=="1",onProgress:e.onProgress??(()=>{}),onWarning:e.onWarning??(()=>{}),clock:e.clock??Date.now,get closed(){return a},close(){if(c)return c;let h;return c=new Promise(g=>{h=g}),a=!0,d.abort(),(async()=>{let g=[],y=0;for(let b of[...m])try{await b.close(),y++,m.delete(b)}catch(_){g.push(G(_))}g.length||p(g),h({released:y,errors:g})})(),c},finalizeSync(h){if(u)return u;a=!0;let g=[],y={released:0,errors:g};u=y,c??=Promise.resolve(y);let b=[];for(let _ of[...m])try{let v=_.finalizeSync(h);v instanceof Promise?b.push(v.then(()=>{y.released++,m.delete(_)}).catch(E=>{g.push(G(E))})):(y.released++,m.delete(_))}catch(v){g.push(G(v))}return d.abort(h),b.length?c=Promise.all(b).then(()=>(g.length||p(g),y)):g.length||p(g),y}});return ff.set(f,{resources:m,dal(){if(e.dal)return e.dal;if(l)return l;if(a)throw Error("Context is closed");return l??=ut({path:f.dbPath})}}),yT.add(f),hT.set(f,{activeAgents:new WeakSet,activeSessions:new Set,handoffSessions:new Set,reservations:new Map}),f}catch(e){return H("invalid_argument","Invalid context: "+G(e))}}var ff,hT,yT,en=L(()=>{"use strict";Zt();Hc();yt();ff=new WeakMap;hT=new WeakMap;yT=new WeakSet});function _T(t){let e=Object.create(null),n=Object.create(null),r=(s,i,o=!0)=>{if(Array.isArray(s)){let a=s.map((l,c)=>r(l,i+"."+c,!1));return o&&(n[i]=a),a}if(s&&typeof s=="object"&&!(s instanceof Date)){let a=Object.create(null);for(let[l,c]of Object.entries(s)){let d=/^Provider[123]$/.test(i)&&["provider","model1"].includes(l)?l[0].toUpperCase()+l.slice(1):l;if(Object.hasOwn(a,d))throw Error(`Ambiguous property '${i}.${d}'`);a[d]=r(c,i?i+"."+d:d,o&&/^[_a-zA-Z]\w*$/.test(d))}return a}return o&&(n[i]=s),s};for(let[s,i]of Object.entries(t))e[s]=r(i,s,/^[_a-zA-Z]\w*$/.test(s));return{properties:e,flat:n}}var vT=L(()=>{"use strict"});function Wc(t){return{Provider1:t.provider1.provider,Provider2:t.provider2.provider,Provider3:t.provider3.provider,Model1:t.provider1.model1,Model2:t.provider2.model1,Model3:t.provider3.model1}}var hf=L(()=>{"use strict"});import{readFileSync as o$}from"node:fs";import{homedir as a$}from"node:os";import{join as bT,resolve as l$}from"node:path";function Ni(t=process.env,e){let n=t.LMCTL_HOME||(t.HOME===void 0?process.env.LMCTL_HOME:void 0);return e!==void 0?l$(e):bT(n||bT(t.HOME||a$(),".lmctl"),"init.toml")}function c$(t,e,n,r,s){return e==="missing"?"Missing "+t:e==="read"?"Cannot read "+t+": "+n:"Invalid "+t+":"+r+":"+s+": "+n}function Xc(t,e="<init.toml>"){let{document:n}=yf(t,e),r={};for(let i of qc){let o=n[i];if(o===void 0)continue;if(!o||typeof o!="object"||Array.isArray(o)||o instanceof Date)throw new Wt(e,"schema","["+i+"] must be a table with provider and model1");let a={};for(let l of wT){let c=o[l];if(typeof c!="string"||!c.trim())throw new Wt(e,"schema",i+"."+l+" must be a nonempty string");a[l]=c}r[i]=a}let s={raw:t,document:n,path:e,slots:r};return Object.defineProperty(s,"config",{enumerable:!1,get(){let i=qc.find(o=>!r[o]);if(i)throw new Wt(e,"schema","["+i+"] is not in "+e+"; this needs the example slots ["+qc.join("], [")+"] -- add ["+i+"] with provider and model1");return{provider1:r.Provider1,provider2:r.Provider2,provider3:r.Provider3}}}),s}function yf(t,e="<init.toml>"){let n;try{n=br(t.startsWith("\uFEFF")?t.slice(1):t,{integersAsBigInt:"asNeeded",useLegacyDate:!0})}catch(r){let s=r;throw new Wt(e,"syntax",s.message,s.line??1,(s.column??1)+(t.startsWith("\uFEFF")&&s.line===1?1:0))}return{raw:t,document:n,path:e}}function ET(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(o$(t))}catch(n){let r=n;throw new Wt(t,r.code==="ENOENT"?"missing":"read",r.message)}return e}function _f(t=Ni()){return yf(ET(t),t)}function Gc(t=Ni()){return Xc(ET(t),t)}var qc,wT,Wt,Jc=L(()=>{"use strict";go();qc=["Provider1","Provider2","Provider3"],wT=["provider","model1"];Wt=class extends Error{constructor(n,r,s,i=1,o=1){let a=c$(n,r,s,i,o);super(r==="missing"?a+". Run lmctl init first.":a+". Fix the file or run lmctl init.");this.path=n;this.kind=r;this.line=i;this.column=o;this.detail=a}detail}});var TT=L(()=>{"use strict";go();Jc()});import{spawnSync as Sf}from"node:child_process";import{existsSync as kT,readFileSync as RT}from"node:fs";import{homedir as xT}from"node:os";import{resolve as Ef}from"node:path";function Oi(t,e){return e.code==="ETIMEDOUT"?`${t} did not respond within lint's own spawn timeout (${e.message}) \u2014 this does not mean the provider itself is unreachable, only that this specific check didn't finish in time.`:`${t} could not be run: ${e.message}`}function m$(){let t=Sf("agy",["models"],{encoding:"utf-8",timeout:d$});return{status:t.status,stdout:t.stdout??"",error:t.error}}function f$(t){let e=[],n={};for(let r of t.split(/\r?\n/)){let s=r.trim(),i=s.indexOf(" ");if(i<0)continue;let o=s.slice(0,i).trim(),a=s.slice(i+1).trim();o&&(e.push(o),a&&(n[o]=a))}return{models:e,displayNames:n}}function AT(t){if(!t&&vf)return vf;let e=i=>(t||(vf=i),i),n;try{n=(t??p$??m$)()}catch(i){return e({available:!1,models:[],reason:i instanceof Error?Oi("agy models",i):`agy models could not be run: ${String(i)}`})}if(n.error)return e({available:!1,models:[],reason:Oi("agy models",n.error)});if(n.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${n.status??"unknown"}`});let{models:r,displayNames:s}=f$(n.stdout);return r.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:r,displayNames:s})}function h$(){let t=Sf("codex",["debug","models"],{encoding:"utf-8",timeout:g$});return{status:t.status,stdout:t.stdout??"",error:t.error}}function _$(t){let e;try{e=JSON.parse(t)}catch{return}let n=e.models;if(!Array.isArray(n))return;let r=[];for(let s of n){if(!s||typeof s!="object")continue;let{slug:i,visibility:o}=s;typeof i=="string"&&o==="list"&&r.push(i)}return r}function CT(t){if(!t&&bf)return bf;let e=s=>(t||(bf=s),s),n;try{n=(t??y$??h$)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Oi("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(n.error)return e({available:!1,models:[],reason:Oi("codex debug models",n.error)});if(n.status!==0)return e({available:!1,models:[],reason:`codex debug models exited with status ${n.status??"unknown"}`});let r=_$(n.stdout);return r===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):r.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:r})}function b$(t){let e=Sf("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:v$});return{status:e.status,stdout:e.stdout??"",error:e.error}}function w$(t,e){if(!e&&wf.has(t))return wf.get(t);let n=o=>(e||wf.set(t,o),o),r=t?`opencode models ${t}`:"opencode models",s;try{s=(e??b$)(t)}catch(o){return n({available:!1,models:[],reason:o instanceof Error?Oi(r,o):`${r} could not be run: ${String(o)}`})}if(s.error)return n({available:!1,models:[],reason:Oi(r,s.error)});if(s.status!==0)return n({available:!1,models:[],reason:`${r} exited with status ${s.status??"unknown"}`});let i=s.stdout.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0);return i.length===0?n({available:!1,models:[],reason:`${r} returned no models`}):n({available:!0,models:i})}function kf(t,e={}){let n=[];for(let r of t){let s=r.provider.trim().toLowerCase();if(r.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&s!=="muse"&&n.push(`[${r.alias}] effort="${r.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&r.effort&&n.push(`[${r.alias}] effort="${r.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),s==="copilot"){if(!r.model)continue;n.push(`[${r.alias}] model="${r.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(r.effort&&!r.model&&n.push(`[${r.alias}] effort="${r.effort}" has no effect without model= on an opencode member.`),!r.model)continue;let i=T$(e.opencodeConfigPath);if(!i.available){n.push(`[${r.alias}] model="${r.model}" cannot be verified for opencode: ${i.reason}.`);continue}if(i.models.includes(r.model)||/^github-copilot\/(gpt|gemini|o[0-9])/.test(r.model))continue;if(!r.model.includes("/")){let l=i.models.filter(c=>c.endsWith(`/${r.model}`));n.push(l.length>0?`[${r.alias}] model="${r.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model>. Your opencode.json declares it as ${l.join(" / ")}; set model=${l[0]}.`:`[${r.alias}] model="${r.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model> (e.g. github-copilot/${r.model}). Declare it in ~/.config/opencode/opencode.json (see https://lmctl.com/examples/opencode.json).`);continue}let o=r.model.slice(0,r.model.indexOf("/")),a=w$(o,e.opencodeModelsRunner);if(a.available&&a.models.includes(r.model))continue;if(a.available&&!a.models.includes(r.model)){n.push(`[${r.alias}] model="${r.model}" was not found in opencode's LOCALLY-VISIBLE live catalog for "${o}" (checked \`opencode models ${o}\`) -- this is unresolved, not a confirmed unavailability: it could mean opencode genuinely doesn't serve this model, OR that your local catalog/auth for "${o}" is stale/incomplete. Declaring it in opencode.json may or may not help; if it doesn't, check whether a non-opencode provider serves this model directly (e.g. \`lmctl lint\` with model= against provider=codex/claude/gemini/agy).`);continue}n.push(`[${r.alias}] model="${r.model}" is not declared in your opencode.json. opencode resolves github-copilot GPT/Gemini config-free, but copilot Claude and custom providers must be declared \u2014 copy https://lmctl.com/examples/opencode.json to ~/.config/opencode/opencode.json and adjust for your account.`);continue}if(s==="kimi"){if(!r.model)continue;let i=MT(e.kimiConfigPath);i.available?i.models.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not declared in Kimi's [models] config. Valid configured models: ${ua(i.models)}`):n.push(`[${r.alias}] model="${r.model}" cannot be verified for kimi: ${i.reason}.`);continue}if(s==="agy"){if(!r.model)continue;let i=AT(e.agyModelsRunner);i.available?i.models.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in agy's live model catalog (\`agy models\`). Valid models: ${ua(i.models)}`):n.push(`[${r.alias}] model="${r.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!r.model||zc.includes(r.model))continue;Kc.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in dsh's built-in catalog. Valid pinned models: ${ua(Kc)}. Valid server-resolved aliases (DeepSeek resolves these to its current model server-side -- pinning to a specific version instead is a DOWNGRADE, not a safer choice): ${ua(zc)}. The catalog is patchable via dsh profile overlays \u2014 a model added that way warns here even though it may resolve.`);continue}if(s==="hermes"){if(!r.model)continue;let i=r.model.indexOf(":");(i<=0||i===r.model.length-1)&&n.push(`[${r.alias}] model="${r.model}" should use <provider>:<model> from Hermes's ACP catalog. lmctl checks the shape only; provider and model availability are resolved by Hermes.`);continue}if(s!=="pi"){if(s==="codex"){if(!r.model)continue;r.model===ST&&n.push(`[${r.alias}] model="${ST}" is banned as a build model (operator, 2026-09-06) -- it's a fast/cheap classification model, not intended for build work, and there's no cost reason left to reach for it. Use model=gpt-5.6-sol (or leave model= unset) for build work; if this member genuinely does non-build/classification work, this warning can be ignored.`);let i=CT(e.codexModelsRunner);if(!i.available){n.push(`[${r.alias}] model="${r.model}" cannot be verified for codex: ${i.reason}.`);continue}i.models.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in codex's live model catalog (\`codex debug models\`). Valid models: ${ua(i.models)}`);continue}r.model&&(IT.has(s)||n.push(`[${r.alias}] model="${r.model}" cannot be verified for provider "${s}": no model validation path exists for this provider.`))}}}return n}async function NT(t,e={}){let n=t.filter(o=>o.model!==void 0&&IT.has(o.provider.trim().toLowerCase()));if(n.length===0)return{warnings:[],errors:[]};let r=e.snapshot??await As();if(r.catalog===null)return{warnings:[],errors:[]};let s=[],i=[];for(let o of n){let a=o.provider.trim().toLowerCase(),l=o.model,c=Ic(a,l,r.catalog,r.aliases);if(c.kind==="unknown"){let u=hE(r.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${u} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&u$.test(l)){let u=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${u}" instead.`)}}return{warnings:s,errors:i}}async function OT(t,e={}){return(await NT(t,e)).warnings}async function LT(t,e={}){return(await NT(t,e)).errors}function MT(t){let e=process.env.KIMI_CODE_HOME||Ef(xT(),".kimi-code"),n=t??Ef(e,"config.toml");if(!kT(n))return{available:!1,models:[],reason:`${n} not found`};let r;try{r=RT(n,"utf-8")}catch(i){return{available:!1,models:[],reason:`${n} could not be read: ${i instanceof Error?i.message:String(i)}`}}let s=new Set;for(let i of r.split(/\r?\n/)){if(/^\s*\[/.test(i)&&!/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.test(i))return{available:!1,models:[],reason:`${n} has an invalid TOML table header`};let o=/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(i);if(!o)continue;let a=E$(o[1]);if(o[1].trim().startsWith("models")&&a===null)return{available:!1,models:[],reason:`${n} has an invalid [models] table header`};a?.[0]==="models"&&a.length>=2&&s.add(a[1])}return s.size===0?{available:!1,models:[],reason:`${n} has no [models] entries`}:{available:!0,models:[...s]}}function E$(t){let e=[],n=0;for(;n<t.length;){for(;/\s/.test(t[n]??"");)n++;if(n>=t.length)break;let r="",s=t[n]==='"'||t[n]==="'"?t[n++]:void 0;if(s){for(;n<t.length&&t[n]!==s;)s==='"'&&t[n]==="\\"&&n+1<t.length&&n++,r+=t[n++];if(t[n]!==s)return null;n++}else{for(;n<t.length&&t[n]!==".";)r+=t[n++];r=r.trim()}if(!r)return null;for(e.push(r);/\s/.test(t[n]??"");)n++;if(n>=t.length)break;if(t[n]!==".")return null;n++}return e.length>0?e:null}function T$(t){let e=t??Ef(xT(),".config","opencode","opencode.json");if(!kT(e))return{available:!0,models:[]};let n;try{n=JSON.parse(RT(e,"utf-8"))}catch(r){return{available:!1,models:[],reason:`${e} could not be parsed: ${r instanceof Error?r.message:String(r)}`}}return{available:!0,models:S$(n)}}function S$(t){if(!Tf(t))return[];let e=Vc(t.provider)??Vc(t.providers);if(!e)return[];let n=new Set;for(let[r,s]of Object.entries(e)){if(!Tf(s))continue;let i=Vc(s.models)??Vc(s.model);if(i)for(let o of Object.keys(i))n.add(o.startsWith(`${r}/`)?o:`${r}/${o}`)}return[...n].sort()}function Vc(t){return Tf(t)?t:null}function Tf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ua(t){return t.length>0?t.join(", "):"(none)"}var IT,u$,Kc,zc,ST,d$,vf,p$,g$,bf,y$,v$,wf,Yc=L(()=>{"use strict";Cs();Ac();IT=new Set(Object.keys(ta).filter(t=>t!=="codex"&&t!=="kimi")),u$=/\d\.(?=\d)/,Kc=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],zc=["deepseek-flash","deepseek-pro"],ST="gpt-5.3-codex-spark",d$=15e3;vf=null;g$=5e3;bf=null;v$=5e3;wf=new Map});import*as PT from"node:child_process";function R$(t,e){try{let n=e(t,["--version"],{encoding:"utf-8",timeout:5e3});return n.status===0?{found:!0,version:(n.stdout??"").toString().trim().split(/\r?\n/,1)[0]?.trim()||void 0}:n.status===null?{found:!1,failureMode:"not installed"}:{found:!1,failureMode:"runs but failed"}}catch{return{found:!1,failureMode:"not installed"}}}function Rf(t,e={}){let n=e.spawnSync===void 0&&process.env[x$]==="1",r=e.spawnSync??PT.spawnSync,s=new Set,i=[];for(let o of t){if(s.has(o))continue;s.add(o);let a=DT[o];if(!a){i.push({provider:o,binary:"<unknown>",found:!1,failureMode:"not installed"});continue}if(n){i.push({provider:o,binary:a,found:!0,version:"(skipped)"});continue}let l=R$(a,r);l.found?i.push({provider:o,binary:a,found:!0,version:l.version}):i.push({provider:o,binary:a,found:!1,failureMode:l.failureMode})}return i}function FT(t){if(t.binary==="<unknown>")return`unknown provider "${t.provider}" \u2014 no binary mapping (allowed: ${Object.keys(DT).join(", ")})`;let e=k$[t.provider],n=e?` (install via ${e})`:"";return t.failureMode==="runs but failed"?`provider "${t.provider}" binary '${t.binary}' found but \`${t.binary} --version\` failed to run cleanly \u2014 check install integrity${n}`:`provider "${t.provider}" binary '${t.binary}' not installed${n}`}var DT,k$,x$,xf=L(()=>{"use strict";DT={claude:"claude",codex:"codex",copilot:"copilot",gemini:"gemini",opencode:"opencode",lmplayer:"lmplayer",qwen:"qwen",agy:"agy",kimi:"kimi",dsh:"dsh",hermes:"hermes",miniplayer:"miniplayer",muse:"muse",pi:"pi"},k$={claude:"https://docs.claude.com/code",codex:"https://github.com/openai/codex",copilot:"https://docs.github.com/copilot/cli",gemini:"https://github.com/google-gemini/gemini-cli",opencode:"https://opencode.ai",lmplayer:"Install lmplayer and ensure the lmplayer binary is on PATH.",qwen:"https://github.com/QwenLM/qwen-code",agy:"https://antigravity.google",kimi:"https://github.com/MoonshotAI/kimi-code",dsh:"https://github.com/deepseek-ai/deepseek-harness",hermes:"https://github.com/NousResearch/hermes-agent",pi:"https://github.com/badlogic/pi-mono"};x$="LMCTL_SKIP_BINARY_CHECK"});var $T=L(()=>{"use strict";xm();hf();Jc();Jc();TT();Yc();Cs();xf()});import{resolve as I$,join as jT}from"node:path";function If(t,e={}){try{if(!Ci(t))return H("invalid_argument","Expected a context created by createLmctlContext");if(t.closed)return H("cancelled","Context is closed");if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Profile options must be a map");let n=e.path;if(Object.keys(e).some(i=>!(ht.find(o=>o.name==="loadProfile")?.params.find(o=>o.name==="options")?.keys??[]).some(o=>o.name===i))||n!==void 0&&(typeof n!="string"||!n))return H("invalid_argument","Profile options accept a nonempty path string only");let r=t.env.LMCTL_HOME||(t.env.HOME?jT(t.env.HOME,".lmctl"):void 0);if(!n&&!r)return H("invalid_argument","Profile path requires HOME, LMCTL_HOME or an explicit path");let s=I$(t.cwd,n??jT(r,"init.toml"));return ge({path:Ni({...t.env,HOME:t.env.HOME??t.cwd},s)})}catch(n){return H("invalid_argument","Invalid profile arguments: "+G(n))}}function A$(t){try{if(!t||typeof t!="object"||Array.isArray(t))return H("invalid_argument","Expected a validated InitConfig");let e={};for(let n of["provider1","provider2","provider3"]){let r=t[n];if(!r||typeof r!="object"||Array.isArray(r))return H("invalid_argument",n+" must be a provider map");let s={};for(let i of["provider","model1"]){let o=r[i];if(typeof o!="string"||!o.trim())return H("invalid_argument",n+"."+i+" must be a nonempty string");s[i]=o}e[n]=s}return ge(Wc(e))}catch(e){return H("invalid_argument","Invalid profile: "+G(e))}}function C$(t,e={}){let n=If(t,e);if(n.status==="error")return n;try{let r=Gc(n.path);return ge({profile:{path:r.path,raw:r.raw,config:r.config},values:{...Wc(r.config),Directory:t.cwd,NonInteractive:!t.interactive}})}catch(r){return r instanceof Wt?H(r.kind,r.message,{path:r.path,line:r.line,column:r.column}):H("read","Could not load profile: "+G(r),{path:n.path})}}function N$(t,e={}){let n=If(t,e);if(n.status==="error")return n;try{let r=_f(n.path),{properties:s,flat:i}=_T(r.document);return ge({path:r.path,properties:s,flat:i})}catch(r){return r instanceof Wt?H(r.kind,r.message,{path:r.path,line:r.line,column:r.column}):H("schema","Invalid properties in "+n.path+": "+G(r)+". Fix the file or run lmctl init.",{path:n.path})}}var UT=L(()=>{"use strict";vT();zn();$T();hf();en();yt()});function Tn(t){return t!=="gemini"}function Qc(t){if(!Tn(t))throw new Error(Hr)}var Hr,Li=L(()=>{"use strict";Hr="Standalone Gemini CLI support is disabled; use provider=agy with an Agy-supported Gemini model."});function BT(t){if(t.length===0||!t.startsWith("---"))throw new Sn("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
2211
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==n)return this.db.exec("COMMIT"),!1;if(r.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&la(this.db,r,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let r=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of r)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(la(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,n){let r=this.stmts.getRuntimeState.get(ia,aa(e,n),oa);return r===void 0?null:DE(r.data)}setTerminalLock(e){this.db.transaction(()=>{let r=this.getTerminalLock(e.teamfile,e.alias);r!==null&&r.lock_id!==e.lock_id&&uf(this.db,r,!0),this.stmts.upsertRuntimeState.run(ia,aa(e.teamfile,e.alias),oa,JSON.stringify(e),e.last_heartbeat),r?.lock_id!==e.lock_id&&qE(this.db,e)})()}heartbeatTerminalLock(e,n,r,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,n);if(i===null||i.lock_id!==r)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(ia,aa(e,n),oa,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,n,r){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,n);if(s===null||s.lock_id!==r)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(ia,aa(e,n),oa);return i.changes===1&&uf(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,n,r){let s=this.stmts.getRuntimeState.get(e,n,r);return s===void 0?null:YF(s.data)}tryAcquireRuntimeProcessLock(e,n,r,s,i=z()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,n,r);if(o!==null&&!QF(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:iT(),holder_pid:process.pid,holder_host:pf(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,n,r,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,n,r,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,n,r);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,n,r);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,n){return this.stmts.setRunCurrentState.run(n,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,n,r){return this.stmts.setRunPausedState.run(n,r,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,n){return this.stmts.setRunPendingEscalationDecision.run(n,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,n){return this.stmts.setRunTerminalState.run(n,z(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,n){return this.resumeRunTxn(e,n,z())}insertStep(e){let n=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,z());return this.stmts.getStep.get(n.lastInsertRowid)}finishStep(e,n,r){return this.stmts.finishStep.run(n??null,r??null,z(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let n=this.stmts.listLatestStepOutcomesByState.all(e),r={};for(let s of n)r[s.state_name]=s.outcome;return r}insertSubmittedPr(e){let n=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??z(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(n.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let n=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,z());return this.stmts.getStepArtifact.get(n.lastInsertRowid)}insertExternalObject(e){let r=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,z()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:r}}insertExternalSignal(e){let n=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,z()),r=n.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(n.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:r}}raiseAttention(e){let n=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,z());return this.stmts.getAttention.get(n.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(z(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let n=z();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,n,n),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,n){return this.stmts.getDurableMemoryByName.get(e,n)??null}deleteDurableMemory(e,n){return this.stmts.deleteDurableMemory.run(e,n).changes>0}listDurableMemory(e,n){return n!==void 0?this.stmts.listDurableMemoryByType.all(e,n):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,n){return n!==void 0&&n.length>0?this.stmts.listDurableMemory.all(e).filter(s=>n.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:r,description:s,type:i,updated_at:o})=>({name:r,description:s,type:i,updated_at:o}))}recordSessionSize(e){let n=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??z());return this.stmts.getSessionSize.get(n.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,n,r=20){return this.stmts.sessionSizeHistory.all(e,n,r)}insertSessionEvent(e){let n=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(n.lastInsertRowid)}listSessionEvents(e,n){return n!==void 0?this.stmts.listSessionEventsSince.all(e,n):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,n=1e3){return this.stmts.listAllEventsSince.all(e,n)}latestAgentCall(e){let n=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(n===void 0)return null;try{let r=JSON.parse(n.payload);return typeof r.alias!="string"||typeof r.provider!="string"?null:{alias:r.alias,provider:r.provider,...typeof r.model=="string"?{model:r.model}:{}}}catch{return null}}agentCallTokenTotals(e){let n=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),r=0,s=0,i=0;for(let o of n)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(r+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:r,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let n=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(n.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,n,r){return this.stmts.findUnackedDrift.get(e,n??null,r)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let n=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,n,n),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,n){return this.stmts.getInteractiveSessionByRunAndState.get(e,n)??null}setInteractiveAgentOutput(e,n,r){this.stmts.setInteractiveAgentOutput.run(n,r,Date.now(),e)}resumeInteractive(e,n,r){return this.resumeInteractiveTxn(e,n,r,z())}resumeEscalation(e,n){return this.resumeEscalationTxn(e,n,z())}}});import{homedir as t$}from"node:os";import{join as dT}from"node:path";function s$(t=process.env){let e=t.LMCTL_HOME;return e!==void 0&&e.length>0?e:dT(t.HOME||t$(),n$)}function mT(t=process.env){return dT(s$(t),r$)}function Ai(t,e=process.env){return t!==void 0&&t.length>0?t:e.LMCTL_DB!==void 0&&e.LMCTL_DB.length>0?e.LMCTL_DB:mT(e)}function pT(t,e=process.env){return e.LMCTL_DB!==void 0&&e.LMCTL_DB.length>0&&e.LMCTL_DB!==mT(e)?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}var n$,r$,Hc=L(()=>{"use strict";n$=".lmctl",r$="state.db"});import{isAbsolute as i$,resolve as fT,join as gT}from"node:path";function En(t,e){let n=ff.get(t);if(!n||t.closed)throw Error("Context is closed");return n.resources.add(e),()=>n.resources.delete(e)}function un(t){let e=ff.get(t);if(!e)throw Error("Unknown context");return e.dal()}function Br(t){let e=hT.get(t);if(!e)throw Error("Context state is unavailable");return e}function Ci(t){return t!==null&&typeof t=="object"&&yT.has(t)}function gf(t){try{if(!t||typeof t!="object"||Array.isArray(t))return H("invalid_argument","Context needs an explicit options map");let e={...t},n=["pid","env","cwd","dbPath","dal","onProgress","onWarning","clock","interactive"];if(Object.keys(e).some(h=>!n.includes(h)))return H("invalid_argument","Unknown context option");if(!e.env||typeof e.env!="object"||Array.isArray(e.env)||typeof e.cwd!="string"||!i$(e.cwd))return H("invalid_argument","Context needs an explicit env and absolute cwd");let r=Object.freeze({...e.env});if(Object.values(r).some(h=>h!==void 0&&typeof h!="string"))return H("invalid_argument","Environment values must be strings or undefined");for(let h of["onProgress","onWarning","clock"])if(e[h]!==void 0&&typeof e[h]!="function")return H("invalid_argument",h+" must be a function");if(e.interactive!==void 0&&typeof e.interactive!="boolean")return H("invalid_argument","interactive must be a boolean");if(e.dbPath!==void 0&&(typeof e.dbPath!="string"||!e.dbPath))return H("invalid_argument","dbPath must be a nonempty string");if(e.pid!==void 0&&(!Number.isInteger(e.pid)||e.pid<=0))return H("invalid_argument","pid must be a positive integer");let s=fT(e.cwd),i=r.LMCTL_HOME||(r.HOME?gT(r.HOME,".lmctl"):void 0);if(!(e.dbPath||r.LMCTL_DB||(i?gT(i,"state.db"):void 0)))return H("invalid_argument","Context needs dbPath, LMCTL_DB, LMCTL_HOME or HOME");let a=!1,l,c,u,d=new AbortController,m=new Set,p=h=>{if(l){try{l.close()}catch(g){h.push(V(g))}l=void 0}},f=Object.freeze({status:"ok",error:null,pid:e.pid,signal:d.signal,env:r,cwd:s,dbPath:fT(s,Ai(e.dbPath,r)),dal:e.dal,interactive:e.interactive??r.LMCTL_NON_INTERACTIVE!=="1",onProgress:e.onProgress??(()=>{}),onWarning:e.onWarning??(()=>{}),clock:e.clock??Date.now,get closed(){return a},close(){if(c)return c;let h;return c=new Promise(g=>{h=g}),a=!0,d.abort(),(async()=>{let g=[],y=0;for(let b of[...m])try{await b.close(),y++,m.delete(b)}catch(_){g.push(V(_))}g.length||p(g),h({released:y,errors:g})})(),c},finalizeSync(h){if(u)return u;a=!0;let g=[],y={released:0,errors:g};u=y,c??=Promise.resolve(y);let b=[];for(let _ of[...m])try{let v=_.finalizeSync(h);v instanceof Promise?b.push(v.then(()=>{y.released++,m.delete(_)}).catch(E=>{g.push(V(E))})):(y.released++,m.delete(_))}catch(v){g.push(V(v))}return d.abort(h),b.length?c=Promise.all(b).then(()=>(g.length||p(g),y)):g.length||p(g),y}});return ff.set(f,{resources:m,dal(){if(e.dal)return e.dal;if(l)return l;if(a)throw Error("Context is closed");return l??=ut({path:f.dbPath})}}),yT.add(f),hT.set(f,{activeAgents:new WeakSet,activeSessions:new Set,handoffSessions:new Set,reservations:new Map}),f}catch(e){return H("invalid_argument","Invalid context: "+V(e))}}var ff,hT,yT,en=L(()=>{"use strict";Zt();Hc();yt();ff=new WeakMap;hT=new WeakMap;yT=new WeakSet});function _T(t){let e=Object.create(null),n=Object.create(null),r=(s,i,o=!0)=>{if(Array.isArray(s)){let a=s.map((l,c)=>r(l,i+"."+c,!1));return o&&(n[i]=a),a}if(s&&typeof s=="object"&&!(s instanceof Date)){let a=Object.create(null);for(let[l,c]of Object.entries(s)){let d=/^Provider[123]$/.test(i)&&["provider","model1"].includes(l)?l[0].toUpperCase()+l.slice(1):l;if(Object.hasOwn(a,d))throw Error(`Ambiguous property '${i}.${d}'`);a[d]=r(c,i?i+"."+d:d,o&&/^[_a-zA-Z]\w*$/.test(d))}return a}return o&&(n[i]=s),s};for(let[s,i]of Object.entries(t))e[s]=r(i,s,/^[_a-zA-Z]\w*$/.test(s));return{properties:e,flat:n}}var vT=L(()=>{"use strict"});function Wc(t){return{Provider1:t.provider1.provider,Provider2:t.provider2.provider,Provider3:t.provider3.provider,Model1:t.provider1.model1,Model2:t.provider2.model1,Model3:t.provider3.model1}}var hf=L(()=>{"use strict"});import{readFileSync as o$}from"node:fs";import{homedir as a$}from"node:os";import{join as bT,resolve as l$}from"node:path";function Ni(t=process.env,e){let n=t.LMCTL_HOME||(t.HOME===void 0?process.env.LMCTL_HOME:void 0);return e!==void 0?l$(e):bT(n||bT(t.HOME||a$(),".lmctl"),"init.toml")}function c$(t,e,n,r,s){return e==="missing"?"Missing "+t:e==="read"?"Cannot read "+t+": "+n:"Invalid "+t+":"+r+":"+s+": "+n}function Xc(t,e="<init.toml>"){let{document:n}=yf(t,e),r={};for(let i of qc){let o=n[i];if(o===void 0)continue;if(!o||typeof o!="object"||Array.isArray(o)||o instanceof Date)throw new Wt(e,"schema","["+i+"] must be a table with provider and model1");let a={};for(let l of wT){let c=o[l];if(typeof c!="string"||!c.trim())throw new Wt(e,"schema",i+"."+l+" must be a nonempty string");a[l]=c}r[i]=a}let s={raw:t,document:n,path:e,slots:r};return Object.defineProperty(s,"config",{enumerable:!1,get(){let i=qc.find(o=>!r[o]);if(i)throw new Wt(e,"schema","["+i+"] is not in "+e+"; this needs the example slots ["+qc.join("], [")+"] -- add ["+i+"] with provider and model1");return{provider1:r.Provider1,provider2:r.Provider2,provider3:r.Provider3}}}),s}function yf(t,e="<init.toml>"){let n;try{n=br(t.startsWith("\uFEFF")?t.slice(1):t,{integersAsBigInt:"asNeeded",useLegacyDate:!0})}catch(r){let s=r;throw new Wt(e,"syntax",s.message,s.line??1,(s.column??1)+(t.startsWith("\uFEFF")&&s.line===1?1:0))}return{raw:t,document:n,path:e}}function ET(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(o$(t))}catch(n){let r=n;throw new Wt(t,r.code==="ENOENT"?"missing":"read",r.message)}return e}function _f(t=Ni()){return yf(ET(t),t)}function Gc(t=Ni()){return Xc(ET(t),t)}var qc,wT,Wt,Jc=L(()=>{"use strict";go();qc=["Provider1","Provider2","Provider3"],wT=["provider","model1"];Wt=class extends Error{constructor(n,r,s,i=1,o=1){let a=c$(n,r,s,i,o);super(r==="missing"?a+". Run lmctl init first.":a+". Fix the file or run lmctl init.");this.path=n;this.kind=r;this.line=i;this.column=o;this.detail=a}detail}});var TT=L(()=>{"use strict";go();Jc()});import{spawnSync as Sf}from"node:child_process";import{existsSync as kT,readFileSync as RT}from"node:fs";import{homedir as xT}from"node:os";import{resolve as Ef}from"node:path";function Oi(t,e){return e.code==="ETIMEDOUT"?`${t} did not respond within lint's own spawn timeout (${e.message}) \u2014 this does not mean the provider itself is unreachable, only that this specific check didn't finish in time.`:`${t} could not be run: ${e.message}`}function m$(){let t=Sf("agy",["models"],{encoding:"utf-8",timeout:d$});return{status:t.status,stdout:t.stdout??"",error:t.error}}function f$(t){let e=[],n={};for(let r of t.split(/\r?\n/)){let s=r.trim(),i=s.indexOf(" ");if(i<0)continue;let o=s.slice(0,i).trim(),a=s.slice(i+1).trim();o&&(e.push(o),a&&(n[o]=a))}return{models:e,displayNames:n}}function AT(t){if(!t&&vf)return vf;let e=i=>(t||(vf=i),i),n;try{n=(t??p$??m$)()}catch(i){return e({available:!1,models:[],reason:i instanceof Error?Oi("agy models",i):`agy models could not be run: ${String(i)}`})}if(n.error)return e({available:!1,models:[],reason:Oi("agy models",n.error)});if(n.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${n.status??"unknown"}`});let{models:r,displayNames:s}=f$(n.stdout);return r.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:r,displayNames:s})}function h$(){let t=Sf("codex",["debug","models"],{encoding:"utf-8",timeout:g$});return{status:t.status,stdout:t.stdout??"",error:t.error}}function _$(t){let e;try{e=JSON.parse(t)}catch{return}let n=e.models;if(!Array.isArray(n))return;let r=[];for(let s of n){if(!s||typeof s!="object")continue;let{slug:i,visibility:o}=s;typeof i=="string"&&o==="list"&&r.push(i)}return r}function CT(t){if(!t&&bf)return bf;let e=s=>(t||(bf=s),s),n;try{n=(t??y$??h$)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Oi("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(n.error)return e({available:!1,models:[],reason:Oi("codex debug models",n.error)});if(n.status!==0)return e({available:!1,models:[],reason:`codex debug models exited with status ${n.status??"unknown"}`});let r=_$(n.stdout);return r===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):r.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:r})}function b$(t){let e=Sf("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:v$});return{status:e.status,stdout:e.stdout??"",error:e.error}}function w$(t,e){if(!e&&wf.has(t))return wf.get(t);let n=o=>(e||wf.set(t,o),o),r=t?`opencode models ${t}`:"opencode models",s;try{s=(e??b$)(t)}catch(o){return n({available:!1,models:[],reason:o instanceof Error?Oi(r,o):`${r} could not be run: ${String(o)}`})}if(s.error)return n({available:!1,models:[],reason:Oi(r,s.error)});if(s.status!==0)return n({available:!1,models:[],reason:`${r} exited with status ${s.status??"unknown"}`});let i=s.stdout.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0);return i.length===0?n({available:!1,models:[],reason:`${r} returned no models`}):n({available:!0,models:i})}function kf(t,e={}){let n=[];for(let r of t){let s=r.provider.trim().toLowerCase();if(r.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&s!=="muse"&&n.push(`[${r.alias}] effort="${r.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&r.effort&&n.push(`[${r.alias}] effort="${r.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),s==="copilot"){if(!r.model)continue;n.push(`[${r.alias}] model="${r.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(r.effort&&!r.model&&n.push(`[${r.alias}] effort="${r.effort}" has no effect without model= on an opencode member.`),!r.model)continue;let i=T$(e.opencodeConfigPath);if(!i.available){n.push(`[${r.alias}] model="${r.model}" cannot be verified for opencode: ${i.reason}.`);continue}if(i.models.includes(r.model)||/^github-copilot\/(gpt|gemini|o[0-9])/.test(r.model))continue;if(!r.model.includes("/")){let l=i.models.filter(c=>c.endsWith(`/${r.model}`));n.push(l.length>0?`[${r.alias}] model="${r.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model>. Your opencode.json declares it as ${l.join(" / ")}; set model=${l[0]}.`:`[${r.alias}] model="${r.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model> (e.g. github-copilot/${r.model}). Declare it in ~/.config/opencode/opencode.json (see https://lmctl.com/examples/opencode.json).`);continue}let o=r.model.slice(0,r.model.indexOf("/")),a=w$(o,e.opencodeModelsRunner);if(a.available&&a.models.includes(r.model))continue;if(a.available&&!a.models.includes(r.model)){n.push(`[${r.alias}] model="${r.model}" was not found in opencode's LOCALLY-VISIBLE live catalog for "${o}" (checked \`opencode models ${o}\`) -- this is unresolved, not a confirmed unavailability: it could mean opencode genuinely doesn't serve this model, OR that your local catalog/auth for "${o}" is stale/incomplete. Declaring it in opencode.json may or may not help; if it doesn't, check whether a non-opencode provider serves this model directly (e.g. \`lmctl lint\` with model= against provider=codex/claude/gemini/agy).`);continue}n.push(`[${r.alias}] model="${r.model}" is not declared in your opencode.json. opencode resolves github-copilot GPT/Gemini config-free, but copilot Claude and custom providers must be declared \u2014 copy https://lmctl.com/examples/opencode.json to ~/.config/opencode/opencode.json and adjust for your account.`);continue}if(s==="kimi"){if(!r.model)continue;let i=MT(e.kimiConfigPath);i.available?i.models.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not declared in Kimi's [models] config. Valid configured models: ${ua(i.models)}`):n.push(`[${r.alias}] model="${r.model}" cannot be verified for kimi: ${i.reason}.`);continue}if(s==="agy"){if(!r.model)continue;let i=AT(e.agyModelsRunner);i.available?i.models.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in agy's live model catalog (\`agy models\`). Valid models: ${ua(i.models)}`):n.push(`[${r.alias}] model="${r.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!r.model||zc.includes(r.model))continue;Kc.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in dsh's built-in catalog. Valid pinned models: ${ua(Kc)}. Valid server-resolved aliases (DeepSeek resolves these to its current model server-side -- pinning to a specific version instead is a DOWNGRADE, not a safer choice): ${ua(zc)}. The catalog is patchable via dsh profile overlays \u2014 a model added that way warns here even though it may resolve.`);continue}if(s==="hermes"){if(!r.model)continue;let i=r.model.indexOf(":");(i<=0||i===r.model.length-1)&&n.push(`[${r.alias}] model="${r.model}" should use <provider>:<model> from Hermes's ACP catalog. lmctl checks the shape only; provider and model availability are resolved by Hermes.`);continue}if(s!=="pi"){if(s==="codex"){if(!r.model)continue;r.model===ST&&n.push(`[${r.alias}] model="${ST}" is banned as a build model (operator, 2026-09-06) -- it's a fast/cheap classification model, not intended for build work, and there's no cost reason left to reach for it. Use model=gpt-5.6-sol (or leave model= unset) for build work; if this member genuinely does non-build/classification work, this warning can be ignored.`);let i=CT(e.codexModelsRunner);if(!i.available){n.push(`[${r.alias}] model="${r.model}" cannot be verified for codex: ${i.reason}.`);continue}i.models.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in codex's live model catalog (\`codex debug models\`). Valid models: ${ua(i.models)}`);continue}r.model&&(IT.has(s)||n.push(`[${r.alias}] model="${r.model}" cannot be verified for provider "${s}": no model validation path exists for this provider.`))}}}return n}async function NT(t,e={}){let n=t.filter(o=>o.model!==void 0&&IT.has(o.provider.trim().toLowerCase()));if(n.length===0)return{warnings:[],errors:[]};let r=e.snapshot??await As();if(r.catalog===null)return{warnings:[],errors:[]};let s=[],i=[];for(let o of n){let a=o.provider.trim().toLowerCase(),l=o.model,c=Ic(a,l,r.catalog,r.aliases);if(c.kind==="unknown"){let u=hE(r.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${u} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&u$.test(l)){let u=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${u}" instead.`)}}return{warnings:s,errors:i}}async function OT(t,e={}){return(await NT(t,e)).warnings}async function LT(t,e={}){return(await NT(t,e)).errors}function MT(t){let e=process.env.KIMI_CODE_HOME||Ef(xT(),".kimi-code"),n=t??Ef(e,"config.toml");if(!kT(n))return{available:!1,models:[],reason:`${n} not found`};let r;try{r=RT(n,"utf-8")}catch(i){return{available:!1,models:[],reason:`${n} could not be read: ${i instanceof Error?i.message:String(i)}`}}let s=new Set;for(let i of r.split(/\r?\n/)){if(/^\s*\[/.test(i)&&!/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.test(i))return{available:!1,models:[],reason:`${n} has an invalid TOML table header`};let o=/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(i);if(!o)continue;let a=E$(o[1]);if(o[1].trim().startsWith("models")&&a===null)return{available:!1,models:[],reason:`${n} has an invalid [models] table header`};a?.[0]==="models"&&a.length>=2&&s.add(a[1])}return s.size===0?{available:!1,models:[],reason:`${n} has no [models] entries`}:{available:!0,models:[...s]}}function E$(t){let e=[],n=0;for(;n<t.length;){for(;/\s/.test(t[n]??"");)n++;if(n>=t.length)break;let r="",s=t[n]==='"'||t[n]==="'"?t[n++]:void 0;if(s){for(;n<t.length&&t[n]!==s;)s==='"'&&t[n]==="\\"&&n+1<t.length&&n++,r+=t[n++];if(t[n]!==s)return null;n++}else{for(;n<t.length&&t[n]!==".";)r+=t[n++];r=r.trim()}if(!r)return null;for(e.push(r);/\s/.test(t[n]??"");)n++;if(n>=t.length)break;if(t[n]!==".")return null;n++}return e.length>0?e:null}function T$(t){let e=t??Ef(xT(),".config","opencode","opencode.json");if(!kT(e))return{available:!0,models:[]};let n;try{n=JSON.parse(RT(e,"utf-8"))}catch(r){return{available:!1,models:[],reason:`${e} could not be parsed: ${r instanceof Error?r.message:String(r)}`}}return{available:!0,models:S$(n)}}function S$(t){if(!Tf(t))return[];let e=Vc(t.provider)??Vc(t.providers);if(!e)return[];let n=new Set;for(let[r,s]of Object.entries(e)){if(!Tf(s))continue;let i=Vc(s.models)??Vc(s.model);if(i)for(let o of Object.keys(i))n.add(o.startsWith(`${r}/`)?o:`${r}/${o}`)}return[...n].sort()}function Vc(t){return Tf(t)?t:null}function Tf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ua(t){return t.length>0?t.join(", "):"(none)"}var IT,u$,Kc,zc,ST,d$,vf,p$,g$,bf,y$,v$,wf,Yc=L(()=>{"use strict";Cs();Ac();IT=new Set(Object.keys(ta).filter(t=>t!=="codex"&&t!=="kimi")),u$=/\d\.(?=\d)/,Kc=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],zc=["deepseek-flash","deepseek-pro"],ST="gpt-5.3-codex-spark",d$=15e3;vf=null;g$=5e3;bf=null;v$=5e3;wf=new Map});import*as PT from"node:child_process";function R$(t,e){try{let n=e(t,["--version"],{encoding:"utf-8",timeout:5e3});return n.status===0?{found:!0,version:(n.stdout??"").toString().trim().split(/\r?\n/,1)[0]?.trim()||void 0}:n.status===null?{found:!1,failureMode:"not installed"}:{found:!1,failureMode:"runs but failed"}}catch{return{found:!1,failureMode:"not installed"}}}function Rf(t,e={}){let n=e.spawnSync===void 0&&process.env[x$]==="1",r=e.spawnSync??PT.spawnSync,s=new Set,i=[];for(let o of t){if(s.has(o))continue;s.add(o);let a=DT[o];if(!a){i.push({provider:o,binary:"<unknown>",found:!1,failureMode:"not installed"});continue}if(n){i.push({provider:o,binary:a,found:!0,version:"(skipped)"});continue}let l=R$(a,r);l.found?i.push({provider:o,binary:a,found:!0,version:l.version}):i.push({provider:o,binary:a,found:!1,failureMode:l.failureMode})}return i}function FT(t){if(t.binary==="<unknown>")return`unknown provider "${t.provider}" \u2014 no binary mapping (allowed: ${Object.keys(DT).join(", ")})`;let e=k$[t.provider],n=e?` (install via ${e})`:"";return t.failureMode==="runs but failed"?`provider "${t.provider}" binary '${t.binary}' found but \`${t.binary} --version\` failed to run cleanly \u2014 check install integrity${n}`:`provider "${t.provider}" binary '${t.binary}' not installed${n}`}var DT,k$,x$,xf=L(()=>{"use strict";DT={claude:"claude",codex:"codex",copilot:"copilot",gemini:"gemini",opencode:"opencode",lmplayer:"lmplayer",qwen:"qwen",agy:"agy",kimi:"kimi",dsh:"dsh",hermes:"hermes",miniplayer:"miniplayer",muse:"muse",pi:"pi"},k$={claude:"https://docs.claude.com/code",codex:"https://github.com/openai/codex",copilot:"https://docs.github.com/copilot/cli",gemini:"https://github.com/google-gemini/gemini-cli",opencode:"https://opencode.ai",lmplayer:"Install lmplayer and ensure the lmplayer binary is on PATH.",qwen:"https://github.com/QwenLM/qwen-code",agy:"https://antigravity.google",kimi:"https://github.com/MoonshotAI/kimi-code",dsh:"https://github.com/deepseek-ai/deepseek-harness",hermes:"https://github.com/NousResearch/hermes-agent",pi:"https://github.com/badlogic/pi-mono"};x$="LMCTL_SKIP_BINARY_CHECK"});var $T=L(()=>{"use strict";xm();hf();Jc();Jc();TT();Yc();Cs();xf()});import{resolve as I$,join as jT}from"node:path";function If(t,e={}){try{if(!Ci(t))return H("invalid_argument","Expected a context created by createLmctlContext");if(t.closed)return H("cancelled","Context is closed");if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Profile options must be a map");let n=e.path;if(Object.keys(e).some(i=>!(ht.find(o=>o.name==="loadProfile")?.params.find(o=>o.name==="options")?.keys??[]).some(o=>o.name===i))||n!==void 0&&(typeof n!="string"||!n))return H("invalid_argument","Profile options accept a nonempty path string only");let r=t.env.LMCTL_HOME||(t.env.HOME?jT(t.env.HOME,".lmctl"):void 0);if(!n&&!r)return H("invalid_argument","Profile path requires HOME, LMCTL_HOME or an explicit path");let s=I$(t.cwd,n??jT(r,"init.toml"));return ge({path:Ni({...t.env,HOME:t.env.HOME??t.cwd},s)})}catch(n){return H("invalid_argument","Invalid profile arguments: "+V(n))}}function A$(t){try{if(!t||typeof t!="object"||Array.isArray(t))return H("invalid_argument","Expected a validated InitConfig");let e={};for(let n of["provider1","provider2","provider3"]){let r=t[n];if(!r||typeof r!="object"||Array.isArray(r))return H("invalid_argument",n+" must be a provider map");let s={};for(let i of["provider","model1"]){let o=r[i];if(typeof o!="string"||!o.trim())return H("invalid_argument",n+"."+i+" must be a nonempty string");s[i]=o}e[n]=s}return ge(Wc(e))}catch(e){return H("invalid_argument","Invalid profile: "+V(e))}}function C$(t,e={}){let n=If(t,e);if(n.status==="error")return n;try{let r=Gc(n.path);return ge({profile:{path:r.path,raw:r.raw,config:r.config},values:{...Wc(r.config),Directory:t.cwd,NonInteractive:!t.interactive}})}catch(r){return r instanceof Wt?H(r.kind,r.message,{path:r.path,line:r.line,column:r.column}):H("read","Could not load profile: "+V(r),{path:n.path})}}function N$(t,e={}){let n=If(t,e);if(n.status==="error")return n;try{let r=_f(n.path),{properties:s,flat:i}=_T(r.document);return ge({path:r.path,properties:s,flat:i})}catch(r){return r instanceof Wt?H(r.kind,r.message,{path:r.path,line:r.line,column:r.column}):H("schema","Invalid properties in "+n.path+": "+V(r)+". Fix the file or run lmctl init.",{path:n.path})}}var UT=L(()=>{"use strict";vT();zn();$T();hf();en();yt()});function Tn(t){return t!=="gemini"}function Qc(t){if(!Tn(t))throw new Error(Hr)}var Hr,Li=L(()=>{"use strict";Hr="Standalone Gemini CLI support is disabled; use provider=agy with an Agy-supported Gemini model."});function BT(t){if(t.length===0||!t.startsWith("---"))throw new Sn("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
2211
2212
|
`);if(e[0]!=="---")throw new Sn("frontmatter must start at line 1 with `---` on its own line");let n={},r=-1;for(let o=1;o<e.length;o++){let a=e[o];if(a==="---"){r=o;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new Sn(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!O$.has(c))throw new Sn(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Zc.join(", ")}`);n[c]=u}if(r===-1)throw new Sn("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Zc)if(n[o]===void 0)throw new Sn(`missing required frontmatter key "${o}" \u2014 required: ${Zc.join(", ")}`);let s=0;for(let o=0;o<=r;o++)s+=e[o].length+1;s>t.length&&(s=t.length);let i=n.members.split(",").map(o=>o.trim()).filter(Boolean);return{title:n.title,description:n.description,members:i,bodyOffset:s}}var Zc,O$,Sn,HT=L(()=>{"use strict";Zc=["title","description","members"],O$=new Set(Zc),Sn=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});function Cf(t){return Af.has(t)}var Af,eu=L(()=>{"use strict";Af=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","miniplayer","muse","ClaudeMock"])});import{readFileSync as L$,writeFileSync as B3,renameSync as H3,existsSync as qT}from"node:fs";import{basename as M$,resolve as Mi,dirname as Nf}from"node:path";function P$(t){let e={},n=/(\w+)=(?:"([^"]*)"|([\S]*))/g,r;for(;(r=n.exec(t))!==null;){let s=r[1],i=r[2]!==void 0?r[2]:r[3];e[s]=i}return e}function D$(t){return/^\s*_MEMBER_\s+\S/.test(t)}function F$(t){return/^\s*_SESSION_\s+\S/.test(t)}function $$(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function da(t){return/\.(?:lmctl|lmc)$/i.test(t)}function ma(t){return M$(t).replace(/\.(?:lmctl|lmc)$/i,"")}function qt(t){let e=L$(t,"utf-8"),n=Nf(Mi(t)),r=Lf(e,ma(t),{baseDir:n,sourcePath:Mi(t)});for(let s of r.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Mi(n,s.sessiondir));return r}function Lf(t,e,n={}){let r=[],s=[];n.sourcePath,n.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
2212
2213
|
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=BT(i)}catch(l){if(l instanceof Sn)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
2213
2214
|
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(F$(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if($$(c)||!D$(c))continue;let d=P$(c);for(let p of Object.keys(d))if(!WT.includes(p))throw new Error(`line ${u}: unknown key "${p}" on _MEMBER_ line: ${c.trim()}
|
|
@@ -2222,7 +2223,7 @@ ${u}`)}`}bt.renderGrid=lS;function cS(t,{headers:e,align:n,truncate:r,truncateTr
|
|
|
2222
2223
|
`?"\\n":n===" "?"\\t":n==="\r"?"\\r":`\\x${n.codePointAt(0).toString(16).padStart(2,"0")}`)}bt.escapeCell=mj});function tn(t){let e=t.env?.LMCTL_DB;return e!==void 0&&e.length>0?e:Ai(void 0,{...process.env,...t.env})}async function ye(t,e){if(t.dal!==void 0)return e(t.dal);let n=ut({path:tn(t)});try{return await e(n)}finally{n.close()}}function Gf(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
2223
2224
|
`)}function sr(t,e){return t.stderr.write(`error: ${e}
|
|
2224
2225
|
`),1}function mS(t,e,n=5e3){let r=Date.now(),s=r,i=setInterval(()=>{let o=Date.now();o-s<n||t.stderr.write(e(Math.round((o-r)/1e3)))},n);return i.unref(),{poke:()=>{s=Date.now()},stop:()=>clearInterval(i)}}function pS(t,e){let n=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${n}
|
|
2225
|
-
`),2}function ou(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var pj,ir=L(()=>{"use strict";Zt();pj=tm(iu(),1);Hc()});import{openSync as fj,closeSync as gj,fstatSync as hj,readSync as yj,constants as fS}from"node:fs";import{dirname as _j,join as au}from"node:path";import{createHash as vj}from"node:crypto";function Kf(t){if(!xs(t.catalog)||!Is(t.aliases)||!t.sha256||!/^[a-f0-9]{64}$/.test(t.sha256))throw Error("invalid or incomplete price snapshot (catalog, aliases and SHA-256 required)");if(!["network","cache","bundled","pinned"].includes(t.source)||t.generatedAt!==null&&typeof t.generatedAt!="string")throw Error("invalid price snapshot metadata");if(t.catalog.records.length>1e5||t.aliases.aliases.length>1e5||t.aliases.standards.length>1e5)throw Error("price snapshot exceeds the 100000-entry limit");let e=i=>{if(i.length>65536)throw Error("price identity exceeds the 65536-character limit")},n=new Set,r=new Set,s=new Set;for(let i of t.catalog.records){let o=_S(i);if(!o||n.has(o))throw Error("duplicate or missing price record id");n.add(o),e(o),e(i.source),e(i.source_model_id);for(let u of[i.source,i.source_model_id])if(typeof u!="string"||!u.trim())throw Error("invalid price record identity");let a=i;for(let u of[i.provider,i.mode,i.gateway_id,i.record_id,a.vendor_model_id,a.canonical_slug])if(u!=null&&typeof u!="string")throw Error("invalid price record metadata");for(let u of[i.pricing.input_per_1m_tokens,i.pricing.output_per_1m_tokens,i.pricing.input_cache_read_per_1m_tokens,i.pricing.input_cache_write_per_1m_tokens??null])if(!gS(u))throw Error("price rates must be finite nonnegative numbers or null");let l=i.pricing.source_cost_fields;if(l!=null&&(typeof l!="object"||Array.isArray(l)))throw Error("invalid source cost fields");for(let u of["cache_creation_input_token_cost","cache_creation_input_token_cost_above_1hr"])if(l?.[u]!==void 0&&!gS(l[u]))throw Error("source blend rates must be finite nonnegative numbers or null");let c=i.pricing.currency;if(c!=null&&c!=="USD")throw Error("price currency must be USD")}for(let i of t.aliases.standards){e(i.standard_slug),i.catalog_record_id!==null&&e(i.catalog_record_id);let o=i.standard_slug.toLowerCase();if(!o||r.has(o))throw Error("duplicate price standard");r.add(o)}for(let i of t.aliases.aliases){e(i.alias),i.standard_slug!==null&&e(i.standard_slug);let o=i.alias.toLowerCase();if(!o||s.has(o))throw Error("duplicate price alias");if(s.add(o),i.standard_slug!==null&&!r.has(i.standard_slug.toLowerCase()))throw Error("price alias references missing standard")}}function hS(t){let e=fj(t,fS.O_RDONLY|fS.O_NONBLOCK);try{let n=hj(e);if(!n.isFile()||n.size>bj)throw Error("price file must be a regular file within the 64 MiB size limit");let r=Buffer.alloc(n.size+1),s=0;for(;s<r.length;){let i=yj(e,r,s,r.length-s,null);if(i===0)break;s+=i}if(s!==n.size)throw Error("price file changed while reading; retry with a complete file");return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(r.subarray(0,s))}finally{gj(e)}}function wj(t,e=au(_j(t),"aliases.json")){let n=hS(t),r=hS(e),s;try{s=yS(n)}catch{s=null}if(!s||!("records"in Object(s))){let a=n.trim().split(/\r?\n/).filter(c=>c.trim()).map(c=>JSON.parse(c)),l=a[0]?.schema_version!==void 0&&a[0]?.pricing===void 0&&a[0]?.source_model_id===void 0?a.shift():{};s={schema_version:l.schema_version??1,generated_at:l.generated_at??"",records:a}}let i=yS(r),o={catalog:s,aliases:i,source:"pinned",generatedAt:s?.generated_at||null,sha256:vj("sha256").update(n).update(r).digest("hex")};return Kf(o),o}function Vf(t){let e=t.pragma("busy_timeout",{simple:!0});try{return t.pragma("busy_timeout = 0"),t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='price_snapshot'").get()?t.transaction(()=>{let n=t.prepare("SELECT * FROM price_snapshot").get();if(!n)return null;let r=t.prepare("SELECT * FROM price_record ORDER BY ordinal").all().map(o=>{if(typeof o.record_id!="string"||!o.record_id||o.currency!=="USD"||o.unit!=="per_1m_tokens")throw Error("invalid stored price identity, currency or unit");let a=JSON.parse(o.record_json);return{...a,record_id:o.record_id,pricing:{...a.pricing,input_per_1m_tokens:o.input_1m,output_per_1m_tokens:o.output_1m,input_cache_read_per_1m_tokens:o.cache_read_1m,input_cache_write_per_1m_tokens:o.cache_write_1m,source_cost_fields:JSON.parse(o.source_cost_fields??"{}")}}});if(r.length!==n.record_count)throw Error("incomplete stored price snapshot");let s=t.prepare("SELECT alias,standard_slug,evidence FROM price_alias ORDER BY alias").all(),i={catalog:{schema_version:1,generated_at:n.generated_at??"",records:r},aliases:{schema_version:1,standards:JSON.parse(n.standards_json),aliases:s},source:n.source,generatedAt:n.generated_at,sha256:n.sha256,fetchedAt:n.fetched_at,loadedAt:n.loaded_at,recordCount:n.record_count};return Kf(i),i})():null}finally{t.pragma("busy_timeout = "+e)}}function Ej(t,e,n={}){Kf(e);let r=()=>t.prepare("SELECT sha256 FROM price_snapshot").get()?.sha256===e.sha256,s=t.pragma("busy_timeout",{simple:!0});try{return t.pragma("busy_timeout = 0"),r()?"unchanged":t.transaction(()=>{if(r())return"unchanged";t.exec("DELETE FROM price_alias; DELETE FROM price_record; DELETE FROM price_snapshot;");let i=t.prepare("INSERT INTO price_record(record_id,source,provider,source_model_id,vendor_model_id,canonical_slug,currency,unit,input_1m,output_1m,cache_read_1m,cache_write_1m,source_cost_fields,record_json,ordinal) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");e.catalog.records.forEach((c,u)=>{let d=c;i.run(_S(c),c.source,c.provider??null,c.source_model_id,d.vendor_model_id??null,d.canonical_slug??null,"USD","per_1m_tokens",c.pricing.input_per_1m_tokens,c.pricing.output_per_1m_tokens,c.pricing.input_cache_read_per_1m_tokens,c.pricing.input_cache_write_per_1m_tokens??null,JSON.stringify(c.pricing.source_cost_fields??{}),JSON.stringify(c),u)});let o=t.prepare("INSERT INTO price_alias(alias,standard_slug,evidence,catalog_record_id) VALUES(?,?,?,?)"),a=new Map(e.aliases.standards.map(c=>[c.standard_slug.toLowerCase(),c]));for(let c of e.aliases.aliases){let u=a.get(c.standard_slug?.toLowerCase()??"");o.run(c.alias.toLowerCase(),c.standard_slug,c.evidence,u?.catalog_record_id??null)}let l=new Date(n.now??Date.now()).toISOString();return t.prepare("INSERT INTO price_snapshot(sha256,generated_at,source,fetched_at,loaded_at,record_count,standards_json) VALUES(?,?,?,?,?,?,?)").run(e.sha256,e.generatedAt,e.source,l,l,e.catalog.records.length,JSON.stringify(e.aliases.standards)),"updated"}).immediate()}catch(i){if(/^SQLITE_(BUSY|LOCKED|READONLY)(_|$)/.test(String(i?.code)))return"deferred";throw i}finally{t.pragma("busy_timeout = "+s)}}async function Tj(t,e={}){let n=e.now??Date.now(),r={...process.env,...e.env},s=Vf(t),i=Jf.get(t),o=i&&i.hash===s?.sha256?i.at:Date.parse(s?.fetchedAt??"");if(!e.force&&s&&n>=o&&n-o<kc(r))return{status:"unchanged",snapshot:s};let a=e.load??(()=>r.LMCTL_PRICE_DATA?Promise.resolve(wj(au(r.LMCTL_PRICE_DATA,"model_list.json"))):As({cacheDir:r.LMCTL_HOME?au(r.LMCTL_HOME,"cache","lmprice"):r.HOME?au(r.HOME,".lmctl","cache","lmprice"):void 0,ttlMs:e.force?0:kc(r)})),l,c;try{c=await(e.budgetMs===void 0?a():Promise.race([a(),new Promise(m=>{l=setTimeout(()=>m(null),e.budgetMs)})]))}finally{clearTimeout(l)}if(Jf.set(t,{hash:s?.sha256??null,at:n}),!c?.catalog||!c.aliases||!c.sha256||c.refreshFailed&&(s||c.source!=="bundled"))return{status:"unavailable",snapshot:s};let u=Ej(t,c,{now:n}),d=Vf(t);return Jf.set(t,{hash:d?.sha256??null,at:n}),{status:u,snapshot:d}}async function lu(t,e){try{return(await Tj(t,{env:e,budgetMs:900})).snapshot??pa}catch(n){if(/^SQLITE_(BUSY|LOCKED)(_|$)/.test(String(n?.code)))return pa;try{return Vf(t)??pa}catch{return pa}}}async function zf(t){if(t.dal)return lu(t.dal.db,t.env);let e;try{return e=ut({path:tn(t),recover:!1}),await lu(e.db,t.env)}catch{return pa}finally{try{e?.close()}catch{}}}var pa,_S,gS,bj,yS,Jf,Yf=L(()=>{"use strict";Cs();Zt();ir();pa={catalog:null,aliases:null,source:"unavailable",generatedAt:null,sha256:null},_S=t=>t.record_id??t.source+":"+t.source_model_id,gS=t=>t===null||typeof t=="number"&&Number.isFinite(t)&&t>=0;bj=64*1024*1024;yS=t=>JSON.parse(t.replace(/^\uFEFF/,""));Jf=new WeakMap});function or(t){try{return t?.usage}catch{return}}function fa(t,e,n,r){let s,i,o,a=!1;try{o=Cc(e),s=t.dal??ut({path:tn(t),recover:!1}),i=s.insertDirectTurn(o,n,r)}catch{}return{async finish(l){if(!a){a=!0;try{s&&i!==void 0&&o&&s.finishDirectTurn(i,await na(o,l,()=>lu(s.db,t.env),{db:s.db,env:t.env}))}catch{}finally{if(s&&s!==t.dal)try{s.close()}catch{}}}}}}function ga(t,e,n){let r=t,s,i;s=or(r)??or(n);try{i=r?.sessionId??n?.sessionId}catch{i=n?.sessionId}return{status:Ti(G(t),e.aborted),usage:s,sessionId:i}}var Qf=L(()=>{"use strict";Zt();ir();Yf();ra();yt()});function js(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var cu=L(()=>{"use strict"});import{randomUUID as Sj}from"node:crypto";import{chmodSync as vS,mkdirSync as kj,readdirSync as Rj,statSync as xj,unlinkSync as Ij,writeFileSync as Aj}from"node:fs";import{homedir as Cj,tmpdir as Nj}from"node:os";import{join as ha}from"node:path";function $j(t){return js(t.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g,"")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"\uFFFD")}function ya(t){return $j(t).replace(/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g,"[REDACTED_PRIVATE_KEY]").replace(/\b((?:set-)?cookie\s*:[ \t]*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b([a-z][a-z0-9+.-]*:\/\/[^\s/:@]*):[^\s/@]+@/gi,"$1:[REDACTED]@").replace(/\bBearer\s+(?=[A-Za-z0-9._~+/-]{12,}\b)(?=[A-Za-z0-9._~+/-]*[0-9._~+/-])[A-Za-z0-9._~+/-]{12,}/gi,"Bearer [REDACTED]").replace(Fj,"$1[REDACTED]").replace(/\b((?:[A-Z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)(?:_[A-Z0-9]+)*=)(?!\[REDACTED\])(?:"[^"]*"|'[^']*'|[^\s,;]+)/g,"$1[REDACTED]").replace(/([?&](?:key|sig|signature)=)[^&\s'"]+/gi,"$1[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED_SECRET]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abeprs]-[A-Za-z0-9-]{10,})/g,"[REDACTED_SECRET]").replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g,"[REDACTED_SECRET]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED_SECRET]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,"[REDACTED_JWT]")}function jj(){let t=process.env.LMCTL_HOME||(process.env.NODE_ENV==="test"?ha(Nj(),`lmctl-test-${process.pid}`,".lmctl"):ha(process.env.HOME||Cj(),".lmctl"));return ha(t,"provider-errors")}function Uj(t,e,n){if(t.length<=e)return t;let r=Math.floor(e*.2),s=e-r,i=t.length-e;return`${t.slice(0,r)}
|
|
2226
|
+
`),2}function ou(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var pj,ir=L(()=>{"use strict";Zt();pj=tm(iu(),1);Hc()});import{openSync as fj,closeSync as gj,fstatSync as hj,readSync as yj,constants as fS}from"node:fs";import{dirname as _j,join as au}from"node:path";import{createHash as vj}from"node:crypto";function Kf(t){if(!xs(t.catalog)||!Is(t.aliases)||!t.sha256||!/^[a-f0-9]{64}$/.test(t.sha256))throw Error("invalid or incomplete price snapshot (catalog, aliases and SHA-256 required)");if(!["network","cache","bundled","pinned"].includes(t.source)||t.generatedAt!==null&&typeof t.generatedAt!="string")throw Error("invalid price snapshot metadata");if(t.catalog.records.length>1e5||t.aliases.aliases.length>1e5||t.aliases.standards.length>1e5)throw Error("price snapshot exceeds the 100000-entry limit");let e=i=>{if(i.length>65536)throw Error("price identity exceeds the 65536-character limit")},n=new Set,r=new Set,s=new Set;for(let i of t.catalog.records){let o=_S(i);if(!o||n.has(o))throw Error("duplicate or missing price record id");n.add(o),e(o),e(i.source),e(i.source_model_id);for(let u of[i.source,i.source_model_id])if(typeof u!="string"||!u.trim())throw Error("invalid price record identity");let a=i;for(let u of[i.provider,i.mode,i.gateway_id,i.record_id,a.vendor_model_id,a.canonical_slug])if(u!=null&&typeof u!="string")throw Error("invalid price record metadata");for(let u of[i.pricing.input_per_1m_tokens,i.pricing.output_per_1m_tokens,i.pricing.input_cache_read_per_1m_tokens,i.pricing.input_cache_write_per_1m_tokens??null])if(!gS(u))throw Error("price rates must be finite nonnegative numbers or null");let l=i.pricing.source_cost_fields;if(l!=null&&(typeof l!="object"||Array.isArray(l)))throw Error("invalid source cost fields");for(let u of["cache_creation_input_token_cost","cache_creation_input_token_cost_above_1hr"])if(l?.[u]!==void 0&&!gS(l[u]))throw Error("source blend rates must be finite nonnegative numbers or null");let c=i.pricing.currency;if(c!=null&&c!=="USD")throw Error("price currency must be USD")}for(let i of t.aliases.standards){e(i.standard_slug),i.catalog_record_id!==null&&e(i.catalog_record_id);let o=i.standard_slug.toLowerCase();if(!o||r.has(o))throw Error("duplicate price standard");r.add(o)}for(let i of t.aliases.aliases){e(i.alias),i.standard_slug!==null&&e(i.standard_slug);let o=i.alias.toLowerCase();if(!o||s.has(o))throw Error("duplicate price alias");if(s.add(o),i.standard_slug!==null&&!r.has(i.standard_slug.toLowerCase()))throw Error("price alias references missing standard")}}function hS(t){let e=fj(t,fS.O_RDONLY|fS.O_NONBLOCK);try{let n=hj(e);if(!n.isFile()||n.size>bj)throw Error("price file must be a regular file within the 64 MiB size limit");let r=Buffer.alloc(n.size+1),s=0;for(;s<r.length;){let i=yj(e,r,s,r.length-s,null);if(i===0)break;s+=i}if(s!==n.size)throw Error("price file changed while reading; retry with a complete file");return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(r.subarray(0,s))}finally{gj(e)}}function wj(t,e=au(_j(t),"aliases.json")){let n=hS(t),r=hS(e),s;try{s=yS(n)}catch{s=null}if(!s||!("records"in Object(s))){let a=n.trim().split(/\r?\n/).filter(c=>c.trim()).map(c=>JSON.parse(c)),l=a[0]?.schema_version!==void 0&&a[0]?.pricing===void 0&&a[0]?.source_model_id===void 0?a.shift():{};s={schema_version:l.schema_version??1,generated_at:l.generated_at??"",records:a}}let i=yS(r),o={catalog:s,aliases:i,source:"pinned",generatedAt:s?.generated_at||null,sha256:vj("sha256").update(n).update(r).digest("hex")};return Kf(o),o}function Vf(t){let e=t.pragma("busy_timeout",{simple:!0});try{return t.pragma("busy_timeout = 0"),t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='price_snapshot'").get()?t.transaction(()=>{let n=t.prepare("SELECT * FROM price_snapshot").get();if(!n)return null;let r=t.prepare("SELECT * FROM price_record ORDER BY ordinal").all().map(o=>{if(typeof o.record_id!="string"||!o.record_id||o.currency!=="USD"||o.unit!=="per_1m_tokens")throw Error("invalid stored price identity, currency or unit");let a=JSON.parse(o.record_json);return{...a,record_id:o.record_id,pricing:{...a.pricing,input_per_1m_tokens:o.input_1m,output_per_1m_tokens:o.output_1m,input_cache_read_per_1m_tokens:o.cache_read_1m,input_cache_write_per_1m_tokens:o.cache_write_1m,source_cost_fields:JSON.parse(o.source_cost_fields??"{}")}}});if(r.length!==n.record_count)throw Error("incomplete stored price snapshot");let s=t.prepare("SELECT alias,standard_slug,evidence FROM price_alias ORDER BY alias").all(),i={catalog:{schema_version:1,generated_at:n.generated_at??"",records:r},aliases:{schema_version:1,standards:JSON.parse(n.standards_json),aliases:s},source:n.source,generatedAt:n.generated_at,sha256:n.sha256,fetchedAt:n.fetched_at,loadedAt:n.loaded_at,recordCount:n.record_count};return Kf(i),i})():null}finally{t.pragma("busy_timeout = "+e)}}function Ej(t,e,n={}){Kf(e);let r=()=>t.prepare("SELECT sha256 FROM price_snapshot").get()?.sha256===e.sha256,s=t.pragma("busy_timeout",{simple:!0});try{return t.pragma("busy_timeout = 0"),r()?"unchanged":t.transaction(()=>{if(r())return"unchanged";t.exec("DELETE FROM price_alias; DELETE FROM price_record; DELETE FROM price_snapshot;");let i=t.prepare("INSERT INTO price_record(record_id,source,provider,source_model_id,vendor_model_id,canonical_slug,currency,unit,input_1m,output_1m,cache_read_1m,cache_write_1m,source_cost_fields,record_json,ordinal) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");e.catalog.records.forEach((c,u)=>{let d=c;i.run(_S(c),c.source,c.provider??null,c.source_model_id,d.vendor_model_id??null,d.canonical_slug??null,"USD","per_1m_tokens",c.pricing.input_per_1m_tokens,c.pricing.output_per_1m_tokens,c.pricing.input_cache_read_per_1m_tokens,c.pricing.input_cache_write_per_1m_tokens??null,JSON.stringify(c.pricing.source_cost_fields??{}),JSON.stringify(c),u)});let o=t.prepare("INSERT INTO price_alias(alias,standard_slug,evidence,catalog_record_id) VALUES(?,?,?,?)"),a=new Map(e.aliases.standards.map(c=>[c.standard_slug.toLowerCase(),c]));for(let c of e.aliases.aliases){let u=a.get(c.standard_slug?.toLowerCase()??"");o.run(c.alias.toLowerCase(),c.standard_slug,c.evidence,u?.catalog_record_id??null)}let l=new Date(n.now??Date.now()).toISOString();return t.prepare("INSERT INTO price_snapshot(sha256,generated_at,source,fetched_at,loaded_at,record_count,standards_json) VALUES(?,?,?,?,?,?,?)").run(e.sha256,e.generatedAt,e.source,l,l,e.catalog.records.length,JSON.stringify(e.aliases.standards)),"updated"}).immediate()}catch(i){if(/^SQLITE_(BUSY|LOCKED|READONLY)(_|$)/.test(String(i?.code)))return"deferred";throw i}finally{t.pragma("busy_timeout = "+s)}}async function Tj(t,e={}){let n=e.now??Date.now(),r={...process.env,...e.env},s=Vf(t),i=Jf.get(t),o=i&&i.hash===s?.sha256?i.at:Date.parse(s?.fetchedAt??"");if(!e.force&&s&&n>=o&&n-o<kc(r))return{status:"unchanged",snapshot:s};let a=e.load??(()=>r.LMCTL_PRICE_DATA?Promise.resolve(wj(au(r.LMCTL_PRICE_DATA,"model_list.json"))):As({cacheDir:r.LMCTL_HOME?au(r.LMCTL_HOME,"cache","lmprice"):r.HOME?au(r.HOME,".lmctl","cache","lmprice"):void 0,ttlMs:e.force?0:kc(r)})),l,c;try{c=await(e.budgetMs===void 0?a():Promise.race([a(),new Promise(m=>{l=setTimeout(()=>m(null),e.budgetMs)})]))}finally{clearTimeout(l)}if(Jf.set(t,{hash:s?.sha256??null,at:n}),!c?.catalog||!c.aliases||!c.sha256||c.refreshFailed&&(s||c.source!=="bundled"))return{status:"unavailable",snapshot:s};let u=Ej(t,c,{now:n}),d=Vf(t);return Jf.set(t,{hash:d?.sha256??null,at:n}),{status:u,snapshot:d}}async function lu(t,e){try{return(await Tj(t,{env:e,budgetMs:900})).snapshot??pa}catch(n){if(/^SQLITE_(BUSY|LOCKED)(_|$)/.test(String(n?.code)))return pa;try{return Vf(t)??pa}catch{return pa}}}async function zf(t){if(t.dal)return lu(t.dal.db,t.env);let e;try{return e=ut({path:tn(t),recover:!1}),await lu(e.db,t.env)}catch{return pa}finally{try{e?.close()}catch{}}}var pa,_S,gS,bj,yS,Jf,Yf=L(()=>{"use strict";Cs();Zt();ir();pa={catalog:null,aliases:null,source:"unavailable",generatedAt:null,sha256:null},_S=t=>t.record_id??t.source+":"+t.source_model_id,gS=t=>t===null||typeof t=="number"&&Number.isFinite(t)&&t>=0;bj=64*1024*1024;yS=t=>JSON.parse(t.replace(/^\uFEFF/,""));Jf=new WeakMap});function or(t){try{return t?.usage}catch{return}}function fa(t,e,n,r){let s,i,o,a=!1;try{o=Cc(e),s=t.dal??ut({path:tn(t),recover:!1}),i=s.insertDirectTurn(o,n,r)}catch{}return{async finish(l){if(!a){a=!0;try{s&&i!==void 0&&o&&s.finishDirectTurn(i,await na(o,l,()=>lu(s.db,t.env),{db:s.db,env:t.env}))}catch{}finally{if(s&&s!==t.dal)try{s.close()}catch{}}}}}}function ga(t,e,n){let r=t,s,i;s=or(r)??or(n);try{i=r?.sessionId??n?.sessionId}catch{i=n?.sessionId}return{status:Ti(V(t),e.aborted),usage:s,sessionId:i}}var Qf=L(()=>{"use strict";Zt();ir();Yf();ra();yt()});function js(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var cu=L(()=>{"use strict"});import{randomUUID as Sj}from"node:crypto";import{chmodSync as vS,mkdirSync as kj,readdirSync as Rj,statSync as xj,unlinkSync as Ij,writeFileSync as Aj}from"node:fs";import{homedir as Cj,tmpdir as Nj}from"node:os";import{join as ha}from"node:path";function $j(t){return js(t.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g,"")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"\uFFFD")}function ya(t){return $j(t).replace(/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g,"[REDACTED_PRIVATE_KEY]").replace(/\b((?:set-)?cookie\s*:[ \t]*)[^\r\n]+/gi,"$1[REDACTED]").replace(/\b([a-z][a-z0-9+.-]*:\/\/[^\s/:@]*):[^\s/@]+@/gi,"$1:[REDACTED]@").replace(/\bBearer\s+(?=[A-Za-z0-9._~+/-]{12,}\b)(?=[A-Za-z0-9._~+/-]*[0-9._~+/-])[A-Za-z0-9._~+/-]{12,}/gi,"Bearer [REDACTED]").replace(Fj,"$1[REDACTED]").replace(/\b((?:[A-Z0-9]+_)*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?)(?:_[A-Z0-9]+)*=)(?!\[REDACTED\])(?:"[^"]*"|'[^']*'|[^\s,;]+)/g,"$1[REDACTED]").replace(/([?&](?:key|sig|signature)=)[^&\s'"]+/gi,"$1[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED_SECRET]").replace(/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{16,}|xox[abeprs]-[A-Za-z0-9-]{10,})/g,"[REDACTED_SECRET]").replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g,"[REDACTED_SECRET]").replace(/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED_SECRET]").replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g,"[REDACTED_JWT]")}function jj(){let t=process.env.LMCTL_HOME||(process.env.NODE_ENV==="test"?ha(Nj(),`lmctl-test-${process.pid}`,".lmctl"):ha(process.env.HOME||Cj(),".lmctl"));return ha(t,"provider-errors")}function Uj(t,e,n){if(t.length<=e)return t;let r=Math.floor(e*.2),s=e-r,i=t.length-e;return`${t.slice(0,r)}
|
|
2226
2227
|
\u2026 ${i} characters of ${n} \u2026
|
|
2227
2228
|
${t.slice(-s)}`}function Bj(t,e){try{let n=Rj(t).filter(s=>Dj.test(s)).sort().map(s=>{let i=ha(t,s);return{path:i,size:xj(i).size}}),r=n.reduce((s,i)=>s+i.size,0);for(let s=0;s<n.length&&(n.length-s>Mj||r>Pj);s++){let i=n[s];i.path!==e&&(Ij(i.path),r-=i.size)}}catch{}}function Hj(t,e){let n=jj(),r=ha(n,`stderr-${Date.now()}-${process.pid}-${Sj()}.log`);try{kj(n,{recursive:!0,mode:448}),vS(n,448);let s=`[${new Date().toISOString()}] provider=${e}
|
|
2228
2229
|
${Uj(t,Lj,"provider output not saved")}
|
|
@@ -2268,7 +2269,7 @@ One possible cause: the provider process failed before a complete ACP response w
|
|
|
2268
2269
|
${Me(e,{provider:t.tool,...t.fullOutput===void 0?{}:{fullOutput:t.fullOutput}})}
|
|
2269
2270
|
|
|
2270
2271
|
${n}`:n}function VU(t,e){return Aa(t)?.filterExpectedStderr?.(e)??e}function nk(t){if(t.method!=="session/update")return!1;let n=t.params?.update;if(n===void 0)return!1;let r=n.sessionUpdate;if(r!=="tool_call"&&r!=="tool_call_update")return!1;let s=n.status;return s!==void 0&&s!=="pending"&&s!=="in_progress"?!1:n.rawInput?.background===!0}async function rk(t,e,n,r){for(let s of t.sessionSetup??[]){let i={...e,sessionId:n.sessionId,response:n.response,sendRpc:r};if(s.applies(i))try{await s.run(i),s.successLog&&Qe(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(X({event:a.event,provider:t.name,...a.fields}),a.stderrLine&&process.stderr.write(a.stderrLine),a.warning&&e.warnings.push(a.warning),s.onFailure==="fail-closed")throw new Error(a.message)}}}function sk(t,e,n){let r=He(e.env,e.cwd,e.sessionId);t.preSpawn?.({...n,cwd:e.cwd,env:r});let s=e.binaryPath||t.binary,i=t.argv(n),o=t.yoloAssertion==="always-yolo"?"yolo":n.permissionMode;if(Ge(e.tool,i,o),e.cwd&&!GU(e.cwd))throw X({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new Ne(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:r}}async function ik(t){let{sendRpc:e,sendNotification:n,opts:r,outputProcessor:s}=t,i=t.strictSessionIdentity===!0,o=await e("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}});n("notifications/initialized");let a=r.sessionId||"",l;if(r.sessionId){let c;try{if(o.result?.agentCapabilities?.loadSession===!1)throw new Error("provider advertises loadSession=false");c=await e("session/load",{sessionId:r.sessionId,cwd:r.cwd,mcpServers:[]})}catch(d){if(i||r.requireResume)throw new Error(`Cannot resume session ${r.sessionId} via ACP: ${d instanceof Error?d.message:String(d)}`);process.stderr.write(`[acp] session/load failed for ${r.sessionId}, creating new session
|
|
2271
|
-
`),X({event:"acp_session_resume_fallback",provider:r.tool,session_id:r.sessionId,error_message:d instanceof Error?d.message:String(d)});let m=await e("session/new",{cwd:r.cwd,mcpServers:[]});return a=lr(m),s.setSessionId(a),{sessionId:a,sessionResponse:m}}let u=lr(c);if(r.requireResume&&u!==""&&u!==r.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${r.sessionId}", received "${u}"`);if(i){let d=lr(c);if(d!==""&&d!==r.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${r.sessionId}", received "${d}"`);if(d===""){if(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${r.sessionId}", received none`);await t.verifyLoadResponse(c)}a=r.sessionId}else a=lr(c,r.sessionId);l=c,s.setSessionId(a)}else{let c=await e("session/new",{cwd:r.cwd,mcpServers:[]});a=lr(c),l=c,s.setSessionId(a)}return{sessionId:a,sessionResponse:l}}function ok(t,e){let n=Aa(e.tool);if(!n)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{tk(e.tool,e.acpMode)}catch(r){return Promise.reject(r)}return new Promise((r,s)=>{let i=e.permissionMode??"yolo",o=[],a={permissionMode:i,...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.acpMode!==void 0?{acpMode:e.acpMode}:{},purpose:"chat",warnings:{push:R=>{o.push(R)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=sk(n,e,a))}catch(R){return s(R instanceof Error?R:new Error(String(R)))}let d=ek(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),p=!1,f=!1,h=0,g=!1,y=!1;if(e.signal){if(e.signal.aborted)return p=!0,X({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),be(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,X({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),be(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let b=e.sessionId||"",_=hu({tool:e.tool,onDelta:e.onDelta,...n.isolateResult?{isolateResult:n.isolateResult}:{}});_.setSessionId(b);let v=Gr(d,{provider:e.tool,onEvent:R=>{h=Date.now(),nk(R)&&(y=!0),e.onEvent?.(R)},onNotification:R=>{h=Date.now(),_.processMessage(R)}}),{sendRpc:E,sendNotification:x}=v,S="";d.stderr?.on("data",R=>{S+=R.toString()}),d.on("error",R=>{v.close(R),X({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:R.message,elapsed_ms:Date.now()-m}),s(new Ne(`Failed to spawn ${n.binary} ${n.baseArgs.join(" ")}: ${R.message}`,{cause:R}))}),d.on("exit",(R,N)=>{if(f=!0,v.close(new De(`ACP process ${N?`terminated by ${N}`:`exited with code ${String(R)}`}`,R,N)),p)return;let O=_.finalize();if(O!==null)n.onExitFinalization?.({...a,sessionId:O.sessionId,result:O.result,stopReason:O.stopReason,exitCode:R}),r({result:O.result,sessionId:O.sessionId,durationMs:Date.now()-m,stopReason:O.stopReason,exitCode:R,sawActivity:O.sawActivity,...o.length>0?{warnings:o}:{}});else{let A=VU(e.tool,S),w=JU({tool:e.tool,exitCode:R,signal:N,stderr:A,fullOutput:S});X({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:R,signal:N,stderr_summary:w,elapsed_ms:Date.now()-m}),s(new De(w,R,N,S))}}),(async()=>{try{let R=await ik({sendRpc:E,sendNotification:x,opts:e,outputProcessor:_});b=R.sessionId,e.onSessionId?.(b);let N=R.sessionResponse;await rk(n,a,{sessionId:b,response:N},E),_.beginTurn(),g=!0,Qe(`acp: prompt sent (${t.length} chars)`);let O;if(await E("session/prompt",{sessionId:b,prompt:[{type:"text",text:t}]},A=>{A.error?_.cancelTurn():O=_.completeTurn(A)}),!O)throw new Error("ACP prompt completed without a result boundary");g=!1,Qe(`acp: result received (${O.result.length} chars, stopReason=${O.stopReason})`),In(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>f,isTurnInFlight:()=>g,lastEventAtMs:()=>h,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>y})}catch(R){be(d).catch(()=>{}),s(R instanceof Error?R:new Error(String(R)))}})()})}async function ak(t){let e=Aa(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&tk(t.tool,t.acpMode);let n=t.permissionMode??"yolo",r=[],s=!0,i={permissionMode:n,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:N=>{r.push(N)}}},{binary:o,spawnArgs:a,spawnEnv:l}=sk(e,t,i),c=ek(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,signal:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m,p=t.sessionId||"",f=null,h="";c.stderr?.on("data",N=>{h+=N.toString()});let g,y,b=hu({tool:t.tool,onDelta:N=>g?.(N),...e.isolateResult?{isolateResult:e.isolateResult}:{}});b.setSessionId(p);let _=Gr(c,{provider:t.tool,onEvent:N=>{d.lastEventAtMs=Date.now(),nk(N)&&(d.backgroundJobLaunched=!0),y?.(N)},onNotification:N=>{d.lastEventAtMs=Date.now(),b.processMessage(N)}}),v=()=>new De(`ACP bundle process (${t.tool}) exited${d.signal!==null?` by ${d.signal}`:d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`,d.exitCode,d.signal,h),E=[],x=()=>d.exited?Promise.resolve():new Promise(N=>{E.push(N)}),S=null;c.on("error",N=>{f=new Ne(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${N.message}`,{cause:N}),X({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:N.message,elapsed_ms:Date.now()-u}),_.close(N)}),c.on("exit",(N,O)=>{if(d.exited=!0,d.exitCode=N,d.signal=O,_.close(new De(`ACP process ${O?`terminated by ${O}`:`exited with code ${String(N)}`}`,N,O)),!d.telemetryFired){d.telemetryFired=!0;let A=b.finalize();A!==null&&e.onExitFinalization?.({...i,sessionId:A.sessionId,result:A.result,stopReason:A.stopReason,exitCode:N})}if(S!==null){let A=S;S=null,A(v())}for(let A of E.splice(0))A()}),c.on("close",(N,O)=>{if(!d.exited){d.exited=!0,d.exitCode=N,d.signal=O;for(let A of E.splice(0))A()}});try{let N=await ik({sendRpc:_.sendRpc,sendNotification:_.sendNotification,opts:t,outputProcessor:b,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async O=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:O,cwd:t.cwd,env:l})});p=N.sessionId,t.onSessionId?.(p),await rk(e,i,{sessionId:N.sessionId,response:N.sessionResponse},_.sendRpc)}catch(N){let O=f??(N instanceof Error?N:new Error(String(N)));throw t.serviceHosted&&t.closeTimeoutMs===void 0?(c.stdin?.end(),await x()):be(c).catch(()=>{}),O}let R=N=>new Promise(O=>{setTimeout(O,N).unref?.()});return{tool:t.tool,get sessionId(){return p},get completedTurns(){return d.completedTurns},async sendTurn(N,O={}){if(m&&await m,d.closed||d.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(d.exited)throw v();if(d.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(O.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:p,cwd:t.cwd,env:l}),d.exited)throw v();if(O.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,g=O.onDelta,y=O.onEvent;let A=Date.now();try{b.beginTurn(),Qe(`acp: bundle prompt sent (${N.length} chars)`);let w,T=!1;if(await new Promise((I,C)=>{S=C;let M,D=()=>{T=!0,m=Promise.resolve().then(()=>M).catch(()=>{}),b.cancelTurn(),_.sendNotification("session/cancel",{sessionId:p}),C(new Error("Aborted"))},j=O.signal;j?.addEventListener("abort",D,{once:!0}),M=_.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:N}]},F=>{T||(F.error?b.cancelTurn():w=b.completeTurn(F),g=void 0,y=void 0)}),M.then(F=>{j?.removeEventListener("abort",D),I(F)},F=>{j?.removeEventListener("abort",D),C(F instanceof Error?F:new Error(String(F)))})}),S=null,!w)throw new Error("ACP prompt completed without a result boundary");d.turnInFlight=!1,d.completedTurns+=1,Qe(`acp: bundle result received (${w.result.length} chars, stopReason=${w.stopReason})`);let k=s&&r.length>0?[...r]:void 0;return s=!1,{result:w.result,sessionId:w.sessionId,stopReason:w.stopReason,durationMs:Date.now()-A,sawActivity:w.sawActivity,...k!==void 0?{warnings:k}:{}}}catch(w){throw S=null,b.cancelTurn(),d.turnInFlight=!1,d.exited?v():w}finally{g=void 0,y=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(t.holdOpen!==void 0?await new Promise(O=>{In(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),O()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let N=t.closeTimeoutMs;if(N===void 0&&t.serviceHosted)await x();else{let O=N??2e3;await Promise.race([x(),R(O)]),d.exited||await be(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,O),killDelayMs:Math.min(1e3,O)}).catch(()=>{})}})()),d.closing}}}var bg=L(()=>{"use strict";Re();qr();Us();wa();An();Re();mn();dn();Ea();lg();ZS();vg();hg();Ea()});function bu(t,e,n){return Tn(t)&&e.tools[t]?.agent===void 0&&n.includes(t)}function wu(t,e){return Tn(t.name)&&t.protocol?.persistentResume===!0&&t.openSession!==void 0&&e.tools[t.name]?.agent===void 0}async function cr(t,e,n,r,s){if(t.provider!==e)throw new Error(`bundle session provider mismatch: session serves "${t.provider}", turn targets "${e}"`);if(t.sessionId!==n)throw new Ui(`session identity mismatch: expected "${n}", got "${t.sessionId}"`);let i=await t.sendTurn(r,s);if(i.sessionId!==n)throw Object.assign(new Ui(`session identity mismatch: expected "${n}", got "${i.sessionId}"`),{usage:i.usage,sessionId:i.sessionId});return{...i,...i.text===""&&i.sawActivity===!1?{status:"empty"}:{}}}async function Eu(t,e){Qc(t.name);let n=e.requireResume??!0;if(n&&!e.sessionId.trim())throw new Error("conversation requires an existing session ID");let r=e.userConfig?.tools[t.name]?.agent!==void 0,s=e.execution!=="per-turn"&&t.openSession!==void 0&&!r;if(e.execution==="persistent"&&!s)throw new Error(`provider "${t.name}" does not support persistent sessions with this configuration`);let i=s?await t.openSession(e):void 0,o=!n&&e.sessionId==="";if(i&&(i.provider!==t.name||typeof i.sessionId!="string"||!i.sessionId.trim()||!o&&i.sessionId!==e.sessionId))throw await i.close(),new Error(`session identity mismatch opening ${t.name}: expected "${e.sessionId}", got "${i.sessionId}" (${i.provider})`);let a=i?.sessionId??e.sessionId,l=0,c=!1,u,d;return{provider:t.name,sessionId:a,execution:s?"persistent":"per-turn",transport:r?"custom":t.protocol?.transport??"unknown",cancellation:r?"unknown":s?t.protocol?.persistentCancellation??"unknown":t.protocol?.perTurnCancellation??"unknown",get completedTurns(){return l},async sendTurn(m,p={}){if(c)throw new Error("conversation is closed");if(u)throw new Error("conversation already has an active turn");if(p.signal?.aborted)throw new Error("Aborted");let f=new AbortController;u=f;let h=()=>f.abort();p.signal?.addEventListener("abort",h,{once:!0});try{let g=i?await cr(i,t.name,a,m,{...p,signal:f.signal}):await t.sendTurn(m,{...e,...p,signal:f.signal,requireResume:n,timeoutMs:e.timeoutMs??0});if(f.signal.aborted)throw Object.assign(new Error("Aborted"),{usage:g.usage,sessionId:g.sessionId});if(n&&g.sessionId!==e.sessionId)throw c=!0,Object.assign(new Ui(`session identity mismatch: expected "${e.sessionId}", got "${g.sessionId}"`),{usage:g.usage,sessionId:g.sessionId});return g.status!=="empty"&&g.status!=="stalled"&&l++,g}catch(g){throw f.signal.aborted&&i&&t.protocol?.persistentCancellation==="session"&&(c=!0),g instanceof Ui&&(c=!0,await i?.close()),g}finally{p.signal?.removeEventListener("abort",h),u=void 0}},close(){return d||(c=!0,u?.abort(),d=i?i.close():Promise.resolve()),d}}}var Ui,Vr=L(()=>{"use strict";Li();Ui=class extends Error{}});import{realpathSync as KU}from"node:fs";import{resolve as zU}from"node:path";function wg(t){let e=zU(t);try{return KU(e)}catch{return e}}var lk=L(()=>{"use strict"});import{platform as ck}from"node:os";function ur(t){let e=new Ca;for(let n of t)e.registerAdapter(n);return e}var Ca,Eg=L(()=>{"use strict";lk();Ca=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let n=[],r=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(r.map(o=>o.discoverSessions()));for(let o of s)n.push(...o);let i=n;if(e?.workspace){let o=wg(e.workspace);i=i.filter(a=>wg(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,n){let r=n?this.providers.filter(s=>s.name===n):this.providers;for(let s of r){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,n){let r=await this.resolveSessions(e,n);return r.length===1?r[0]:null}async resolveSessions(e,n){let r=n?this.providers.filter(i=>i.name===n):this.providers,s=[];for(let i of r){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=ck()==="darwin"||ck()==="win32",n=[];for(let r of this.providers)if(typeof r.getWatchPaths=="function")for(let s of r.getWatchPaths())n.push({provider:r.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return n}async deleteSession(e,n){let r=await this.resolveSession(e,n);return r?r.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:n=>e.load(n),resolveSessionPath:n=>e.resolvePath(n),deleteSession:n=>e.delete(n),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});function Rg(){return new Sg}function xg(t){let e=!1;for(let n of t.split(`
|
|
2272
|
+
`),X({event:"acp_session_resume_fallback",provider:r.tool,session_id:r.sessionId,error_message:d instanceof Error?d.message:String(d)});let m=await e("session/new",{cwd:r.cwd,mcpServers:[]});return a=lr(m),s.setSessionId(a),{sessionId:a,sessionResponse:m}}let u=lr(c);if(r.requireResume&&u!==""&&u!==r.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${r.sessionId}", received "${u}"`);if(i){let d=lr(c);if(d!==""&&d!==r.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${r.sessionId}", received "${d}"`);if(d===""){if(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${r.sessionId}", received none`);await t.verifyLoadResponse(c)}a=r.sessionId}else a=lr(c,r.sessionId);l=c,s.setSessionId(a)}else{let c=await e("session/new",{cwd:r.cwd,mcpServers:[]});a=lr(c),l=c,s.setSessionId(a)}return{sessionId:a,sessionResponse:l}}function ok(t,e){let n=Aa(e.tool);if(!n)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{tk(e.tool,e.acpMode)}catch(r){return Promise.reject(r)}return new Promise((r,s)=>{let i=e.permissionMode??"yolo",o=[],a={permissionMode:i,...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.acpMode!==void 0?{acpMode:e.acpMode}:{},purpose:"chat",warnings:{push:R=>{o.push(R)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=sk(n,e,a))}catch(R){return s(R instanceof Error?R:new Error(String(R)))}let d=ek(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),p=!1,f=!1,h=0,g=!1,y=!1;if(e.signal){if(e.signal.aborted)return p=!0,X({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),be(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,X({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),be(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let b=e.sessionId||"",_=hu({tool:e.tool,onDelta:e.onDelta,...n.isolateResult?{isolateResult:n.isolateResult}:{}});_.setSessionId(b);let v=Gr(d,{provider:e.tool,onEvent:R=>{h=Date.now(),nk(R)&&(y=!0),e.onEvent?.(R)},onNotification:R=>{h=Date.now(),_.processMessage(R)}}),{sendRpc:E,sendNotification:x}=v,S="";d.stderr?.on("data",R=>{S+=R.toString()}),d.on("error",R=>{v.close(R),X({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:R.message,elapsed_ms:Date.now()-m}),s(new Ne(`Failed to spawn ${n.binary} ${n.baseArgs.join(" ")}: ${R.message}`,{cause:R}))}),d.on("exit",(R,N)=>{if(f=!0,v.close(new De(`ACP process ${N?`terminated by ${N}`:`exited with code ${String(R)}`}`,R,N)),p)return;let O=_.finalize();if(O!==null)n.onExitFinalization?.({...a,sessionId:O.sessionId,result:O.result,stopReason:O.stopReason,exitCode:R}),r({result:O.result,sessionId:O.sessionId,durationMs:Date.now()-m,stopReason:O.stopReason,exitCode:R,sawActivity:O.sawActivity,...o.length>0?{warnings:o}:{}});else{let A=VU(e.tool,S),w=JU({tool:e.tool,exitCode:R,signal:N,stderr:A,fullOutput:S});X({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:R,signal:N,stderr_summary:w,elapsed_ms:Date.now()-m}),s(new De(w,R,N,S))}}),(async()=>{try{let R=await ik({sendRpc:E,sendNotification:x,opts:e,outputProcessor:_});b=R.sessionId,e.onSessionId?.(b);let N=R.sessionResponse;await rk(n,a,{sessionId:b,response:N},E),_.beginTurn(),g=!0,Qe(`acp: prompt sent (${t.length} chars)`);let O;if(await E("session/prompt",{sessionId:b,prompt:[{type:"text",text:t}]},A=>{A.error?_.cancelTurn():O=_.completeTurn(A)}),!O)throw new Error("ACP prompt completed without a result boundary");g=!1,Qe(`acp: result received (${O.result.length} chars, stopReason=${O.stopReason})`),In(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>f,isTurnInFlight:()=>g,lastEventAtMs:()=>h,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>y})}catch(R){be(d).catch(()=>{}),s(R instanceof Error?R:new Error(String(R)))}})()})}async function ak(t){let e=Aa(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&tk(t.tool,t.acpMode);let n=t.permissionMode??"yolo",r=[],s=!0,i={permissionMode:n,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:N=>{r.push(N)}}},{binary:o,spawnArgs:a,spawnEnv:l}=sk(e,t,i),c=ek(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,signal:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m,p=t.sessionId||"",f=null,h="";c.stderr?.on("data",N=>{h+=N.toString()});let g,y,b=hu({tool:t.tool,onDelta:N=>g?.(N),...e.isolateResult?{isolateResult:e.isolateResult}:{}});b.setSessionId(p);let _=Gr(c,{provider:t.tool,onEvent:N=>{d.lastEventAtMs=Date.now(),nk(N)&&(d.backgroundJobLaunched=!0),y?.(N)},onNotification:N=>{d.lastEventAtMs=Date.now(),b.processMessage(N)}}),v=()=>new De(`ACP bundle process (${t.tool}) exited${d.signal!==null?` by ${d.signal}`:d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`,d.exitCode,d.signal,h),E=[],x=()=>d.exited?Promise.resolve():new Promise(N=>{E.push(N)}),S=null;c.on("error",N=>{f=new Ne(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${N.message}`,{cause:N}),X({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:N.message,elapsed_ms:Date.now()-u}),_.close(N)}),c.on("exit",(N,O)=>{if(d.exited=!0,d.exitCode=N,d.signal=O,_.close(new De(`ACP process ${O?`terminated by ${O}`:`exited with code ${String(N)}`}`,N,O)),!d.telemetryFired){d.telemetryFired=!0;let A=b.finalize();A!==null&&e.onExitFinalization?.({...i,sessionId:A.sessionId,result:A.result,stopReason:A.stopReason,exitCode:N})}if(S!==null){let A=S;S=null,A(v())}for(let A of E.splice(0))A()}),c.on("close",(N,O)=>{if(!d.exited){d.exited=!0,d.exitCode=N,d.signal=O;for(let A of E.splice(0))A()}});try{let N=await ik({sendRpc:_.sendRpc,sendNotification:_.sendNotification,opts:t,outputProcessor:b,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async O=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:O,cwd:t.cwd,env:l})});p=N.sessionId,t.onSessionId?.(p),await rk(e,i,{sessionId:N.sessionId,response:N.sessionResponse},_.sendRpc)}catch(N){let O=f??(N instanceof Error?N:new Error(String(N)));throw t.serviceHosted&&t.closeTimeoutMs===void 0?(c.stdin?.end(),await x()):be(c).catch(()=>{}),O}let R=N=>new Promise(O=>{setTimeout(O,N).unref?.()});return{tool:t.tool,get sessionId(){return p},get completedTurns(){return d.completedTurns},async sendTurn(N,O={}){if(m&&await m,d.closed||d.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(d.exited)throw v();if(d.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(O.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:p,cwd:t.cwd,env:l}),d.exited)throw v();if(O.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,g=O.onDelta,y=O.onEvent;let A=Date.now();try{b.beginTurn(),Qe(`acp: bundle prompt sent (${N.length} chars)`);let w,T=!1;if(await new Promise((I,C)=>{S=C;let M,D=()=>{T=!0,m=Promise.resolve().then(()=>M).catch(()=>{}),b.cancelTurn(),_.sendNotification("session/cancel",{sessionId:p}),C(new Error("Aborted"))},j=O.signal;j?.addEventListener("abort",D,{once:!0}),M=_.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:N}]},$=>{T||($.error?b.cancelTurn():w=b.completeTurn($),g=void 0,y=void 0)}),M.then($=>{j?.removeEventListener("abort",D),I($)},$=>{j?.removeEventListener("abort",D),C($ instanceof Error?$:new Error(String($)))})}),S=null,!w)throw new Error("ACP prompt completed without a result boundary");d.turnInFlight=!1,d.completedTurns+=1,Qe(`acp: bundle result received (${w.result.length} chars, stopReason=${w.stopReason})`);let k=s&&r.length>0?[...r]:void 0;return s=!1,{result:w.result,sessionId:w.sessionId,stopReason:w.stopReason,durationMs:Date.now()-A,sawActivity:w.sawActivity,...k!==void 0?{warnings:k}:{}}}catch(w){throw S=null,b.cancelTurn(),d.turnInFlight=!1,d.exited?v():w}finally{g=void 0,y=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(t.holdOpen!==void 0?await new Promise(O=>{In(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),O()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let N=t.closeTimeoutMs;if(N===void 0&&t.serviceHosted)await x();else{let O=N??2e3;await Promise.race([x(),R(O)]),d.exited||await be(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,O),killDelayMs:Math.min(1e3,O)}).catch(()=>{})}})()),d.closing}}}var bg=L(()=>{"use strict";Re();qr();Us();wa();An();Re();mn();dn();Ea();lg();ZS();vg();hg();Ea()});function bu(t,e,n){return Tn(t)&&e.tools[t]?.agent===void 0&&n.includes(t)}function wu(t,e){return Tn(t.name)&&t.protocol?.persistentResume===!0&&t.openSession!==void 0&&e.tools[t.name]?.agent===void 0}async function cr(t,e,n,r,s){if(t.provider!==e)throw new Error(`bundle session provider mismatch: session serves "${t.provider}", turn targets "${e}"`);if(t.sessionId!==n)throw new Ui(`session identity mismatch: expected "${n}", got "${t.sessionId}"`);let i=await t.sendTurn(r,s);if(i.sessionId!==n)throw Object.assign(new Ui(`session identity mismatch: expected "${n}", got "${i.sessionId}"`),{usage:i.usage,sessionId:i.sessionId});return{...i,...i.text===""&&i.sawActivity===!1?{status:"empty"}:{}}}async function Eu(t,e){Qc(t.name);let n=e.requireResume??!0;if(n&&!e.sessionId.trim())throw new Error("conversation requires an existing session ID");let r=e.userConfig?.tools[t.name]?.agent!==void 0,s=e.execution!=="per-turn"&&t.openSession!==void 0&&!r;if(e.execution==="persistent"&&!s)throw new Error(`provider "${t.name}" does not support persistent sessions with this configuration`);let i=s?await t.openSession(e):void 0,o=!n&&e.sessionId==="";if(i&&(i.provider!==t.name||typeof i.sessionId!="string"||!i.sessionId.trim()||!o&&i.sessionId!==e.sessionId))throw await i.close(),new Error(`session identity mismatch opening ${t.name}: expected "${e.sessionId}", got "${i.sessionId}" (${i.provider})`);let a=i?.sessionId??e.sessionId,l=0,c=!1,u,d;return{provider:t.name,sessionId:a,execution:s?"persistent":"per-turn",transport:r?"custom":t.protocol?.transport??"unknown",cancellation:r?"unknown":s?t.protocol?.persistentCancellation??"unknown":t.protocol?.perTurnCancellation??"unknown",get completedTurns(){return l},async sendTurn(m,p={}){if(c)throw new Error("conversation is closed");if(u)throw new Error("conversation already has an active turn");if(p.signal?.aborted)throw new Error("Aborted");let f=new AbortController;u=f;let h=()=>f.abort();p.signal?.addEventListener("abort",h,{once:!0});try{let g=i?await cr(i,t.name,a,m,{...p,signal:f.signal}):await t.sendTurn(m,{...e,...p,signal:f.signal,requireResume:n,timeoutMs:e.timeoutMs??0});if(f.signal.aborted)throw Object.assign(new Error("Aborted"),{usage:g.usage,sessionId:g.sessionId});if(n&&g.sessionId!==e.sessionId)throw c=!0,Object.assign(new Ui(`session identity mismatch: expected "${e.sessionId}", got "${g.sessionId}"`),{usage:g.usage,sessionId:g.sessionId});return g.status!=="empty"&&g.status!=="stalled"&&l++,g}catch(g){throw f.signal.aborted&&i&&t.protocol?.persistentCancellation==="session"&&(c=!0),g instanceof Ui&&(c=!0,await i?.close()),g}finally{p.signal?.removeEventListener("abort",h),u=void 0}},close(){return d||(c=!0,u?.abort(),d=i?i.close():Promise.resolve()),d}}}var Ui,Vr=L(()=>{"use strict";Li();Ui=class extends Error{}});import{realpathSync as KU}from"node:fs";import{resolve as zU}from"node:path";function wg(t){let e=zU(t);try{return KU(e)}catch{return e}}var lk=L(()=>{"use strict"});import{platform as ck}from"node:os";function ur(t){let e=new Ca;for(let n of t)e.registerAdapter(n);return e}var Ca,Eg=L(()=>{"use strict";lk();Ca=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let n=[],r=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(r.map(o=>o.discoverSessions()));for(let o of s)n.push(...o);let i=n;if(e?.workspace){let o=wg(e.workspace);i=i.filter(a=>wg(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,n){let r=n?this.providers.filter(s=>s.name===n):this.providers;for(let s of r){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,n){let r=await this.resolveSessions(e,n);return r.length===1?r[0]:null}async resolveSessions(e,n){let r=n?this.providers.filter(i=>i.name===n):this.providers,s=[];for(let i of r){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=ck()==="darwin"||ck()==="win32",n=[];for(let r of this.providers)if(typeof r.getWatchPaths=="function")for(let s of r.getWatchPaths())n.push({provider:r.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return n}async deleteSession(e,n){let r=await this.resolveSession(e,n);return r?r.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:n=>e.load(n),resolveSessionPath:n=>e.resolvePath(n),deleteSession:n=>e.delete(n),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});function Rg(){return new Sg}function xg(t){let e=!1;for(let n of t.split(`
|
|
2272
2273
|
`)){let r;try{r=JSON.parse(n)}catch{continue}let s=r.type;typeof s=="string"&&(s.endsWith(".started")&&(e=!0),["turn.completed","turn.failed","turn.aborted","turn.cancelled","error"].includes(s)&&(e=!1))}return e}function Ig(t){let e=t.trimEnd().split(`
|
|
2273
2274
|
`).at(-1)?.trimStart()??"";if(!e.startsWith("{"))return!1;try{return JSON.parse(e),!1}catch{return!0}}function uk(t){let e,n=!1,r=!1,s;for(let i of t.split(`
|
|
2274
2275
|
`)){let o;try{o=JSON.parse(i)}catch{continue}if(o.type==="thread.started"&&typeof o.thread_id=="string"&&(e=o.thread_id),o.type==="turn.started"&&(n=!0),o.type!=="turn.completed"||!n||r)continue;r=!0;let a=o.usage;if(!a)continue;let l=Et(a.input_tokens),c=Et(a.cached_input_tokens);s={source:"wire",inputUncached:l===null||c===null||c>l?null:l-c,cacheRead:c,cacheWrite:0,output:Et(a.output_tokens),reasoning:Et(a.reasoning_output_tokens),modelReported:typeof o.model=="string"?o.model:null,providerCostUsd:null,reason:null,invalidCounters:wn([a.input_tokens,a.cached_input_tokens,a.output_tokens,a.reasoning_output_tokens])||l!==null&&c!==null&&c>l},[s.inputUncached,s.cacheRead,s.output].includes(null)&&(s.reason="counter_not_exposed")}return(Ig(t)||xg(t))&&(s={source:"wire",inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:"counter_not_exposed",invalidCounters:!0}),{sessionId:e,usage:s}}var Et,YU,Tg,Sg,kg,Ag=L(()=>{"use strict";Qo();Et=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,YU=(t,e)=>t===null||e===null?null:Et(t+e),Tg=(t,e)=>JSON.stringify([t,e]),Sg=class{finished=new Set;seen=new Set;models=new Map;reportModel(e,n){typeof n=="string"&&n&&n!=="<synthetic>"&&this.models.set(e,n)}remember(e,n){typeof n=="string"&&n&&this.finished.add(Tg(e,n))}turn(e,n=""){return new kg(this,e,n)}};kg=class{constructor(e,n,r){this.session=e;this.thread=n;this.id=r}value;ended=!1;reported=new Set;bind(e){return typeof e!="string"||!e||this.ended||this.session.finished.has(Tg(this.thread,e))||this.id&&this.id!==e?!1:(this.id=e,!0)}event(e){let n=e.method,r=e.params,s=r?.turn,i=r?.turnId??s?.id,o=typeof r?.threadId=="string"?r.threadId:this.thread;if(this.thread&&o!==this.thread||(this.thread||(this.thread=o),typeof i=="string"&&this.session.finished.has(Tg(o,i))))return!1;if(n==="turn/started")return this.bind(i);if(this.id&&i&&i!==this.id)return!1;if(n==="turn/completed")return this.id?!this.ended:this.bind(i);if(n!=="thread/tokenUsage/updated")return!0;if(this.ended||!this.id||r?.threadId!==this.thread||r?.turnId!==this.id)return!1;let a=r.tokenUsage;if(!a?.last||typeof a.last!="object"||Array.isArray(a.last)||[a.last.inputTokens,a.last.cachedInputTokens,a.last.outputTokens].every(E=>E==null))return!0;let l=E=>["inputTokens","cachedInputTokens","cacheWriteInputTokens","outputTokens","reasoningOutputTokens","totalTokens"].map(x=>E[x]??null),c=a.total&&["inputTokens","cachedInputTokens","outputTokens"].every(E=>Et(a.total[E])!==null)?l(a.total):null,u=typeof e.id=="string"&&e.id.length>0||typeof e.id=="number"&&Number.isSafeInteger(e.id)?e.id:null,d=Et(e.emittedAtMs)??u,m=Et(e.ordinal)??Et(r.ordinal),p=JSON.stringify([this.thread,this.id,c,l(a.last),d,u,m]),f=d!==null||m!==null;if(f&&this.session.seen.has(p))return!1;f&&this.session.seen.add(p);let h=a.last,g=Et(h.inputTokens),y=Et(h.cachedInputTokens),_={source:"wire",inputUncached:g===null||y===null||y>g?null:g-y,cacheRead:y,cacheWrite:Et(h.cacheWriteInputTokens??0),output:Et(h.outputTokens),reasoning:Et(h.reasoningOutputTokens),modelReported:null,providerCostUsd:null,reason:null,invalidCounters:wn([h.inputTokens,h.cachedInputTokens,h.cacheWriteInputTokens,h.outputTokens,h.reasoningOutputTokens])||g!==null&&y!==null&&y>g};[_.inputUncached,_.cacheRead,_.cacheWrite,_.output].includes(null)&&(_.reason="counter_not_exposed");let v=r.model??h.model;if(typeof v=="string"&&v&&v!=="<synthetic>"&&this.reported.add(v),!this.value)this.value=_;else{for(let E of["inputUncached","cacheRead","cacheWrite","output","reasoning"]){let x=this.value[E],S=_[E];x!==null&&S!==null&&Et(x+S)===null&&(this.value.invalidCounters=!0,this.value.reason="counter_not_exposed"),this.value[E]=YU(this.value[E],_[E])}this.value.reason=this.value.reason||_.reason,this.value.invalidCounters||=_.invalidCounters}return!0}usage(){if(this.value)return{...this.value,modelReported:this.reported.size>1?null:[...this.reported][0]??this.session.models.get(this.thread)??null,mixedModels:this.reported.size>1}}finish(){this.ended=!0,this.id&&this.session.remember(this.thread,this.id)}}});import{readFileSync as QU,writeFileSync as A8,mkdirSync as C8}from"node:fs";import{join as ZU,dirname as O8}from"node:path";import{homedir as e1}from"node:os";function n1(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function r1(t){let e=t.indexOf("=");if(e===-1)return null;let n=t.slice(0,e).trim(),r=n1(t.slice(e+1).trim());return n?{key:n,value:r}:null}function s1(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Tu(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function i1(){return ZU(e1(),".lmctl","config.toml")}function Kr(t){let e=t??i1(),n;try{n=QU(e,"utf-8")}catch{return{tools:{}}}return o1(n)}function dk(t){if(typeof t=="number")return Number.isFinite(t)?t:null;let e=String(t).trim();if(!e)return null;let n=e.match(/^(\d+(?:\.\d+)?)\s*([KkMm]?)$/);if(!n)return null;let r=parseFloat(n[1]);if(!Number.isFinite(r))return null;switch(n[2]){case"K":case"k":return Math.round(r*1e3);case"M":case"m":return Math.round(r*1e6);default:return Math.round(r)}}function o1(t){let e={},n={},r=t.split(`
|
|
@@ -2279,8 +2280,8 @@ ${e}`),e}var l1,ue,Su,c1,u1,d1,nt=L(()=>{"use strict";l1="ACK: waiting for expli
|
|
|
2279
2280
|
Teamfile `,u1=`
|
|
2280
2281
|
|
|
2281
2282
|
After this seed finishes, use \`lmctl prompt `,d1=' <alias> "<message>"` to send a message. Do not run or use lmctl prompt during this seed. Reply only with the ACK above and wait.'});import{spawn as hk}from"node:child_process";import{mkdirSync as m1}from"node:fs";var Hs,we,dt=L(()=>{"use strict";Ag();Bi();gk();nt();mn();cu();dn();qr();Hs=class t extends Error{cancelReason;constructor(e,n){super(e),this.name="TurnAbortError",this.cancelReason=n,Object.setPrototypeOf(this,t.prototype)}},we=class t{name;capabilities;injection;protocol;provider;binary;seedArgs;seedTimeoutMs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.protocol=e.protocol,this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedTimeoutMs=e.seedTimeoutMs??6e4,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let n=e?.prompt;return n===void 0?this.seedArgs:this.seedArgs.map(r=>r===ue?n:r)}turnOptsFor(e){return e}get seedBinary(){return this.binary}seed(e,n){return n?.signal?.aborted?Promise.resolve({success:!1,error:"seed cancelled before dispatch",errorCode:"ABORT_ERR"}):(m1(e,{recursive:!0}),new Promise(r=>{let s;try{try{n?.onDispatch?.()}catch{}s=hk(this.binary,this.seedArgsFor(n),{cwd:e,env:$i(n?.env,e),signal:n?.signal,stdio:["pipe","pipe","pipe"],timeout:this.seedTimeoutMs})}catch(l){return r({success:!1,error:l instanceof Error?l.message:String(l)})}let i="",o="";s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{o+=l.toString()});let a=n?.prompt!==void 0&&this.seedStdin!==void 0?`${n.prompt}
|
|
2282
|
-
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)r({success:!0});else{let u=js(o).trim(),d=js(i).trim(),m=u||d;r({success:!1,...n?.signal?.aborted?{errorCode:"ABORT_ERR"}:{},error:m?Me(m,{provider:this.name}):c?`terminated by ${c}`:`exit code ${l}`})}}),s.on("error",l=>{r({success:!1,error:l.message,errorCode:l.code})})}))}resumeCommand(e,n){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:Su,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,n){let r=this.turnOptsFor(n);if(r.userConfig&&mk(r.userConfig,this.name)){let i=r.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,r,i.agent)}let s=r.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!r.signal?this.transportFn(e,{...r,binary:this.binary}):this.withTimeouts(s,e,r)}withTimeouts(e,n,r){let s=new AbortController,i,o,a="",l,c=r.sessionId,u,d=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{r.onIdleWarning?.(e),m(),s.abort(),u&&u({text:a,...l?{usage:l}:{},sessionId:c,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},m=()=>{clearTimeout(i)};r.signal&&(r.signal.aborted?(o="external",s.abort()):r.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),d();let p={...r,binary:this.binary,signal:s.signal,onUsage:g=>{l=g,r.onUsage?.(g)},onSessionId:g=>{g&&(c=g),r.onSessionId?.(g)},onDelta:g=>{a+=g,d(),r.onDelta?.(g)},onProgress:g=>{g.kind!=="api_retry"&&d(),r.onProgress?.(g)}},f=this.transportFn(n,p).then(g=>(m(),{...g,status:g.status??"ok"})).catch(g=>{throw m(),o==="external"?Object.assign(new Hs("Turn cancelled","external"),{usage:g.usage??l,sessionId:c}):g}),h=new Promise(g=>{u=g});return Promise.race([f,h])}runOneShotAgent(e,n,r){let s=pk(n.userConfig,this.name,n.sessionId,e,n.profile),i=Date.now();return new Promise((o,a)=>{let l=n.timeoutMs!==void 0&&n.timeoutMs<=0?0:fk(n.env),c=hk(s,{shell:!0,cwd:n.cwd,env:He(n.env,n.cwd,n.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m,p,f=!1,h=null,g=null,y=()=>{clearTimeout(m),m=setTimeout(()=>{!Ig(_)&&!xg(_)&&E(h,g)},100)},b=l>0?setTimeout(()=>{d=!0,c.kill(),this.name==="codex"&&E(null)},l):void 0,_="",v="";if(c.stdout?.on("data",x=>{let S=x.toString();_+=S,n.onDelta?.(S),f&&!u&&y()}),c.stderr?.on("data",x=>{v+=x.toString(),f&&!u&&y()}),n.signal){if(n.signal.aborted)return clearTimeout(b),c.kill(),a(new Error("Aborted"));n.signal.addEventListener("abort",()=>c.kill(),{once:!0})}let E=(x,S=null)=>{if(u)return;u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),this.name==="codex"&&(c.stdout?.destroy(),c.stderr?.destroy());let R=Date.now()-i,N=this.name==="codex"?uk(_):{};N.usage&&n.onUsage?.(N.usage),N.sessionId&&n.onSessionId?.(N.sessionId);let O=A=>Object.assign(A,{usage:N.usage,sessionId:N.sessionId??n.sessionId});if(this.name==="codex"&&n.signal?.aborted)a(O(new Hs("Turn cancelled","external")));else if(d)a(O(new Error(`Agent command timed out after ${l}ms`)));else if(x===0||x===null&&S===null)o({text:_.trim(),sessionId:N.sessionId??n.sessionId,durationMs:R,...N.usage?{usage:N.usage}:{}});else{let A=v.trim();a(O(new De(A?Me(A,{provider:this.name}):S?`Agent command terminated by ${S}`:`Agent command exited with code ${x}`,x,S,v)))}};this.name==="codex"?(c.on("close",(x,S)=>E(x,S)),c.on("exit",(x,S)=>{u||(f=!0,h=x,g=S,y(),p=setTimeout(()=>E(x,S),5e3))})):c.on("exit",(x,S)=>E(x,S)),c.on("error",x=>{u||(u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),a(x))})})}}});function _k(t){if(!t.length)return;let e={...t[0]},n=new Set(t.map(r=>r.modelReported).filter(r=>r!==null));for(let r of t.slice(1)){for(let s of["inputUncached","cacheRead","cacheWrite","output","reasoning"]){let i=e[s],o=r[s];i!==null&&o!==null&&We(i+o)===null&&(e.invalidCounters=!0),e[s]=i===null||o===null?null:We(i+o)}e.invalidCounters||=r.invalidCounters,e.reason||=r.reason}return e.modelReported=n.size===1?[...n][0]:null,e.mixedModels=n.size>1,(e.invalidCounters||["inputUncached","cacheRead","cacheWrite","output"].some(r=>e[r]===null))&&(e.reason="counter_not_exposed"),e}var We,zr,yk,Ru,Hi,xu=L(()=>{"use strict";Qo();We=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,zr=t=>typeof t=="string"&&t.length>0&&t!=="<synthetic>"?t:null,yk=()=>({source:"wire",inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:null});Ru=class{constructor(e,n){this.session=e;this.seen=n}parts=[];event(e,n){if(e.sessionId!==this.session||e.turnId!==n||!e.usage||typeof e.usage!="object")return!1;let r=e.sourceRange,s=zr(r?.first?.id),i=zr(r?.last?.id),o=zr(r?.stream?.id),a=zr(r?.stream?.kind),l=s&&i&&o&&a?JSON.stringify([this.session,a,o,s,i]):zr(e.viewCursor)?JSON.stringify([this.session,e.viewCursor]):null;if(l&&this.seen.has(l))return!1;l&&this.seen.add(l);let c=e.usage,u=We(e.promptTokens),d=We(c.outputTokens),m=We(c.cacheReadTokens),p=We(c.cacheWriteTokens),f=u===0,h=m??(f?0:null),g=p??(f?0:null),y=u!==null&&h!==null&&g!==null&&h+g<=u?u-h-g:null,b=(h??0)>0||(g??0)>0,_={...yk(),inputUncached:y,cacheRead:h,cacheWrite:g,output:d,reasoning:We(c.reasoningTokens),modelReported:zr(e.modelId),invalidCounters:wn([e.promptTokens,e.totalTokens,c.inputTokens,c.cachedTokens,c.cacheReadTokens,c.cacheWriteTokens,c.outputTokens,c.reasoningTokens])||b||y===null||d===null||We(e.totalTokens)!==null&&u!==null&&d!==null&&e.totalTokens!==u+d||We(c.reasoningTokens)!==null&&d!==null&&c.reasoningTokens>d};return this.parts.push(_),!0}usage(){return _k(this.parts)}},Hi=class{constructor(e,n,r){this.session=e;this.boundary=n;this.seen=r}parts=new Map;ownershipUncertain=!1;latestSnapshot;invalidateOwnership(){this.ownershipUncertain=!0,this.latestSnapshot&&(this.latestSnapshot.invalidCounters=!0,this.latestSnapshot.reason="counter_not_exposed")}update(e,n=1/0){let r=e.filter(l=>We(l.seq)!==null&&l.seq>this.boundary&&l.seq<=n),s=r.find(l=>l.type==="turn/start")?.data?.turn,i=new Set(r.map(l=>l.data?.turn).filter(l=>We(l)!==null)),o=this.ownershipUncertain||i.size>1,a=new Map;for(let l of r){let c=l.data;if(!c||s!==void 0&&c.turn!==s)continue;let u=l.type==="assistant/message",d=u?c.usage:l.type==="assistant/chunk"&&c.chunk?.type==="usage"?c.chunk.usage:void 0;if(!d||typeof d!="object")continue;let m=We(c.turn)!==null&&We(c.step)!==null?["step",c.turn,c.step]:zr(c.message?.id)?["message",c.message.id]:["seq",l.seq],p=JSON.stringify([this.session,...m]);if(this.seen.has(p))continue;let f=a.get(p);(!f||u||!f.final)&&a.set(p,{record:l,final:u})}this.parts=new Map;for(let[l,{record:c,final:u}]of a){let d=c.data,m=u?d.usage:d.chunk.usage;this.parts.set(l,{...yk(),inputUncached:We(m.inputTokens),cacheRead:We(m.cacheReadTokens),output:We(m.outputTokens),reasoning:We(m.reasoningTokens),modelReported:zr(d.message?.source?.model),invalidCounters:o||[m.inputTokens,m.cacheReadTokens,m.outputTokens].some(p=>We(p)===null)||wn([m.inputTokens,m.cacheReadTokens,m.outputTokens,m.reasoningTokens])||We(m.reasoningTokens)!==null&&We(m.outputTokens)!==null&&m.reasoningTokens>m.outputTokens})}}lastUsage(){let e=[...this.parts.values()].at(-1);return e?{...e}:void 0}usage(){let e=_k([...this.parts.values()]);return e&&this.ownershipUncertain&&(e.invalidCounters=!0,e.reason="counter_not_exposed"),this.latestSnapshot=e,e}finish(){for(let e of this.parts.keys())this.seen.add(e)}}});import{spawn as p1}from"node:child_process";import{randomBytes as f1}from"node:crypto";import{realpath as Iu}from"node:fs/promises";function Na(){let t=f1(16);t.writeUIntBE(Date.now(),0,6),t[6]=t[6]&15|112,t[8]=t[8]&63|128;let e=t.toString("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}async function Au(t){if(t.signal?.aborted)throw new Error("Aborted");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t.sessionId))throw new Error("Muse requires a native session UUID");let e=t.permissionMode==="plan",n=["serve",...e?["--disable-write","--disable-shell"]:["--disable-sandbox","--trust-workspace"],...t.model?["--model",t.model]:[]];Ge("muse",n,t.permissionMode??"yolo");let r=p1(t.progPath??"muse",n,{cwd:t.cwd,env:He(t.env,t.cwd,t.sessionId),stdio:["pipe","pipe","pipe"]}),s,i=new Set,o=new Set,a,l,c=!1,u=!1,d=!1,m=!1,p=0,f=wS(),h=Date.now(),g=t.sessionId;r.stderr.setEncoding("utf8"),r.stderr.on("data",w=>{f.append(w)});let y=(w,T,k)=>{if(s===w){if(s=void 0,w.id&&o.add(w.id),T){let I=w.usage.usage()??(w.outcome?{source:null,inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:"turn_not_completed"}:void 0);Object.assign(T,{usage:I?{...I,outcome:w.outcome}:void 0,sessionId:g})}else k&&(k.usage=w.usage.usage());w.cleanup(),w.drained(),w.settled||(w.settled=!0,T?w.reject(T):(p++,w.resolve(k)))}},b=w=>{a||(a=w,s&&y(s,a),v.close(a),!m&&!c&&be(r,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{}))},_=(w,T)=>{let k=T.params;if(!k||k.sessionId!==g)return;let I=T.method;if(I==="view/gap"||I==="session/closed"){b(new Error(`Muse ${I}: the conversation cannot continue without reopening`));return}if(I==="turn/unqueued"&&k.turnId===w.id){w.outcome="cancelled",y(w,new Hs("Muse queued turn cancelled","external"));return}I==="turn/started"&&k.turnId===w.id&&(w.queued=!1);let C=k.item,M=k.turnId??C?.turnId;if(M&&M!==w.id||I==="session/tokenUsage"&&(w.settled||k.turnId!==w.id||!w.usage.event(k,w.id)))return;w.opts.onEvent?.(T);let D={kind:"other",raw:T};if(["item/started","item/updated","item/completed"].includes(I)&&C?.turnId===w.id&&typeof C.itemId=="string"){let F=w.items.get(C.itemId);if(F&&typeof C.revision=="number"&&C.revision<=F.revision)return;w.items.set(C.itemId,{...C}),(C.kind==="toolCall"||C.kind==="userShell")&&I!=="item/updated"?D={kind:I==="item/completed"?"tool_result":"tool_use",id:C.itemId,tool:C.tool??C.kind,summary:C.failureReason??C.fallbackText,...I==="item/completed"?{status:C.status==="completed"?"ok":"error"}:{},...C.durationMs!==void 0?{elapsedMs:C.durationMs}:{},raw:T}:C.kind==="reasoning"?D={kind:"thinking",raw:T}:C.kind==="agentMessage"&&(D={kind:"text",raw:T})}else if(I==="item/delta"&&typeof k.itemId=="string"&&typeof k.delta=="string"){let F=w.items.get(k.itemId);if(!F)return;F.kind==="agentMessage"&&(k.field===void 0||k.field==="text")?(F.text=(F.text??"")+k.delta,w.cancelled||w.opts.onDelta?.(k.delta),D={kind:"text",raw:T}):F.kind==="reasoning"&&(D={kind:"thinking",raw:T})}if(w.cancelled||w.opts.onProgress?.(D),I!=="turn/completed"||k.turnId!==w.id)return;if(!["completed","failed","cancelled"].includes(k.terminal)){b(new Error(`Muse returned an unknown turn terminal: ${String(k.terminal)}`));return}if(w.cancelled||k.terminal==="cancelled"){w.outcome="cancelled",y(w,new Hs("Muse turn cancelled",w.cancelled?"external":"provider"));return}if(k.terminal!=="completed"){w.outcome="error",y(w,new Error(k.error?.message??k.reason??`Muse turn ended with ${String(k.terminal)}`));return}let j=[...w.items.values()].filter(F=>F.kind==="agentMessage");y(w,void 0,{text:j.map(F=>typeof F.text=="string"?F.text:"").join(`
|
|
2283
|
-
`),sessionId:g,durationMs:typeof k.durationMs=="number"?k.durationMs:Date.now()-w.started,stopReason:k.terminal,...j.some(
|
|
2283
|
+
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)r({success:!0});else{let u=js(o).trim(),d=js(i).trim(),m=u||d;r({success:!1,...n?.signal?.aborted?{errorCode:"ABORT_ERR"}:{},error:m?Me(m,{provider:this.name}):c?`terminated by ${c}`:`exit code ${l}`})}}),s.on("error",l=>{r({success:!1,error:l.message,errorCode:l.code})})}))}resumeCommand(e,n){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:Su,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,n){let r=this.turnOptsFor(n);if(r.userConfig&&mk(r.userConfig,this.name)){let i=r.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,r,i.agent)}let s=r.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!r.signal?this.transportFn(e,{...r,binary:this.binary}):this.withTimeouts(s,e,r)}withTimeouts(e,n,r){let s=new AbortController,i,o,a="",l,c=r.sessionId,u,d=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{r.onIdleWarning?.(e),m(),s.abort(),u&&u({text:a,...l?{usage:l}:{},sessionId:c,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},m=()=>{clearTimeout(i)};r.signal&&(r.signal.aborted?(o="external",s.abort()):r.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),d();let p={...r,binary:this.binary,signal:s.signal,onUsage:g=>{l=g,r.onUsage?.(g)},onSessionId:g=>{g&&(c=g),r.onSessionId?.(g)},onDelta:g=>{a+=g,d(),r.onDelta?.(g)},onProgress:g=>{g.kind!=="api_retry"&&d(),r.onProgress?.(g)}},f=this.transportFn(n,p).then(g=>(m(),{...g,status:g.status??"ok"})).catch(g=>{throw m(),o==="external"?Object.assign(new Hs("Turn cancelled","external"),{usage:g.usage??l,sessionId:c}):g}),h=new Promise(g=>{u=g});return Promise.race([f,h])}runOneShotAgent(e,n,r){let s=pk(n.userConfig,this.name,n.sessionId,e,n.profile),i=Date.now();return new Promise((o,a)=>{let l=n.timeoutMs!==void 0&&n.timeoutMs<=0?0:fk(n.env),c=hk(s,{shell:!0,cwd:n.cwd,env:He(n.env,n.cwd,n.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m,p,f=!1,h=null,g=null,y=()=>{clearTimeout(m),m=setTimeout(()=>{!Ig(_)&&!xg(_)&&E(h,g)},100)},b=l>0?setTimeout(()=>{d=!0,c.kill(),this.name==="codex"&&E(null)},l):void 0,_="",v="";if(c.stdout?.on("data",x=>{let S=x.toString();_+=S,n.onDelta?.(S),f&&!u&&y()}),c.stderr?.on("data",x=>{v+=x.toString(),f&&!u&&y()}),n.signal){if(n.signal.aborted)return clearTimeout(b),c.kill(),a(new Error("Aborted"));n.signal.addEventListener("abort",()=>c.kill(),{once:!0})}let E=(x,S=null)=>{if(u)return;u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),this.name==="codex"&&(c.stdout?.destroy(),c.stderr?.destroy());let R=Date.now()-i,N=this.name==="codex"?uk(_):{};N.usage&&n.onUsage?.(N.usage),N.sessionId&&n.onSessionId?.(N.sessionId);let O=A=>Object.assign(A,{usage:N.usage,sessionId:N.sessionId??n.sessionId});if(this.name==="codex"&&n.signal?.aborted)a(O(new Hs("Turn cancelled","external")));else if(d)a(O(new Error(`Agent command timed out after ${l}ms`)));else if(x===0||x===null&&S===null)o({text:_.trim(),sessionId:N.sessionId??n.sessionId,durationMs:R,...N.usage?{usage:N.usage}:{}});else{let A=v.trim();a(O(new De(A?Me(A,{provider:this.name}):S?`Agent command terminated by ${S}`:`Agent command exited with code ${x}`,x,S,v)))}};this.name==="codex"?(c.on("close",(x,S)=>E(x,S)),c.on("exit",(x,S)=>{u||(f=!0,h=x,g=S,y(),p=setTimeout(()=>E(x,S),5e3))})):c.on("exit",(x,S)=>E(x,S)),c.on("error",x=>{u||(u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),a(x))})})}}});function _k(t){if(!t.length)return;let e={...t[0]},n=new Set(t.map(r=>r.modelReported).filter(r=>r!==null));for(let r of t.slice(1)){for(let s of["inputUncached","cacheRead","cacheWrite","output","reasoning"]){let i=e[s],o=r[s];i!==null&&o!==null&&We(i+o)===null&&(e.invalidCounters=!0),e[s]=i===null||o===null?null:We(i+o)}e.invalidCounters||=r.invalidCounters,e.reason||=r.reason}return e.modelReported=n.size===1?[...n][0]:null,e.mixedModels=n.size>1,(e.invalidCounters||["inputUncached","cacheRead","cacheWrite","output"].some(r=>e[r]===null))&&(e.reason="counter_not_exposed"),e}var We,zr,yk,Ru,Hi,xu=L(()=>{"use strict";Qo();We=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,zr=t=>typeof t=="string"&&t.length>0&&t!=="<synthetic>"?t:null,yk=()=>({source:"wire",inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:null});Ru=class{constructor(e,n){this.session=e;this.seen=n}parts=[];event(e,n){if(e.sessionId!==this.session||e.turnId!==n||!e.usage||typeof e.usage!="object")return!1;let r=e.sourceRange,s=zr(r?.first?.id),i=zr(r?.last?.id),o=zr(r?.stream?.id),a=zr(r?.stream?.kind),l=s&&i&&o&&a?JSON.stringify([this.session,a,o,s,i]):zr(e.viewCursor)?JSON.stringify([this.session,e.viewCursor]):null;if(l&&this.seen.has(l))return!1;l&&this.seen.add(l);let c=e.usage,u=We(e.promptTokens),d=We(c.outputTokens),m=We(c.cacheReadTokens),p=We(c.cacheWriteTokens),f=u===0,h=m??(f?0:null),g=p??(f?0:null),y=u!==null&&h!==null&&g!==null&&h+g<=u?u-h-g:null,b=(h??0)>0||(g??0)>0,_={...yk(),inputUncached:y,cacheRead:h,cacheWrite:g,output:d,reasoning:We(c.reasoningTokens),modelReported:zr(e.modelId),invalidCounters:wn([e.promptTokens,e.totalTokens,c.inputTokens,c.cachedTokens,c.cacheReadTokens,c.cacheWriteTokens,c.outputTokens,c.reasoningTokens])||b||y===null||d===null||We(e.totalTokens)!==null&&u!==null&&d!==null&&e.totalTokens!==u+d||We(c.reasoningTokens)!==null&&d!==null&&c.reasoningTokens>d};return this.parts.push(_),!0}usage(){return _k(this.parts)}},Hi=class{constructor(e,n,r){this.session=e;this.boundary=n;this.seen=r}parts=new Map;ownershipUncertain=!1;latestSnapshot;invalidateOwnership(){this.ownershipUncertain=!0,this.latestSnapshot&&(this.latestSnapshot.invalidCounters=!0,this.latestSnapshot.reason="counter_not_exposed")}update(e,n=1/0){let r=e.filter(l=>We(l.seq)!==null&&l.seq>this.boundary&&l.seq<=n),s=r.find(l=>l.type==="turn/start")?.data?.turn,i=new Set(r.map(l=>l.data?.turn).filter(l=>We(l)!==null)),o=this.ownershipUncertain||i.size>1,a=new Map;for(let l of r){let c=l.data;if(!c||s!==void 0&&c.turn!==s)continue;let u=l.type==="assistant/message",d=u?c.usage:l.type==="assistant/chunk"&&c.chunk?.type==="usage"?c.chunk.usage:void 0;if(!d||typeof d!="object")continue;let m=We(c.turn)!==null&&We(c.step)!==null?["step",c.turn,c.step]:zr(c.message?.id)?["message",c.message.id]:["seq",l.seq],p=JSON.stringify([this.session,...m]);if(this.seen.has(p))continue;let f=a.get(p);(!f||u||!f.final)&&a.set(p,{record:l,final:u})}this.parts=new Map;for(let[l,{record:c,final:u}]of a){let d=c.data,m=u?d.usage:d.chunk.usage;this.parts.set(l,{...yk(),inputUncached:We(m.inputTokens),cacheRead:We(m.cacheReadTokens),output:We(m.outputTokens),reasoning:We(m.reasoningTokens),modelReported:zr(d.message?.source?.model),invalidCounters:o||[m.inputTokens,m.cacheReadTokens,m.outputTokens].some(p=>We(p)===null)||wn([m.inputTokens,m.cacheReadTokens,m.outputTokens,m.reasoningTokens])||We(m.reasoningTokens)!==null&&We(m.outputTokens)!==null&&m.reasoningTokens>m.outputTokens})}}lastUsage(){let e=[...this.parts.values()].at(-1);return e?{...e}:void 0}usage(){let e=_k([...this.parts.values()]);return e&&this.ownershipUncertain&&(e.invalidCounters=!0,e.reason="counter_not_exposed"),this.latestSnapshot=e,e}finish(){for(let e of this.parts.keys())this.seen.add(e)}}});import{spawn as p1}from"node:child_process";import{randomBytes as f1}from"node:crypto";import{realpath as Iu}from"node:fs/promises";function Na(){let t=f1(16);t.writeUIntBE(Date.now(),0,6),t[6]=t[6]&15|112,t[8]=t[8]&63|128;let e=t.toString("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}async function Au(t){if(t.signal?.aborted)throw new Error("Aborted");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t.sessionId))throw new Error("Muse requires a native session UUID");let e=t.permissionMode==="plan",n=["serve",...e?["--disable-write","--disable-shell"]:["--disable-sandbox","--trust-workspace"],...t.model?["--model",t.model]:[]];Ge("muse",n,t.permissionMode??"yolo");let r=p1(t.progPath??"muse",n,{cwd:t.cwd,env:He(t.env,t.cwd,t.sessionId),stdio:["pipe","pipe","pipe"]}),s,i=new Set,o=new Set,a,l,c=!1,u=!1,d=!1,m=!1,p=0,f=wS(),h=Date.now(),g=t.sessionId;r.stderr.setEncoding("utf8"),r.stderr.on("data",w=>{f.append(w)});let y=(w,T,k)=>{if(s===w){if(s=void 0,w.id&&o.add(w.id),T){let I=w.usage.usage()??(w.outcome?{source:null,inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:"turn_not_completed"}:void 0);Object.assign(T,{usage:I?{...I,outcome:w.outcome}:void 0,sessionId:g})}else k&&(k.usage=w.usage.usage());w.cleanup(),w.drained(),w.settled||(w.settled=!0,T?w.reject(T):(p++,w.resolve(k)))}},b=w=>{a||(a=w,s&&y(s,a),v.close(a),!m&&!c&&be(r,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{}))},_=(w,T)=>{let k=T.params;if(!k||k.sessionId!==g)return;let I=T.method;if(I==="view/gap"||I==="session/closed"){b(new Error(`Muse ${I}: the conversation cannot continue without reopening`));return}if(I==="turn/unqueued"&&k.turnId===w.id){w.outcome="cancelled",y(w,new Hs("Muse queued turn cancelled","external"));return}I==="turn/started"&&k.turnId===w.id&&(w.queued=!1);let C=k.item,M=k.turnId??C?.turnId;if(M&&M!==w.id||I==="session/tokenUsage"&&(w.settled||k.turnId!==w.id||!w.usage.event(k,w.id)))return;w.opts.onEvent?.(T);let D={kind:"other",raw:T};if(["item/started","item/updated","item/completed"].includes(I)&&C?.turnId===w.id&&typeof C.itemId=="string"){let $=w.items.get(C.itemId);if($&&typeof C.revision=="number"&&C.revision<=$.revision)return;w.items.set(C.itemId,{...C}),(C.kind==="toolCall"||C.kind==="userShell")&&I!=="item/updated"?D={kind:I==="item/completed"?"tool_result":"tool_use",id:C.itemId,tool:C.tool??C.kind,summary:C.failureReason??C.fallbackText,...I==="item/completed"?{status:C.status==="completed"?"ok":"error"}:{},...C.durationMs!==void 0?{elapsedMs:C.durationMs}:{},raw:T}:C.kind==="reasoning"?D={kind:"thinking",raw:T}:C.kind==="agentMessage"&&(D={kind:"text",raw:T})}else if(I==="item/delta"&&typeof k.itemId=="string"&&typeof k.delta=="string"){let $=w.items.get(k.itemId);if(!$)return;$.kind==="agentMessage"&&(k.field===void 0||k.field==="text")?($.text=($.text??"")+k.delta,w.cancelled||w.opts.onDelta?.(k.delta),D={kind:"text",raw:T}):$.kind==="reasoning"&&(D={kind:"thinking",raw:T})}if(w.cancelled||w.opts.onProgress?.(D),I!=="turn/completed"||k.turnId!==w.id)return;if(!["completed","failed","cancelled"].includes(k.terminal)){b(new Error(`Muse returned an unknown turn terminal: ${String(k.terminal)}`));return}if(w.cancelled||k.terminal==="cancelled"){w.outcome="cancelled",y(w,new Hs("Muse turn cancelled",w.cancelled?"external":"provider"));return}if(k.terminal!=="completed"){w.outcome="error",y(w,new Error(k.error?.message??k.reason??`Muse turn ended with ${String(k.terminal)}`));return}let j=[...w.items.values()].filter($=>$.kind==="agentMessage");y(w,void 0,{text:j.map($=>typeof $.text=="string"?$.text:"").join(`
|
|
2284
|
+
`),sessionId:g,durationMs:typeof k.durationMs=="number"?k.durationMs:Date.now()-w.started,stopReason:k.terminal,...j.some($=>$.truncated)?{warnings:["Muse reported a truncated response; inspect the native transcript for complete content"]}:{}})},v=Gr(r,{provider:"muse",protocol:"msp",onProtocolError:b,onNotification:w=>{if(h=Date.now(),w.method==="view/gap"||w.method==="session/closed"){w.params?.sessionId===g&&!c&&b(new Error(`Muse ${w.method}: session must be reopened`));return}let T=s;T&&(T.id?_(T,w):T.events.push(w))}}),E=async(w,T,k=Na())=>(await v.sendRpc(w,{...T,commandId:k})).result,x=w=>{!w.id||w.interruptSent||s!==w||(w.interruptSent=!0,E("turn/interrupt",{sessionId:g,turnId:w.id}).catch(T=>{s===w&&b(T instanceof Error?T:new Error(String(T)))}))},S=w=>{!w.id||w.unqueueSent||s!==w||(w.unqueueSent=!0,E("turn/unqueue",{sessionId:g,turnId:w.id}).catch(T=>{let k=T instanceof Error?T.message:String(T);/already started|not queued|launch boundary|turn is running/i.test(k)?(w.queued=!1,x(w)):s===w&&b(T instanceof Error?T:new Error(k))}))},R=w=>{w.queued?S(w):x(w)};r.on("error",w=>b(new Error(`Unable to start Muse: ${w.message}`)));let N=()=>{c||m||a||d||(d=!0,be(r,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(w=>b(w instanceof Error?w:new Error(String(w)))))};r.stdin.on("error",N),r.stdout.on("end",N),r.on("exit",()=>{m=!0}),r.on("close",(w,T)=>{m=!0,c?v.close(new Error("Muse session closed")):b(new Error(Fi(`Muse exited (${T??w}) after ${p} completed prompt(s)`,f.text().trim()?Me(f.text(),{provider:"muse"}):""))),s&&y(s,new Error("Muse session closed"))});let O=()=>{if(l)return l;c=!0;let w=!!s;return s&&(s.cancelled=!0,R(s)),l=(async()=>{m||(await new Promise(T=>In(u?t.holdOpen:void 0,{isAborted:()=>w,hasChildExited:()=>m,isTurnInFlight:()=>!!s,lastEventAtMs:()=>h,closeStdin:()=>{r.stdin.end(),T()},label:"muse"})),await be(r,{stdinEnd:!1,softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{})),s&&y(s,new Error("Muse session closed")),v.close(new Error("Muse session closed"))})(),l},A=()=>{b(new Error("Aborted")),O()};t.signal?.addEventListener("abort",A,{once:!0});try{if(t.signal?.aborted)throw new Error("Aborted");let w=(await v.sendRpc("initialize",{clientInfo:{name:"lmctl",version:"1"}})).result;if(w?.schema?.version!==1)throw new Error("Muse MSP schema version is unsupported");if(t.expectedHome&&(typeof w.museHome!="string"||await Iu(w.museHome)!==await Iu(t.expectedHome)))throw new Error("Muse data home does not match the configured session reader");if(w.sessionDurability!==void 0&&w.sessionDurability!=="durable")throw new Error("Muse did not provide durable sessions");v.sendNotification("initialized");let T=e?"denyUnmatched":"allowAll",I=(t.create?await E("session/start",{sessionId:g,workspaceRoot:t.cwd,approvalMode:T,...t.model?{modelId:t.model}:{}}):await E("session/resume",{sessionId:g,excludeItems:!0}))?.session;if(I?.sessionId!==g)throw new Error(`Muse did not return requested session "${g}"`);if(typeof I.workspaceRoot!="string"||await Iu(I.workspaceRoot)!==await Iu(t.cwd))throw new Error("Muse session belongs to a different working directory");if(I.activeTurnId||I.status!=="idle")throw new Error(`Muse session is not idle (${String(I.status)})`);if((await E("session/setApprovalMode",{sessionId:g,mode:T}))?.effectiveMode?.mode!==T)throw new Error("Muse did not apply the requested approval mode");if(!t.create&&t.model&&I.modelId!==t.model&&(await E("session/setModel",{sessionId:g,model:{modelId:t.model,...I.providerId?{providerId:I.providerId}:{}}}))?.status!=="accepted")throw new Error("Muse did not accept the requested model");u=!0}catch(w){throw await O(),a??w}finally{t.signal?.removeEventListener("abort",A)}return{provider:"muse",sessionId:g,get completedTurns(){return p},close:O,async sendTurn(w,T={}){if(s?.cancelled&&await s.drain,a)throw new Error(a.message);if(c)throw new Error("Muse session is closed");if(s)throw new Error("Muse already has an active turn");if(T.signal?.aborted)throw new Error("Aborted");return new Promise((k,I)=>{let C,M=new Promise($=>{C=$}),D={usage:new Ru(g,i),commandId:Na(),events:[],items:new Map,opts:T,started:Date.now(),cancelled:!1,interruptSent:!1,unqueueSent:!1,queued:!1,settled:!1,resolve:k,reject:I,drain:M,drained:C,cleanup:()=>{}};s=D;let j=()=>{D.cancelled=!0,D.settled=!0,I(Object.assign(new Error("Aborted"),{usage:D.usage.usage(),sessionId:g})),R(D)};D.cleanup=()=>T.signal?.removeEventListener("abort",j),T.signal?.addEventListener("abort",j,{once:!0}),E("turn/start",{sessionId:g,input:[{type:"text",text:w}],...t.effort?{reasoningEffort:t.effort}:{}},D.commandId).then($=>{if(s===D){if($?.commandId!==D.commandId||$.status!=="accepted"||!["started","queued"].includes($.disposition)||typeof $.turnId!="string"||$.turnId.length===0||o.has($.turnId)){b(new Error("Muse did not admit a fresh turn; refusing ambiguous dispatch"));return}D.id=$.turnId,D.queued=$.disposition==="queued",D.cancelled&&R(D);for(let Z of D.events)s===D&&_(D,Z);D.events=[]}},$=>{s===D&&y(D,$ instanceof Error?$:new Error(String($)))})})}}}var vk=L(()=>{"use strict";xu();dt();ag();Us();mn();wa();An();dn()});import{join as Ng}from"node:path";import{mkdir as g1}from"node:fs/promises";function Og(t={}){let e=tc(t.museDataHome),n=s=>({...s??process.env,XDG_DATA_HOME:e}),r=async(s,i)=>{if(i.bundleSession)return cr(i.bundleSession,"muse",i.sessionId,s,i);let o=i.sessionId||Na(),a=await Au({...i,sessionId:o,create:i.sessionId==="",env:n(i.env),expectedHome:Ng(e,"muse")});try{return await a.sendTurn(s,i)}finally{await a.close()}};return new class extends we{constructor(){super({provider:new ec({museDataHome:e}),protocol:{transport:"muse-msp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"muse",seedArgs:[],startTemplate:"muse",resumeTemplate:"muse resume {{session_id}}",transport:r})}openSession(s){return Au({...s,env:n(s.env),expectedHome:Ng(e,"muse")})}async seed(s,i){await g1(s,{recursive:!0});let o=Na(),a,l;try{a=await Au({sessionId:o,cwd:s,create:!0,env:n(i?.env),signal:i?.signal,expectedHome:Ng(e,"muse"),model:i?.model,effort:i?.effort}),i?.signal?.throwIfAborted();try{i?.onDispatch?.()}catch{}let c=await a.sendTurn(i?.prompt??ue,{signal:i?.signal});if(l=c.usage,await a.close(),!await this.load(o))throw new Error("Muse seed did not persist a readable native session");return{success:!0,sessionId:o,usage:c.usage}}catch(c){return{success:!1,sessionId:o,usage:c?.usage??l,error:`Muse seed failed: ${c instanceof Error?c.message:String(c)}`}}finally{await a?.close()}}}}var Lg=L(()=>{"use strict";dt();Ep();vk();Vr();nt()});function wk(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=[];for(let n=0;n<t.length;n++)n===0?e.push(t[n]):e.push(`
|
|
2284
2285
|
|
|
2285
2286
|
--- additional response (turn ${n+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
2286
2287
|
|
|
@@ -2289,13 +2290,13 @@ One possible cause: the provider stream ended before a complete response was del
|
|
|
2289
2290
|
${Me(e,{provider:t.tool})}
|
|
2290
2291
|
|
|
2291
2292
|
${r}`:r}function Ak(t){let e=t.tool||"claude",n=t.binaryPath||y1[e]||"claude",r=["-p","","--output-format","stream-json","--input-format","stream-json"];e==="claude"&&r.push("--verbose"),t.sessionId&&r.push("--resume",t.sessionId),t.model&&r.push("--model",t.model);let s=t.permissionMode??"yolo",i=Xr(e,s)??v1[e]??["--dangerously-skip-permissions"];if(r.push(...i),Ge(e,r,s),t.cwd&&!kk(t.cwd))throw X({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new Ne(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=He(t.env,t.cwd,t.sessionId);return{tool:e,binary:n,args:r,spawnEnv:e==="claude"?MS(o):o}}function Ck(t,e){return new Promise((n,r)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=Ak(e))}catch(q){return r(q instanceof Error?q:new Error(String(q)))}let c=Sk(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",q=>{Qe(`stream-json: stdin pipe error, ignored (exit handler reports): ${q.message}`)});let u=!1;if(e.signal){if(e.signal.aborted)return u=!0,X({event:"transport_abort",provider:i,phase:"pre_spawn"}),be(c).catch(()=>{}),r(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,X({event:"transport_abort",provider:i}),be(c).catch(()=>{}),r(Object.assign(new Error("Aborted"),{usage:M.usage()}))},{once:!0})}let d="",m=!1,p=!1,f=0,h=!1,g="",y="",b,_,v=null,E=null,x=!1,S=!1,R=Rk(),N=xk();function O(){b!==void 0&&(clearTimeout(b),b=void 0)}function A(){_!==void 0&&(clearTimeout(_),_=void 0)}let w=null;function T(){return m||u||M.sawResult()}function k(q){return q==="text_done"?R:N}async function I(q){if(q==="text_done"?b=void 0:_=void 0,T()||v!==null)return;w??=Date.now();let Y=k(q);if(e.holdOpen){let me=(e.holdOpen.maxHoldMs??pu)-(Date.now()-w),ee=me>0?await fu(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),me,e.signal):!1;if(T()||(q==="text_done"?b!==void 0:_!==void 0))return;if(ee===!0){X({event:"transport_stall_grace_deferred",provider:i,grace_kind:q,grace_ms:Y,reason:"outstanding_dispatched_work"}),C(q);return}}E=q,v=q==="text_done"?`${i} finished responding but never emitted its closing result event (${Y}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${Y}ms of silence)`,X({event:"transport_stall_grace_fired",provider:i,grace_kind:q,grace_ms:Y}),be(c).catch(()=>{})}function C(q){let Y=setTimeout(()=>{I(q)},k(q));Y.unref?.(),q==="text_done"?(O(),b=Y):(A(),_=Y)}let M=Cu({usageState:i==="claude"?Mg(!!e.sessionId):void 0,onEvent:q=>{f=Date.now(),h=q.type!=="result",q.type==="system"&&q.subtype==="init"&&(y=q.session_id||y),q.type==="assistant"?(x=!Ik(q),S=x&&q.message?.stop_reason==="pause_turn"):(q.type==="result"||q.type==="user")&&(x=!1,S=!1),O(),i==="claude"&&x&&!S&&!M.sawResult()&&C("text_done"),A(),i==="claude"&&!M.sawResult()&&C("tool_use_silence"),e.onEvent?.(q)},onText:q=>{g+=q,e.onText?.(q)}});function D(){p||(p=!0,In(e.holdOpen,{isAborted:()=>u,hasChildExited:()=>m,isTurnInFlight:()=>h,lastEventAtMs:()=>f,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function j(q){let Y=M.sawResult();M.processLine(q);let ne=M.usage();ne&&e.onUsage?.(ne),!Y&&M.sawResult()&&D()}c.stdout?.on("data",q=>{d+=q.toString();let Y=d.split(`
|
|
2292
|
-
`);d=Y.pop()||"";for(let ne of Y)j(ne)});let
|
|
2293
|
-
${Me(
|
|
2294
|
-
${Me(
|
|
2295
|
-
`),Qe(`stream-json: prompt sent (${t.length} chars)`)})}function b1(t){return t==="qwen"?[Nu(ae,".qwen","projects")]:[Nu(ae,".claude","projects")]}async function Tk(t,e,n){let r=n??b1(t),s=null;for(let a of r){let l;try{l=await h1(a)}catch{continue}for(let c of l){for(let u of[Nu(a,c,`${e}.jsonl`),Nu(a,c,"chats",`${e}.jsonl`)])if(kk(u)){s=u;break}if(s!==null)break}if(s!==null)break}if(s===null)throw new Error(`stream-json bundle: no session file for session "${e}" under ${r.join(", ")} \u2014 the session must exist on disk before a bundle can resume it`);let o=(await Ht(s,5).catch(()=>[])).map(a=>a?.sessionId).find(a=>typeof a=="string"&&a.length>0);if(o!==e)throw new Error(`stream-json bundle: session file ${s} header does not match the requested session (expected "${e}", header carries ${o??"no sessionId"}) \u2014 the session was likely re-seeded externally; aborting instead of writing into the wrong session`)}async function Nk(t){let{tool:e,binary:n,args:r,spawnEnv:s}=Ak(t),i=Sk(n,r,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",B=>{Qe(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${B.message}`)});let a={exited:!1,exitCode:null,signal:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=e==="claude"?Mg(!!t.sessionId):void 0,u=c?.resultIds??new Set,d=null,m="";i.stderr?.on("data",B=>{m+=B.toString()});let p="",f="",h=!1,g=!1,y=null,b=null,_=null,v,E,x=Rk(),S=xk(),R=null,N=[],O=()=>a.exited?Promise.resolve():new Promise(B=>{N.push(B)}),A=()=>new De(`stream-json bundle process (${e}) exited${a.signal!==null?` by ${a.signal}`:a.exitCode!==null?` with code ${a.exitCode}`:""} after ${a.completedTurns} completed prompt(s); the bundle cannot continue`,a.exitCode,a.signal,m);function w(){v!==void 0&&(clearTimeout(v),v=void 0)}function T(){E!==void 0&&(clearTimeout(E),E=void 0)}function k(){return a.exited||R===null||R.aborted||R.processor.sawResult()}function I(B){return B==="text_done"?x:S}async function C(B){if(B==="text_done"?v=void 0:E=void 0,k()||y!==null)return;_??=Date.now();let W=I(B);if(t.holdOpen){let
|
|
2296
|
-
`);ne=W.pop()||"";for(let
|
|
2297
|
-
${
|
|
2298
|
-
${kt}`:
|
|
2293
|
+
`);d=Y.pop()||"";for(let ne of Y)j(ne)});let $="";c.stderr?.on("data",q=>{$+=q.toString()}),c.on("error",q=>{X({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:q.message}),r(new Ne(`Failed to spawn ${o}: ${q.message}`,{cause:q}))}),c.on("exit",(q,Y)=>{if(m=!0,O(),A(),u)return;d.trim()&&j(d);let ne=M.finalize();if(ne?.isError)X({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:ne.errorMessage}),r(Object.assign(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${ne.errorMessage??"unknown error"}`),{usage:ne.usage,sessionId:ne.sessionId}));else if(ne)Qe(`stream-json: result ${ne.result.slice(0,80)}${ne.result.length>80?"...":""} (${ne.durationMs}ms)`),n({result:ne.result,sessionId:ne.sessionId,durationMs:ne.durationMs,numTurns:ne.numTurns,usage:ne.usage,exitCode:q});else if(v!==null&&E==="text_done"&&g.trim().length>0)X({event:"transport_stall_finalized",provider:i,reason:v,text_len:g.length}),n({result:g,sessionId:y||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:q,warnings:[v]});else if(v!==null&&E==="tool_use_silence"){let me=$.trim()?`
|
|
2294
|
+
${Me($,{provider:i})}`:"",ee=`${v} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(e.sessionId?` (session=${e.sessionId})`:"")+me;X({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:q,signal:Y,stderr_summary:ee}),r(new De(ee,q,Y,$))}else{let me=v!==null?`${v} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:"")+($.trim()?`
|
|
2295
|
+
${Me($,{provider:i})}`:""):_1({tool:i,exitCode:q,signal:Y,stderr:$});X({event:"transport_error",provider:i,error_class:"Error",reason:v!==null?"provider_stalled_no_content":"provider_no_result",exit_code:q,signal:Y,stderr_summary:me}),r(new De(me,q,Y,$))}});let Z=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(Z+`
|
|
2296
|
+
`),Qe(`stream-json: prompt sent (${t.length} chars)`)})}function b1(t){return t==="qwen"?[Nu(ae,".qwen","projects")]:[Nu(ae,".claude","projects")]}async function Tk(t,e,n){let r=n??b1(t),s=null;for(let a of r){let l;try{l=await h1(a)}catch{continue}for(let c of l){for(let u of[Nu(a,c,`${e}.jsonl`),Nu(a,c,"chats",`${e}.jsonl`)])if(kk(u)){s=u;break}if(s!==null)break}if(s!==null)break}if(s===null)throw new Error(`stream-json bundle: no session file for session "${e}" under ${r.join(", ")} \u2014 the session must exist on disk before a bundle can resume it`);let o=(await Ht(s,5).catch(()=>[])).map(a=>a?.sessionId).find(a=>typeof a=="string"&&a.length>0);if(o!==e)throw new Error(`stream-json bundle: session file ${s} header does not match the requested session (expected "${e}", header carries ${o??"no sessionId"}) \u2014 the session was likely re-seeded externally; aborting instead of writing into the wrong session`)}async function Nk(t){let{tool:e,binary:n,args:r,spawnEnv:s}=Ak(t),i=Sk(n,r,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",B=>{Qe(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${B.message}`)});let a={exited:!1,exitCode:null,signal:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=e==="claude"?Mg(!!t.sessionId):void 0,u=c?.resultIds??new Set,d=null,m="";i.stderr?.on("data",B=>{m+=B.toString()});let p="",f="",h=!1,g=!1,y=null,b=null,_=null,v,E,x=Rk(),S=xk(),R=null,N=[],O=()=>a.exited?Promise.resolve():new Promise(B=>{N.push(B)}),A=()=>new De(`stream-json bundle process (${e}) exited${a.signal!==null?` by ${a.signal}`:a.exitCode!==null?` with code ${a.exitCode}`:""} after ${a.completedTurns} completed prompt(s); the bundle cannot continue`,a.exitCode,a.signal,m);function w(){v!==void 0&&(clearTimeout(v),v=void 0)}function T(){E!==void 0&&(clearTimeout(E),E=void 0)}function k(){return a.exited||R===null||R.aborted||R.processor.sawResult()}function I(B){return B==="text_done"?x:S}async function C(B){if(B==="text_done"?v=void 0:E=void 0,k()||y!==null)return;_??=Date.now();let W=I(B);if(t.holdOpen){let pe=(t.holdOpen.maxHoldMs??pu)-(Date.now()-_),kt=pe>0?await fu(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),pe,void 0):!1;if(k()||(B==="text_done"?v!==void 0:E!==void 0))return;if(kt===!0){X({event:"transport_stall_grace_deferred",provider:e,grace_kind:B,grace_ms:W,reason:"outstanding_dispatched_work"}),M(B);return}}b=B,y=B==="text_done"?`${e} finished responding but never emitted its closing result event (${W}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${W}ms of silence)`,X({event:"transport_stall_grace_fired",provider:e,grace_kind:B,grace_ms:W}),be(i).catch(()=>{})}function M(B){if(t.serviceHosted)return;let W=setTimeout(()=>{C(B)},I(B));W.unref?.(),B==="text_done"?(w(),v=W):(T(),E=W)}let D=!1,j,$,Z=new Promise((B,W)=>{j=B,$=W});Z.catch(()=>{});let q=t.serviceHosted&&t.closeTimeoutMs===void 0?void 0:setTimeout(()=>{D||(D=!0,$(new Error(`stream-json bundle: ${e} emitted no init event within the open timeout \u2014 cannot verify the resumed session identity`)))},t.closeTimeoutMs!==void 0?Math.max(t.closeTimeoutMs,5e3):3e4);q?.unref?.();function Y(B){D||(D=!0,q!==void 0&&clearTimeout(q),B?$(B):j())}let ne="";function me(B){if(a.lastEventAtMs=Date.now(),B.type==="system"&&B.subtype==="init"){if(c&&typeof B.model=="string"&&(c.model=B.model),f=B.session_id||f,t.sessionId&&typeof B.session_id=="string"&&B.session_id.length>0&&B.session_id!==t.sessionId){let J=new Error(`stream-json bundle: provider resumed a different session (init reported "${B.session_id}", expected "${t.sessionId}")`);Y(J),be(i).catch(()=>{});return}Y()}let W=R?.processor.sawResult()??!0;B.type==="assistant"?(h=!Ik(B),g=h&&B.message?.stop_reason==="pause_turn"):(B.type==="result"||B.type==="user")&&(h=!1,g=!1),w(),e==="claude"&&a.turnActive&&h&&!g&&!W&&M("text_done"),T(),e==="claude"&&a.turnActive&&!W&&M("tool_use_silence")}function ee(){let B=R;if(B===null)return;let W=B.processor.finalize();if(W!==null){if(R=null,a.turnActive=!1,w(),T(),W.isError){X({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:W.errorMessage}),B.reject(Object.assign(new Error(`${e} reported an error for this turn (no assistant output)`+(t.sessionId?` \u2014 session=${t.sessionId}`:"")+`: ${W.errorMessage??"unknown error"}`),{usage:W.usage,sessionId:W.sessionId}));return}a.completedTurns+=1,l=W.sessionId||l,Qe(`stream-json bundle: result ${W.result.slice(0,80)}${W.result.length>80?"...":""} (${W.durationMs}ms)`),B.resolve({result:W.result,sessionId:W.sessionId||l,durationMs:W.durationMs,numTurns:W.numTurns,usage:W.usage})}}function st(B){if(!B.trim())return;let W;try{W=JSON.parse(B)}catch{return}let J=Pg(W,f||l);if(J&&u.has(J))return;let pe=R;if(pe===null&&J&&(u.add(J),c&&(c.cost=null)),me(W),pe!==null){let kt=pe.processor.sawResult();pe.processor.processLine(B),pe.onEventForward?.(W),!kt&&pe.processor.sawResult()&&ee()}}i.stdout?.on("data",B=>{ne+=B.toString();let W=ne.split(`
|
|
2297
|
+
`);ne=W.pop()||"";for(let J of W)st(J)}),i.on("error",B=>{if(d=new Ne(`Failed to spawn ${n}: ${B.message}`,{cause:B}),X({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:B.message}),Y(d),R!==null){let W=R;R=null,a.turnActive=!1,W.reject(d)}}),i.on("exit",(B,W)=>{a.exited=!0,a.exitCode=B,a.signal=W,w(),T(),ne.trim()&&st(ne),Y(a.exited&&!D?new De(`stream-json bundle: ${e} ${W?`terminated by ${W}`:`exited (code ${String(B)})`} before its init event`,B,W):void 0);let J=R;if(J!==null&&(R=null,a.turnActive=!1,!J.aborted))if(y!==null&&b==="text_done"&&p.trim().length>0)X({event:"transport_stall_finalized",provider:e,reason:y,text_len:p.length}),J.resolve({result:p,sessionId:f||t.sessionId||"",durationMs:Date.now()-J.startMs,numTurns:1,warnings:[y]});else if(y!==null&&b==="tool_use_silence"){let pe=m.trim()?Me(m,{provider:e}):"";X({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:B,signal:W,...pe?{stderr_summary:pe}:{}}),J.reject(new De(`${y} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(t.sessionId?` (session=${t.sessionId})`:"")+(pe?`
|
|
2298
|
+
${pe}`:""),B,W,m))}else{let pe=A(),kt=m.trim()?Me(m,{provider:e}):"";X({event:"transport_error",provider:e,error_class:"Error",reason:y!==null?"provider_stalled_no_content":"provider_no_result",exit_code:B,signal:W,...kt?{stderr_summary:kt}:{}}),J.reject(new De(kt?`${pe.message}
|
|
2299
|
+
${kt}`:pe.message,B,W,m))}for(let pe of N.splice(0))pe()}),i.on("close",(B,W)=>{if(!a.exited){a.exited=!0,a.exitCode=B,a.signal=W,w(),T(),D||Y(new De(`stream-json bundle: ${e} ${W?`terminated by ${W}`:`closed (code ${String(B)})`} before its init event`,B,W));for(let J of N.splice(0))J()}});try{t.sessionId&&await Tk(e,t.sessionId,t.sessionFileRoots),await Z}catch(B){let W=d??(B instanceof Error?B:new Error(String(B)));if(t.serviceHosted&&t.closeTimeoutMs===void 0)i.stdin?.end(),await O();else{let J=t.closeTimeoutMs??2e3;await be(i,{softDelayMs:Math.min(1e3,J),killDelayMs:Math.min(1e3,J)}).catch(()=>{})}throw W}let Ve=B=>new Promise(W=>{setTimeout(W,B).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(B,W={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw A();if(R!==null)throw new Error(`stream-json bundle session (${e}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);let J=()=>(a.closed=!0,be(i).catch(()=>{}),new Error("Aborted"));if(W.signal?.aborted)throw J();if(t.sessionId&&(await Tk(e,t.sessionId,t.sessionFileRoots),a.exited))throw A();if(W.signal?.aborted)throw J();return p="",h=!1,g=!1,y=null,b=null,_=null,new Promise((pe,kt)=>{let ei=Cu({usageState:c,resultIds:u,sessionId:f||l,onText:F=>{p+=F,W.onText?.(F)}}),ti={processor:ei,resolve:pe,reject:kt,startMs:Date.now(),aborted:!1,onEventForward:W.onEvent};R=ti,a.turnActive=!0;let ni=()=>{ti.aborted=!0,X({event:"transport_abort",provider:e}),a.closed=!0,be(i).catch(()=>{}),R===ti&&(R=null,a.turnActive=!1),kt(Object.assign(new Error("Aborted"),{usage:ei.usage()}))};W.signal?.addEventListener("abort",ni,{once:!0});let cl=JSON.stringify({type:"user",message:{role:"user",content:B}});i.stdin?.write(`${cl}
|
|
2299
2300
|
`),Qe(`stream-json bundle: prompt sent (${B.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(B=>{In(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),B()},label:e})}):i.stdin?.end(),!a.exited)){let B=t.closeTimeoutMs;if(B===void 0&&t.serviceHosted)await O();else{let W=B??2e3;await Promise.race([O(),Ve(W)]),a.exited||await be(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,W),killDelayMs:Math.min(1e3,W)}).catch(()=>{})}}})()),a.closing}}}var y1,v1,Fg=L(()=>{"use strict";qr();Us();An();Re();wa();mn();Dg();Xe();dn();Dg();y1={claude:"claude",qwen:"qwen"};v1={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function Ou(t={}){return[]}var $g=L(()=>{"use strict"});function jg(t){return t==="plan"?"read-only":"danger-full-access"}function Ok(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function Lu(){return{agentItems:new Map,resultText:""}}function Wi(t,e,n,r){let s=t.method;if(!s)return!1;let i=t.params;if(s==="turn/started")return e.agentItems.clear(),e.resultText="",!1;if(s==="item/started"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=typeof o.phase=="string"?o.phase:void 0,l=a==="commentary"||a==="final_answer"?a:void 0;return e.agentItems.set(o.id,{phase:l,buffer:""}),!0}return!1}if(s==="item/agentMessage/delta"){let o=i?.delta||"",a=typeof i?.itemId=="string"?i.itemId:void 0;if(!o)return!0;let l=a?e.agentItems.get(a):void 0;return l?(l.phase==="commentary"||(l.buffer+=o),n?.(o),l.phase&&i&&(i._lmctlItemPhase=l.phase)):(e.resultText+=o,n?.(o)),!0}if(s==="item/completed"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=e.agentItems.get(o.id);if(a){if(a.phase!=="commentary"){let l=typeof o.text=="string"?o.text:a.buffer;if(r&&typeof o.text=="string"&&o.text!==a.buffer){let c=typeof i?.threadId=="string"?i.threadId:void 0,u=typeof i?.turnId=="string"?i.turnId:void 0;r({itemId:o.id,threadId:c,turnId:u,expectedFromItemText:o.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(o.id)}return!0}return!1}return!1}function Mu(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function Lk(t){let e=t.params,n=e?.error,r=typeof n?.message=="string"?n.message:void 0,s=r&&r.length>0?r:"(no message)";return e?.willRetry===!0?{willRetry:!0}:{willRetry:!1,turnError:new Error(`Turn errored: ${s}`)}}function Pu(){return{pendingCodexError:null}}function Du(t,e){let n=Lk(t);return n.willRetry||(e.pendingCodexError=n.turnError),n}function Fu(t,e){if(e.pendingCodexError){let i=e.pendingCodexError;return e.pendingCodexError=null,{shouldReject:!0,turnError:i}}let r=t.params?.turn;if((typeof r?.status=="string"?r.status:void 0)==="failed"){let i=r?.error,o=typeof i?.message=="string"?i.message:void 0,a=o&&o.length>0?o:"(no message)";return{shouldReject:!0,turnError:new Error(`Turn errored: ${a}`)}}return{shouldReject:!1}}var Ug=L(()=>{"use strict"});import{spawn as Mk}from"node:child_process";import{createInterface as Pk}from"node:readline";import{existsSync as w1,readFileSync as E1}from"node:fs";import{fileURLToPath as T1}from"node:url";function Dk(){return Ok(S1)}function Yr(t,e){Qe(`[codex:${t}] ${JSON.stringify(e)}`)}function k1(t){let e=t.stderr.trim(),n=`lmctl: codex app-server ${t.signal?`terminated by ${t.signal}`:`exited with code ${t.exitCode}`} before completing the turn.
|
|
2300
2301
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
2301
2302
|
${Me(e,{provider:"codex"})}
|
|
@@ -2305,7 +2306,7 @@ ${n}`:n}function Fk(t){let e=t.binaryPath||"codex",n=["app-server","--listen","s
|
|
|
2305
2306
|
`)}m.on("line",O=>{let A;try{A=JSON.parse(O)}catch{return}if(typeof A.id=="number"&&p.has(A.id)){$k(l,A);let I=p.get(A.id);if(p.delete(A.id),A.error){let C=A.error,M=typeof C?.message=="string"&&C.message.length>0?C.message:JSON.stringify(A.error);I.reject(ba(`codex app-server error: ${M}`,C))}else I.resolve(A);e.onEvent?.(A);return}let w=A.method;if(!w){e.onEvent?.(A);return}if(d||!c.event(A))return;let T=c.usage();if(T&&e.onUsage?.(T),w==="thread/started"){let C=A.params?.thread;C?.id&&(h=C.id,e.onSessionId?.(h))}let k=Pe()?I=>{Yr("item.text/buffer-mismatch",{itemId:I.itemId,threadId:I.threadId??null,turnId:I.turnId??null,expectedFromItemText:I.expectedFromItemText,gotFromBuffer:I.gotFromBuffer,expectedLen:I.expectedFromItemText.length,gotLen:I.gotFromBuffer.length})}:void 0;if(w==="turn/started"){let I=A.params,C=I?.turn;C?.id&&(g=C.id),Wi(A,v,e.onDelta,k),Pe()&&Yr("turn/started",{params:I??null})}if(Pe()&&(w==="item/started"||w==="item/completed")){let I=A.params;I?.item?.type==="agentMessage"&&Yr(w,{params:I??null})}if(w==="item/started"||w==="item/agentMessage/delta"||w==="item/completed"){if(w==="item/agentMessage/delta"){let I=A.params;Pe()&&Yr("agentMessage/delta",{params:I??null})}Wi(A,v,e.onDelta,k)}if(w==="turn/completed"){c.finish();let I=A.params;if(Pe())for(let[M,D]of v.agentItems.entries())D.buffer&&Yr("turn/completed/unflushed-item",{itemId:M,phase:D.phase,bufferLen:D.buffer.length});Mu(v),Pe()&&Yr("turn/completed",{params:I??null});let C=Fu(A,E);C.shouldReject?(Pe()&&Yr("turn/completed/terminal-reject",{message:C.turnError.message}),b=!0,y=!0,a.stdin?.end(),r(u(C.turnError))):(y=!0,a.stdin?.end())}if(w==="error"){let I=Du(A,E);if(Pe()){let C=A.params,M=C?.error,D=typeof M?.message=="string"?M.message:"(no message)";Yr(I.willRetry?"error/retry":"error/terminal-deferred",{message:D,willRetry:I.willRetry,params:C??null})}}e.onEvent?.(A)});let R="";a.stderr?.on("data",O=>{R+=O.toString()});let N=O=>{X({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:O.message});let A=new Ne(`Failed to spawn codex app-server: ${O.message}`,{cause:O});for(let w of p.values())w.reject(u(A));p.clear(),r(u(A))};a.on("error",N),a.stdin?.on("error",N),a.on("exit",(O,A)=>{if(d||b)return;if(y){n({result:v.resultText,usage:c.usage(),threadId:h,turnId:g,durationMs:Date.now()-_,exitCode:O});return}if(E.pendingCodexError){r(u(E.pendingCodexError));return}let w=k1({exitCode:O,signal:A,stderr:R});X({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:O,signal:A,stderr_summary:w}),r(u(new De(w,O,A,R)))}),(async()=>{try{if(await x("initialize",Dk()),S("initialized",{}),e.threadId)try{let O=x("thread/resume",{threadId:e.threadId,sandbox:o,approvalPolicy:"never",...e.model?{model:e.model}:{}}),A,w=e.serviceHosted&&e.closeTimeoutMs===void 0?new Promise(()=>{}):new Promise((T,k)=>{A=setTimeout(()=>k(new Error("resume timeout")),3e4)});try{let k=(await Promise.race([O,w])).result?.thread?.id;if(e.requireResume&&k!==e.threadId)throw new Error(`thread/resume did not return the requested thread "${e.threadId}" (got "${k??"unknown"}")`)}finally{clearTimeout(A)}h=e.threadId,e.onSessionId?.(h)}catch(O){if(e.requireResume)throw O;process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
2306
2307
|
`),X({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:O instanceof Error?O.message:String(O)});let w=(await x("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;w?.id&&(h=w.id,e.onSessionId?.(h))}else{let A=(await x("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;A?.id&&(h=A.id,e.onSessionId?.(h))}c=l.turn(h),await x("turn/start",{threadId:h,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(O){be(a).catch(()=>{}),r(O instanceof Error?O:new Error(String(O)))}})()})}async function Uk(t){let{binary:e,codexArgs:n,sandbox:r}=Fk(t),s=Mk(e,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:He(t.env,t.cwd,t.threadId)}),i=Date.now(),o={exited:!1,exitCode:null,signal:null,completedTurns:0,closed:!1,closing:null},a=t.threadId||"",l=Rg(),c=null,u="";s.stderr?.on("data",A=>{u+=A.toString()});let d=Pk({input:s.stdout}),m=new Map,p=1;function f(A,w={}){return new Promise((T,k)=>{let I=p++;m.set(I,{resolve:T,reject:k});let C=JSON.stringify({jsonrpc:"2.0",id:I,method:A,params:w});s.stdin?.write(C+`
|
|
2307
2308
|
`)})}function h(A,w={}){let T=JSON.stringify({jsonrpc:"2.0",method:A,params:w});s.stdin?.write(T+`
|
|
2308
|
-
`)}let g=[],y=()=>o.exited?Promise.resolve():new Promise(A=>{g.push(A)}),b=()=>new De(`codex bundle process exited${o.signal!==null?` by ${o.signal}`:o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`,o.exitCode,o.signal,u),_=null,v=null,E,x,S=A=>{A.turnId&&f("turn/interrupt",{threadId:a,turnId:A.turnId}).catch(()=>{})};function R(A){let w=_;w===null||w.settled||(w.settled=!0,_=null,w.usage.finish(),A&&w.reject(Object.assign(A,{usage:w.usage.usage(),sessionId:a})))}d.on("line",A=>{let w;try{w=JSON.parse(A)}catch{return}if(typeof w.id=="number"&&m.has(w.id)){$k(l,w);let D=m.get(w.id);if(m.delete(w.id),w.error){let j=w.error
|
|
2309
|
+
`)}let g=[],y=()=>o.exited?Promise.resolve():new Promise(A=>{g.push(A)}),b=()=>new De(`codex bundle process exited${o.signal!==null?` by ${o.signal}`:o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`,o.exitCode,o.signal,u),_=null,v=null,E,x,S=A=>{A.turnId&&f("turn/interrupt",{threadId:a,turnId:A.turnId}).catch(()=>{})};function R(A){let w=_;w===null||w.settled||(w.settled=!0,_=null,w.usage.finish(),A&&w.reject(Object.assign(A,{usage:w.usage.usage(),sessionId:a})))}d.on("line",A=>{let w;try{w=JSON.parse(A)}catch{return}if(typeof w.id=="number"&&m.has(w.id)){$k(l,w);let D=m.get(w.id);if(m.delete(w.id),w.error){let j=w.error,$=typeof j?.message=="string"&&j.message.length>0?j.message:JSON.stringify(w.error);D.reject(ba(`codex app-server error: ${$}`,j))}else D.resolve(w);_?.onEvent?.(w);return}let T=w.method;if(!T){_?.onEvent?.(w);return}if(T==="thread/started"){let j=w.params?.thread;j?.id&&(a=j.id,t.onSessionId?.(a))}let k=w.params,I=k?.turnId??k?.turn?.id;if(v&&(T==="turn/started"&&!v.turnId&&I&&(v.usage.bind(I),v.usage.finish(),v.turnId=I,S(v)),T==="turn/completed"&&I===v.turnId&&(l.remember(a,I),v=null,x?.()),T.startsWith("turn/")||T.startsWith("item/")||T==="error"))return;let C=_;if(I&&C?.turnId&&I!==C.turnId||C!==null&&!C.usage.event(w))return;let M=C?.usage.usage();if(M&&C?.onUsage?.(M),T==="turn/started"&&C!==null){let j=w.params?.turn;j?.id&&(C.turnId=j.id),Wi(w,C.agentState,C.onDelta,void 0)}if(C!==null&&(T==="item/started"||T==="item/agentMessage/delta"||T==="item/completed")&&Wi(w,C.agentState,C.onDelta,void 0),T==="turn/completed"&&C!==null&&!C.settled){Mu(C.agentState);let D=Fu(w,C.turnState);C.settled=!0,C.usage.finish(),_=null,D.shouldReject?C.reject(Object.assign(D.turnError,{usage:C.usage.usage(),sessionId:a})):(o.completedTurns+=1,C.resolve({text:C.agentState.resultText,usage:C.usage.usage(),sessionId:a,turnId:C.turnId,durationMs:Date.now()-C.startMs}))}T==="error"&&C!==null&&Du(w,C.turnState),C?.onEvent?.(w)});let N=A=>{c=new Ne(`Failed to spawn codex app-server: ${A.message}`,{cause:A}),X({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:A.message});for(let w of m.values())w.reject(c);m.clear(),R(c)};s.on("error",N),s.stdin?.on("error",N),s.on("exit",(A,w)=>{o.exited=!0,x?.(),o.exitCode=A,o.signal=w;let T=b();for(let I of m.values())I.reject(T);m.clear();let k=_;if(k!==null&&!k.settled)if(k.settled=!0,k.usage.finish(),_=null,k.turnState.pendingCodexError)k.reject(Object.assign(k.turnState.pendingCodexError,{usage:k.usage.usage(),sessionId:a}));else{let I=u.trim()?Me(u,{provider:"codex"}):"";X({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:A,signal:w,...I?{stderr_summary:I}:{}}),k.reject(Object.assign(new De(I?`${T.message}
|
|
2309
2310
|
${I}`:T.message,A,w,u),{usage:k.usage.usage(),sessionId:a}))}for(let I of g.splice(0))I()}),s.on("close",(A,w)=>{if(!o.exited){o.exited=!0,o.exitCode=A,o.signal=w;for(let T of g.splice(0))T()}});try{if(await f("initialize",Dk()),h("initialized",{}),t.threadId){let A;try{A=await f("thread/resume",{threadId:t.threadId,sandbox:r,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(T){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${T instanceof Error?T.message:String(T)} (the thread/start fallback is disabled in bundle mode)`)}let w=A.result?.thread;if(w?.id!==t.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${t.threadId}", received "${w?.id??"unknown"}"`);a=t.threadId,t.onSessionId?.(a)}else{let w=(await f("thread/start",{cwd:t.cwd,approvalPolicy:"never",sandbox:r,...t.model?{model:t.model}:{}})).result?.thread;w?.id&&(a=w.id,t.onSessionId?.(a))}}catch(A){let w=c??(A instanceof Error?A:new Error(String(A)));if(t.serviceHosted&&t.closeTimeoutMs===void 0)s.stdin?.end(),await y();else{let T=t.closeTimeoutMs??2e3;await be(s,{softDelayMs:Math.min(1e3,T),killDelayMs:Math.min(1e3,T)}).catch(()=>{})}throw w}let O=A=>new Promise(w=>{setTimeout(w,A).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(A,w={}){if(E&&await E,o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw b();if(_!==null)throw new Error("codex bundle session has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending");if(w.signal?.aborted)throw new Error("Aborted");return new Promise((T,k)=>{let I={usage:l.turn(a),onUsage:w.onUsage,agentState:Lu(),turnState:Pu(),resolve:T,reject:k,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};_=I;let C=()=>{I.settled||(I.settled=!0,_=null,v=I,E=new Promise(M=>{x=M}),S(I),w.signal?.removeEventListener("abort",C),I.usage.finish(),k(Object.assign(new Error("Aborted"),{usage:I.usage.usage(),sessionId:a})))};w.signal?.addEventListener("abort",C,{once:!0}),f("turn/start",{threadId:a,input:[{type:"text",text:A}],...t.model?{model:t.model}:{}}).then(M=>{I.usage.bind(M.result?.turn?.id)}).catch(M=>{if(I.settled){v===I&&(v=null,x?.());return}I.settled=!0,_=null,w.signal?.removeEventListener("abort",C),I.usage.finish(),k(Object.assign(o.exited?b():M instanceof Error?M:new Error(String(M)),{usage:I.usage.usage(),sessionId:a}))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,x?.(),!o.exited&&(t.holdOpen!==void 0?await new Promise(A=>{In(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>_!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),A()},label:"codex"})}):s.stdin?.end(),!o.exited)){let A=t.closeTimeoutMs;if(A===void 0&&t.serviceHosted)await y();else{let w=A??2e3;await Promise.race([y(),O(w)]),o.exited||await be(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,w),killDelayMs:Math.min(1e3,w)}).catch(()=>{})}}})()),o.closing}}}var S1,Bk=L(()=>{"use strict";Ag();Re();Re();qr();Us();wa();An();$g();Re();mn();dn();Ug();Ug();S1=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(E1(T1(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});function Fe(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length>e?n.slice(0,e-1)+"\u2026":n}function Hk(t,e){return n=>{if(n.kind==="tool_use"&&typeof n.id=="string"){if(t.size>=R1){let r=t.keys().next().value;r!==void 0&&t.delete(r)}t.set(n.id,Date.now()),e(n);return}if(n.kind==="tool_result"&&typeof n.id=="string"&&n.elapsedMs===void 0){let r=t.get(n.id);if(r!==void 0){e({...n,elapsedMs:Date.now()-r}),t.delete(n.id);return}}e(n)}}function Wk(){let t=new Map;return(e,n)=>{x1(e,Hk(t,n))}}function x1(t,e){let n=t.type;if(n==="system"){let r=t.subtype;if(r==="api_retry"){let s=typeof t.attempt=="number"?t.attempt:void 0,i=typeof t.max_retries=="number"?t.max_retries:void 0,o=typeof t.error_status=="number"?t.error_status:void 0,a=typeof t.error=="string"?t.error:void 0,l=typeof t.retry_delay_ms=="number"?t.retry_delay_ms:void 0,c=[];s!==void 0&&c.push(i!==void 0?`attempt ${s}/${i}`:`attempt ${s}`),o!==void 0&&c.push(`HTTP ${o}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(Fe(a,60));let u=c.length>0?c.join(", "):r;e({kind:"api_retry",summary:u});return}if(r==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(Fe(i,80)),e({kind:"other",summary:o.join(": "),raw:t});return}e({kind:"system",summary:r||"system",raw:t});return}if(n==="assistant"||n==="user"){let s=t.message?.content;if(!Array.isArray(s))return;for(let i of s){let o=i.type;if(o==="text"){let a=i.text||"";a&&e({kind:"text",summary:Fe(a),raw:i})}else if(o==="tool_use"){let a=i.name||"tool",l=typeof i.id=="string"?i.id:void 0,c=i.input,u="";c&&(typeof c.command=="string"?u=c.command:typeof c.file_path=="string"?u=c.file_path:typeof c.path=="string"?u=c.path:typeof c.pattern=="string"?u=c.pattern:typeof c.url=="string"?u=c.url:u=Fe(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:Fe(u),id:l,raw:i})}else if(o==="thinking"||o==="redacted_thinking"){let a=i.thinking||i.data||"";e({kind:"thinking",summary:Fe(a),raw:i})}else if(o==="tool_result"){let l=i.is_error===!0?"error":"ok",c=typeof i.tool_use_id=="string"?i.tool_use_id:void 0,u,d=i.content;if(typeof d=="string")u=`${d.split(`
|
|
2310
2311
|
`).length} lines, ${d.length} chars`;else if(Array.isArray(d)){let m=d.map(p=>typeof p=="object"&&p&&"text"in p?p.text:"").filter(Boolean).join("");m&&(u=`${m.split(`
|
|
2311
2312
|
`).length} lines, ${m.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(n==="result"){e({kind:"system",summary:"result",raw:t});return}}async function $u(t,e){let n=e.binary==="qwen"?"qwen":"claude",r=e.onProgress?Wk():void 0;if(e.bundleSession!==void 0)return cr(e.bundleSession,n,e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let s=await Ck(t,{sessionId:e.sessionId,cwd:e.cwd,env:e.env,tool:n,binaryPath:e.progPath,model:e.model,permissionMode:e.permissionMode,onText:e.onDelta,onUsage:e.onUsage,onEvent:i=>{typeof i.session_id=="string"&&i.session_id&&e.onSessionId?.(i.session_id),r&&r(i,e.onProgress)},signal:e.signal,holdOpen:e.holdOpen});return{text:s.result,...s.usage?{usage:s.usage}:{},sessionId:s.sessionId,durationMs:s.durationMs,numTurns:s.numTurns,...s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{}}}async function ju(t){let e=t.binary==="qwen"?"qwen":"claude",n=await Nk({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs,serviceHosted:t.serviceHosted,sessionFileRoots:t.sessionFileRoots});return{provider:e,get sessionId(){return n.sessionId},get completedTurns(){return n.completedTurns},async sendTurn(r,s={}){let i=Wk(),o=await n.sendTurn(r,{onText:s.onDelta,onEvent:a=>{s.onEvent?.(a),s.onProgress&&i(a,s.onProgress)},signal:s.signal});return{text:o.result,...o.usage?{usage:o.usage}:{},sessionId:o.sessionId,durationMs:o.durationMs,...o.warnings!==void 0?{warnings:o.warnings}:{}}},close:()=>n.close()}}function qk(){let t=new Map;return(e,n)=>{I1(e,Hk(t,n))}}function I1(t,e){if(t.method!=="session/update")return;let s=t.params?.update;if(!s)return;let i=s.sessionUpdate;if(i){if(i==="agent_message_chunk"){let a=s.content?.text||"";a&&e({kind:"text",summary:Fe(a)});return}if(i==="agent_thought_chunk"||i==="thought"||i==="reasoning"){let a=s.content?.text||"";e({kind:"thinking",summary:Fe(a)});return}if(i==="tool_call"){let o=s.title||s.kind||"tool",a=typeof s.toolCallId=="string"?s.toolCallId:void 0,l="",c=s.rawInput;c&&(typeof c.command=="string"?l=c.command:typeof c.file_path=="string"?l=c.file_path:typeof c.path=="string"?l=c.path:l=Fe(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:Fe(l),id:a});return}if(i==="tool_call_update"){let o=s.status||"",a=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(o==="completed"||o==="failed")e({kind:"tool_result",summary:o,status:o==="failed"?"error":"ok",id:a});else if(o==="in_progress"){let l=s.content,c=typeof l=="string"?l:typeof l?.text=="string"?l.text:"",u=c?`running\u2026 ${Fe(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:i})}}function Xk(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function pn(t,e){let n=e.acpTool||e.binary,r=e.onProgress?qk():void 0;if(e.bundleSession!==void 0)return cr(e.bundleSession,n,e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let s=[];if(e.model&&n==="copilot"){let a="copilot --acp does not implement per-session model selection";wt({event:"model_ignored",provider:n,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await ok(t,{tool:n,sessionId:e.sessionId,onSessionId:e.onSessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,effort:e.effort,alias:e.alias,permissionMode:e.permissionMode,acpMode:e.acpMode,requireResume:e.requireResume,onDelta:e.onDelta,onEvent:r?a=>r(a,e.onProgress):void 0,signal:e.signal,holdOpen:e.holdOpen}),o=[...s,...i.warnings??[]];return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,...Xk(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function Cn(t){let e=t.acpTool||t.binary,n=await ak({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,effort:t.effort,alias:t.alias,permissionMode:t.permissionMode,acpMode:t.acpMode,requireResume:!0,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs,serviceHosted:t.serviceHosted});return{provider:e,get sessionId(){return n.sessionId},get completedTurns(){return n.completedTurns},async sendTurn(r,s={}){let i=qk(),o=await n.sendTurn(r,{...s,onEvent:a=>{s.onEvent?.(a),s.onProgress&&i(a,s.onProgress)}});return{text:o.result,sessionId:o.sessionId,durationMs:o.durationMs,stopReason:o.stopReason,sawActivity:o.sawActivity,...Xk(o.result,o.sawActivity)?{status:"empty"}:{},...o.warnings!==void 0?{warnings:o.warnings}:{}}},close:()=>n.close()}}function Gk(t,e){let n=t.method;if(!n)return;let r=t.params;if(n==="turn/started"){e({kind:"system",summary:"turn started"});return}if(n==="turn/completed"){e({kind:"system",summary:"turn completed"});return}if(n==="error"){let s=r?.error,i=typeof s?.message=="string"?s.message:void 0,o=i&&i.length>0?i:"(no message)",a=r?.willRetry===!0;e(a?{kind:"api_retry",summary:`codex retry: ${Fe(o,120)}`}:{kind:"other",summary:`codex error: ${Fe(o,120)}`});return}if(n==="item/started"||n==="item/completed"){let s=r?.item;if(!s)return;let i=s.type,o=n==="item/started";switch(i){case"commandExecution":{let a=typeof s.id=="string"?s.id:void 0,l=s.command,c=Array.isArray(l)?l.join(" "):typeof l=="string"?l:"";if(o)e({kind:"tool_use",tool:"Bash",summary:Fe(c||"(command)"),id:a});else{let u=s.exitCode,d=s.status||"",m=typeof s.durationMs=="number"?s.durationMs:void 0,p=typeof u=="number"?`exit ${u}`:d||"done",f=[];typeof u=="number"?f.push(`exit ${u}`):d&&f.push(d),typeof m=="number"&&f.push(`${Math.round(m/1e3)}s`),e({kind:"tool_result",summary:f.join(", ")||"done",status:p,elapsedMs:m,id:a})}return}case"fileChange":{let a=typeof s.id=="string"?s.id:void 0;if(o){let l=s.changes,c=Array.isArray(l)?l.map(u=>u.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:Fe(c||"(edit)"),id:a})}else{let l=s.status||"done";e({kind:"tool_result",summary:l,status:l,id:a})}return}case"mcpToolCall":{let a=typeof s.id=="string"?s.id:void 0,l=s.server||"mcp",c=s.tool||"tool";if(o)e({kind:"tool_use",tool:`${l}/${c}`,summary:"",id:a});else{let u=s.status||"done";e({kind:"tool_result",summary:u,status:u,id:a})}return}case"webSearch":{let a=typeof s.id=="string"?s.id:void 0;e(o?{kind:"tool_use",tool:"WebSearch",summary:Fe(s.query||""),id:a}:{kind:"tool_result",summary:"done",status:"done",id:a});return}case"reasoning":{o&&e({kind:"thinking",summary:""});return}case"agentMessage":case"userMessage":return;default:{i&&e({kind:o?"tool_use":"tool_result",tool:i,summary:""});return}}}if(n==="item/agentMessage/delta"){let s=r?.delta||"";if(s){let i=typeof r?._lmctlItemPhase=="string"?r._lmctlItemPhase:void 0;e(i==="commentary"?{kind:"thinking",summary:Fe(s)}:{kind:"text",summary:Fe(s)})}return}if(n.startsWith("item/reasoning/")||n==="item/reasoning/summaryTextDelta"||n==="item/reasoning/textDelta"){let s=(typeof r?.delta=="string"?r.delta:"")||"";e({kind:"thinking",summary:Fe(s)});return}if(n==="item/commandExecution/outputDelta"){let s=(typeof r?.delta=="string"?r.delta:"")||"";if(s){let i=s.split(`
|
|
@@ -2315,7 +2316,7 @@ ${I}`:T.message,A,w,u),{usage:k.usage.usage(),sessionId:a}))}for(let I of g.spli
|
|
|
2315
2316
|
`);try{return JSON.stringify(t)}catch{return String(t)}}function W1(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function q1(t,e){if(e===void 0)return;let n={input:e};if(t!=="apply_patch"||typeof e!="string")return n;let r=[...e.matchAll(/^\*\*\* (?:(Add|Update|Delete) File|(Move) to): (.+)\r?$/gm)].map(s=>({kind:s[1]??s[2],path:s[3]?.trim()})).filter(s=>!!(s.kind&&s.path));return r.length>0&&(n.path=r[0].path,n.paths=r.map(s=>s.path),n.kinds=r.map(s=>s.kind)),n}async function nR(t){let e=0,n=0,r=0,s=0,i=0,o,a,l=new Set,c,u;for await(let d of Ce(t)){if(d.type==="event_msg"&&d.payload?.type==="user_message"){let m=d.payload.message||d.payload.text;m&&(u=Q(m.trim(),80))}if(d.type==="response_item"&&d.payload){let m=d.payload;if(m.type==="message"&&m.role==="user"&&m.content){let p=m.internal_chat_message_metadata_passthrough?.content_item_kinds;for(let f=0;f<m.content.length;f++){let h=m.content[f];Gg(p,f)||h.type==="input_text"&&typeof h.text=="string"&&h.text&&(e++,u=Q(h.text.trim(),80))}}else if(m.type==="message"&&m.role==="assistant"&&m.content)for(let p of m.content)p.type==="output_text"&&typeof p.text=="string"&&p.text&&e++}if(d.payload&&typeof d.payload.model_context_window=="number"&&(c=d.payload.model_context_window),d.type==="event_msg"&&d.payload?.type==="token_count"&&d.payload.info?.total_token_usage){let m=d.payload.info.total_token_usage;n=m.input_tokens??n,r=m.cached_input_tokens??m.cache_read_input_tokens??r,s=m.output_tokens??s,i=m.reasoning_output_tokens??i;let p=d.payload.info.last_token_usage;if(p&&typeof p.input_tokens=="number"&&typeof p.output_tokens=="number"){let h=JSON.stringify([d.timestamp??null,d.ordinal??null,m,p]);if(!l.has(h)){l.add(h);let g=[p.input_tokens,p.cached_input_tokens??p.cache_read_input_tokens??0,p.output_tokens,p.reasoning_output_tokens??0];a??=[0,0,0,0],g.forEach((y,b)=>{a[b]+=y})}}let f=H1(d.payload.info.last_token_usage);f&&(o=f),typeof d.payload.info.model_context_window=="number"&&(c=d.payload.info.model_context_window)}}return a&&([n,r,s,i]=a),{messageCount:e,totalInputTokens:n,totalCachedInputTokens:r,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:c,lastUserMessage:u}}var U1,Hu,rR=L(()=>{"use strict";Xe();U1=new Set(["agents_md.instructions","environments.environment_context","plugins.recommendations","plugins.usage_instructions","apps.instructions","collaboration_mode.instructions","generic.developer_instructions","host_skills.instructions","model_switch.instructions","multi_agent.mode_instructions","multi_agent.role_instructions","multi_agent.usage_hint","permissions.instructions","skills.instructions"]);Hu=class{name="codex";codexDirs;constructor(e={}){let n=[Oa(ae,".codex"),Oa(ae,".code")];if(e.codexDirs&&e.codexDirs.length>0){this.codexDirs=[...new Set(e.codexDirs)];return}let r=[e.codexDir||n[0],e.codeDir||n[1]];this.codexDirs=[...new Set(r)]}getWatchPaths(){return this.codexDirs.map(e=>({directory:Oa(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let n of this.codexDirs){let r=Oa(n,"sessions");try{await eR(r),e.push(r)}catch{}}return e}async discoverSessions(){let e=[],n=await this.getSessionsDirs();for(let r of n){let s=await this.findSessionFiles(r);for(let i of s)try{let o=await this.extractSummary(i);o&&e.push(o)}catch{}}return e}async findSessionFiles(e){let n=[],r;try{r=await F1(e)}catch{return n}for(let s of r){let i=Oa(e,s),o=await eR(i).catch(()=>null);if(o)if(o.isDirectory()){let a=await this.findSessionFiles(i);n.push(...a)}else s.endsWith(".jsonl")&&n.push(i)}return n}extractSessionIdFromFilename(e){let n=j1(e,".jsonl"),r=n.match(/rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(.+)$/);return r?r[1]:n}async extractSummary(e){let n=await Ht(e,30),r=await je(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,u,d,m;for(let f of n){if(f.type==="session_meta"&&f.payload&&(f.payload.id&&(s=f.payload.id),f.payload.cwd&&(i=f.payload.cwd),f.payload.cli_version&&(o=f.payload.cli_version),f.payload.timestamp&&(l=new Date(f.payload.timestamp)),f.payload.originator&&(d=f.payload.originator),f.payload.source&&(m=f.payload.source)),f.type==="turn_context"&&f.payload&&(f.payload.model&&(a=f.payload.model),!i&&f.payload.cwd&&(i=f.payload.cwd)),f.type==="event_msg"&&f.payload?.type==="user_message"){let h=f.payload.message||f.payload.text;h&&(c||(c=Q(h.trim(),80)),u=Q(h.trim(),80))}if(f.type==="response_item"&&f.payload?.type==="message"&&f.payload.role==="user"&&f.payload.content){let h=f.payload.internal_chat_message_metadata_passthrough?.content_item_kinds;for(let g=0;g<f.payload.content.length;g++){let y=f.payload.content[g];Gg(h,g)||y.type==="input_text"&&typeof y.text=="string"&&y.text&&(c||(c=Q(y.text.trim(),80)),u=Q(y.text.trim(),80))}}}if(!i)return null;let p=await nR(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||r.createdAt,modifiedAt:r.modifiedAt,model:a,cliVersion:o,startCommand:tR(d,m),firstUserMessage:c,lastUserMessage:p.lastUserMessage??u,messageCount:p.messageCount,filePath:e,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCachedInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,totalReasoningOutputTokens:p.totalReasoningOutputTokens||void 0,lastInputTokens:p.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:p.lastTokenUsage,modelContextWindow:p.modelContextWindow}}async loadSession(e){let n=await this.resolveSessionFile(e);if(!n)return null;let r=await je(n),s=[],i="",o,a,l,c,u,d=e,m,p,f=new Set,h=[],g=new Set,y=[],b=(E,x)=>{let S=y.find(R=>!R.mirrored&&R.source!==x&&R.text===E);S?S.mirrored=!0:y.push({text:E,source:x,mirrored:!1})},_=()=>{h.push(...y.map(E=>E.text)),y=[]};for await(let E of Ce(n)){let x=E.timestamp?new Date(E.timestamp):new Date;if(E.type==="session_meta"&&E.payload){E.payload.id&&(d=E.payload.id),E.payload.cwd&&(i=E.payload.cwd),E.payload.cli_version&&(o=E.payload.cli_version),E.payload.timestamp&&(l=new Date(E.payload.timestamp)),m=tR(E.payload.originator,E.payload.source);continue}if(E.type==="turn_context"&&E.payload){E.payload.model&&(a=E.payload.model),!i&&E.payload.cwd&&(i=E.payload.cwd);continue}if(E.type==="response_item"&&E.payload){let S=E.payload;if(S.type==="message"){if(S.role==="user"&&S.content){let R=S.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(R)){let N=S.content.filter((O,A)=>R[A]==="user.text"&&typeof O.text=="string").map(O=>O.text).join(`
|
|
2316
2317
|
`);R.includes("user.text")&&N&&(!S.id||!g.has(S.id))&&(b(N,"metadata"),S.id&&g.add(S.id))}for(let N=0;N<S.content.length;N++){let O=S.content[N];if(!Gg(R,N)&&O.type==="input_text"&&typeof O.text=="string"&&O.text){let A=O.text.trim();c||(c=Q(A,80)),u=Q(A,80),La(s,f,{role:"user",timestamp:x,content:ke(A)})}}continue}if(S.role==="assistant"&&S.content){for(let R of S.content)R.type==="output_text"&&typeof R.text=="string"&&R.text&&La(s,f,{role:"assistant",timestamp:x,content:ke(R.text),model:a});continue}if(S.role!=="user"&&S.role!=="assistant"&&S.content){for(let R of S.content)(R.type==="input_text"||R.type==="output_text")&&typeof R.text=="string"&&R.text&&La(s,f,{role:"system",timestamp:x,content:ke(R.text.trim())});continue}}if(S.type==="function_call"){s.push({role:"tool_use",timestamp:x,content:S.name||"unknown tool",toolName:S.name,toolInput:S.arguments!==void 0?ke(Xi(S.arguments)):void 0,toolInputData:W1(S.arguments),toolCallId:S.call_id});continue}if(S.type==="function_call_output"){s.push({role:"tool_result",timestamp:x,content:ke(Xi(S.output)),toolCallId:S.call_id});continue}if(S.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:x,content:S.name||"unknown tool",toolName:S.name,toolInput:S.input!==void 0?ke(Xi(S.input)):void 0,toolInputData:q1(S.name,S.input),toolCallId:S.call_id});continue}if(S.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:x,content:ke(Xi(S.output)),toolCallId:S.call_id});continue}if(S.type==="reasoning"&&S.summary){let R=S.summary.map(N=>Xi(N.text)).join(`
|
|
2317
2318
|
`);R.trim()&&La(s,f,{role:"thinking",timestamp:x,content:ke(R)});continue}}if(E.type==="event_msg"&&E.payload&&(E.payload.type==="task_started"?(_(),p="in_progress"):E.payload.type==="task_complete"?p="complete":E.payload.type==="turn_aborted"&&(p="aborted"),E.payload.type==="user_message"&&typeof E.payload.message=="string"&&b(E.payload.message,"event"),E.payload.type==="agent_reasoning")){let S=E.payload.message||E.payload.text;S&&La(s,f,{role:"thinking",timestamp:x,content:ke(S)})}}if(!i)return null;_();let v=await nR(n);return{provider:"codex",sessionId:d,cwd:i,createdAt:l||r.createdAt,modifiedAt:r.modifiedAt,model:a,cliVersion:o,startCommand:m,turnStatus:p,firstUserMessage:c,lastUserMessage:u,messageCount:v.messageCount,filePath:n,totalInputTokens:v.totalInputTokens||void 0,totalCachedInputTokens:v.totalCachedInputTokens||void 0,totalOutputTokens:v.totalOutputTokens||void 0,totalReasoningOutputTokens:v.totalReasoningOutputTokens||void 0,lastInputTokens:v.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:v.lastTokenUsage,modelContextWindow:v.modelContextWindow,messages:s,userPrompts:h}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await $1(n),!0):!1}async resolveSessionFile(e){let n=await this.getSessionsDirs(),r=[];for(let i of n){let o=await this.findSessionFiles(i);r.push(...o)}for(let i of r)if(this.extractSessionIdFromFilename(i)===e)return i;let s=[];for(let i of r)this.extractSessionIdFromFilename(i).startsWith(e)&&s.push(i);if(s.length===1)return s[0];for(let i of r){let o=await Ht(i,1);if(o.length>0&&o[0].type==="session_meta"){let a=o[0].payload?.id;if(a===e||a&&a.startsWith(e))return i}}return null}}});import{execFile as X1}from"node:child_process";import{realpathSync as sR,readdirSync as G1}from"node:fs";import{homedir as J1}from"node:os";import{join as Wu,resolve as iR,sep as V1}from"node:path";function Kg(t){return new Vg(t)}var Jg,Vg,zg=L(()=>{"use strict";rR();dt();dr();nt();Jg="gpt-5.6-sol",Vg=class extends we{nativeLaunchFailureHint="If the message mentions a shared background server or feature mismatch, it could be a CLI/daemon version mismatch: compare codex --version with codex app-server daemon version (cliVersion vs appServerVersion) and search the web for the error text.";constructor(e){super({provider:new Hu(e),protocol:{transport:"codex-app-server",perTurnCancellation:"process",persistentCancellation:"turn",persistentResume:!0},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append"},binary:"codex",seedArgs:["exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","-"],seedStdin:`${ue}
|
|
2318
|
-
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Jk})}async preflightNativeLaunch(e){let n=performance.now()+1800,r=(N,O)=>new Promise(A=>{let w=Math.ceil(n-performance.now());if(w<=0){A(void 0);return}let T,k=()=>{try{T?.kill("SIGKILL")}catch{}},I=()=>{k()},C=()=>{k()},M=()=>{k()};process.once("exit",I),process.once("SIGINT",C),process.once("SIGTERM",M);let D=()=>{process.removeListener("exit",I),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",M)};T=X1(N,O,{cwd:e.cwd,env:e.env,signal:e.signal,timeout:w,killSignal:"SIGKILL",maxBuffer:65536},(j
|
|
2319
|
+
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Jk})}async preflightNativeLaunch(e){let n=performance.now()+1800,r=(N,O)=>new Promise(A=>{let w=Math.ceil(n-performance.now());if(w<=0){A(void 0);return}let T,k=()=>{try{T?.kill("SIGKILL")}catch{}},I=()=>{k()},C=()=>{k()},M=()=>{k()};process.once("exit",I),process.once("SIGINT",C),process.once("SIGTERM",M);let D=()=>{process.removeListener("exit",I),process.removeListener("SIGINT",C),process.removeListener("SIGTERM",M)};T=X1(N,O,{cwd:e.cwd,env:e.env,signal:e.signal,timeout:w,killSignal:"SIGKILL",maxBuffer:65536},(j,$)=>{D(),A(j?void 0:$)})}),s=await r(e.binary,["app-server","daemon","version"]);if(s===void 0)return{kind:"ok"};let i;try{i=JSON.parse(s)}catch{let N=s.match(/\{[\s\S]*\}/);if(N)try{i=JSON.parse(N[0])}catch{return{kind:"ok"}}else return{kind:"ok"}}let o=N=>typeof N=="string"&&/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/.test(N)&&N.length<=100,a=typeof i?.cliVersion=="string"?i.cliVersion:typeof i?.cli_version=="string"?i.cli_version:"",l=typeof i?.appServerVersion=="string"?i.appServerVersion:typeof i?.app_server_version=="string"?i.app_server_version:"",c=a.trim(),u=l.trim(),d=typeof i?.status=="string"?i.status.toLowerCase():"";if(!(d==="running"||d==="alreadyrunning")||!o(c)||!o(u))return{kind:"ok"};if(c===u)return{kind:"ok"};let p="codex CLI "+c+" differs from the running codex daemon "+u,f="To align your CLI: npm i -g @openai/codex@"+u,h=p+"; using the daemon's binary. "+f,g={kind:"ok",message:p+"; no matching daemon binary is available, launching the PATH CLI. "+f},y=iR(e.cwd,e.env.CODEX_HOME||Wu(e.env.HOME||J1(),".codex")),b=[],_=[],v=process.platform==="win32"?"codex.exe":"codex",E=i.managedCodexPath??i.managed_codex_path;typeof E=="string"&&E.trim().length>0&&b.push(E.trim());let x=N=>N.replace(/\+.*$/,""),S=x(u),R=process.arch==="arm64"?"aarch64":"x86_64";for(let N of["app-server-daemon","standalone"]){let O=Wu(y,"packages",N,"releases");try{_.push(sR(O)+V1);let A=G1(O).filter(w=>process.arch==="x64"&&(w.includes("aarch64")||w.includes("arm64"))||process.arch==="arm64"&&(w.includes("x86_64")||w.includes("x64")||w.includes("i686"))?!1:w===u||w===S||w.startsWith(u+"-")||w.startsWith(S+"-"));A.sort((w,T)=>{let k=w.includes(R)?0:1,I=T.includes(R)?0:1;return k!==I?k-I:w.localeCompare(T)});for(let w of A)b.push(Wu(O,w,"bin",v)),b.push(Wu(O,w,v))}catch{}}for(let N of new Set(b)){if(performance.now()>=n||e.signal?.aborted)break;let O;try{if(O=sR(iR(e.cwd,N)),!_.some(T=>O.startsWith(T)))continue}catch{continue}let w=(await r(O,["--version"]))?.trim().match(/^codex(?:-cli)?\s+([0-9A-Za-z.+-]+)/)?.[1];if(w&&(w===u||x(w)===S))return{kind:"use-binary",binary:O,message:h}}return g}openSession(e){return Vk({...e,model:e.model??Jg})}seedArgsFor(e){let n=super.seedArgsFor(e),r=e?.model??Jg;return[...n.slice(0,-1),"--model",r,n[n.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Jg}}}});import{createHash as K1}from"node:crypto";import{readdir as Ma,readFile as oR,stat as qu,unlink as z1}from"node:fs/promises";import{join as Gt,basename as Y1,dirname as Q1}from"node:path";import{cwd as Z1}from"node:process";function Yg(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function aR(t){return t==="user"}function Qg(t){return t==="gemini"||t==="assistant"}function Ws(t,e=new Date(0)){if(!t)return e;let n=new Date(t);return Number.isNaN(n.getTime())?e:n}function eB(t){return`${t.sessionId}\0${t.cwd}`}function tB(t,e){let n=t.filePaths??[t.filePath],r=e.filePaths??[e.filePath],s=[...new Set([...n,...r])],i=e.modifiedAt.getTime()>=t.modifiedAt.getTime()?e:t;return{...i,createdAt:t.createdAt.getTime()<=e.createdAt.getTime()?t.createdAt:e.createdAt,modifiedAt:i.modifiedAt,filePath:i.filePath,filePaths:s}}function Xu(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function lR(t){let e=0,n=0,r=0,s=0,i=0,o;for(let a of t){if(!Qg(a.type)||!a.tokens)continue;let l=Xu(a.tokens.input),c=Xu(a.tokens.cached),u=Math.max(l-c,0),d=Xu(a.tokens.output),m=Xu(a.tokens.thoughts);e+=l,n+=c,r+=d,s+=m,i=l,o={inputTokens:u,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:d,reasoningOutputTokens:m,totalTokens:l+d+m}}return{totalInputTokens:e,totalCachedInputTokens:n,totalOutputTokens:r,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function nB(t){return K1("sha256").update(t).digest("hex")}function Pa(t,e){let n=e;for(;n&&!t.has(n);){t.add(n);let r=Q1(n);if(r===n)break;n=r}}var Gu,cR=L(()=>{"use strict";Xe();hc();Re();Gu=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let n=e.geminiDir||Gt(ae,".gemini");this.geminiProjectsFile=Gt(n,"projects.json"),this.geminiTmpDir=Gt(n,"tmp");let r=e.claudeDir||Gt(ae,".claude");this.claudeProjectsDir=Gt(r,"projects");let s=[Gt(ae,".codex"),Gt(ae,".code")],i=e.codexDirs&&e.codexDirs.length>0?e.codexDirs:[e.codexDir||s[0],e.codeDir||s[1]];this.codexSessionDirs=[...new Set(i)].map(o=>Gt(o,"sessions")),this.extraWorkspacePaths=e.extraWorkspacePaths||[]}getWatchPaths(){return[{directory:this.geminiTmpDir,filePattern:/\.jsonl?$/}]}async discoverSessions(){let e=await this.findSessionFiles(),n=new Map;for(let r of e)try{let s=await this.extractSummary(r);if(!s)continue;let i=eB(s),o=n.get(i);n.set(i,o?tB(o,s):s)}catch{}return[...n.values()]}async loadSession(e){let n=await this.resolveSessionFile(e);if(!n)return null;let r;try{r=await this.readSessionFile(n)}catch{return null}if(!r)return null;let s=await je(n),i=[],o=[],a=r.messages||[],l=r.sessionId||this.extractSessionIdFromFilename(n),c=r.projectHash||"",u=await this.resolveWorkspace(c),d,m,p;for(let y of a){let b=Ws(y.timestamp),_=y.type,v=ke(Yg(y.content));if(aR(_)){let x=Yg(y.content);x&&o.push(x);let S=v.trim();S&&(d||(d=Q(S,80)),m=Q(S,80)),i.push({role:"user",timestamp:b,content:S||v});continue}if(Qg(_)){y.model&&(p=y.model);for(let x of y.thoughts||[]){let S=[x.subject,x.description].filter(Boolean).join(`
|
|
2319
2320
|
`).trim();S&&i.push({role:"thinking",timestamp:Ws(x.timestamp,b),content:ke(S)})}i.push({role:"assistant",timestamp:b,content:v,model:y.model});continue}let E=_?`[${_}] `:"";i.push({role:"system",timestamp:b,content:`${E}${v}`.trim()})}let f=Ws(r.startTime,s.createdAt),h=Ws(r.lastUpdated,s.modifiedAt),g=lR(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:f,modifiedAt:h,model:p,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(y=>y.role==="user"||y.role==="assistant").length,filePath:n,totalInputTokens:g.totalInputTokens||void 0,totalCachedInputTokens:g.totalCachedInputTokens||void 0,totalOutputTokens:g.totalOutputTokens||void 0,totalReasoningOutputTokens:g.totalReasoningOutputTokens||void 0,lastInputTokens:g.lastInputTokens||void 0,lastTokenUsage:g.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let n=await this.readSessionFile(e);if(!n)return null;let r=await je(e),s=n.messages||[],i=n.sessionId||this.extractSessionIdFromFilename(e),o=n.projectHash||"",a=await this.resolveWorkspace(o),l,c,u,d=0;for(let p of s)if(aR(p.type)){d++;let f=Yg(p.content).trim();f&&(l||(l=Q(ke(f),80)),c=Q(ke(f),80))}else Qg(p.type)&&(d++,p.model&&(u=p.model));let m=lR(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Ws(n.startTime,r.createdAt),modifiedAt:Ws(n.lastUpdated,r.modifiedAt),model:u,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async readSessionFile(e){let n=await oR(e,"utf-8");if(Yo(n)==="unknown")return X({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:n.slice(0,120),message:`gemini session file at ${e} matches neither old (.json with messages[]) nor new (.jsonl with kind metadata) format. Skipping; lmctl ls / audit / stats will not see this session.`}),null;try{return ks(n)}catch{return null}}extractSessionIdFromFilename(e){let n=Y1(e).replace(/\.jsonl?$/,""),r=n.match(/session-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-(.+)$/);return r?r[1]:n}async findSessionFiles(){let e=[],n;try{n=await Ma(this.geminiTmpDir)}catch{return e}for(let r of n){let s=Gt(this.geminiTmpDir,r,"chats");if(!(await qu(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Ma(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(Gt(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await z1(n),!0):!1}async resolveSessionFile(e){let n=await this.findSessionFiles(),r=[];for(let s of n){let i=await this.readSessionFile(s).catch(()=>null),o=this.extractSessionIdFromFilename(s),a=i?.sessionId||o,l=a===e||a.startsWith(e),c=o===e||o.startsWith(e)||o.length>=8&&e.startsWith(o);if(!l&&!c)continue;let u=await je(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));r.push({filePath:s,modifiedAt:Ws(i?.lastUpdated,u.modifiedAt)})}return r.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),r[0]?.filePath??null}async resolveWorkspace(e){return e?(await this.getWorkspaceHashMap()).get(e)||`[hash:${e.slice(0,16)}]`:"(unknown workspace)"}async getWorkspaceHashMap(){if(this.workspaceHashMap)return this.workspaceHashMap;let e=new Set;Pa(e,Z1());for(let r of this.extraWorkspacePaths)Pa(e,r);for(let r of await this.collectGeminiProjectPaths())Pa(e,r);for(let r of await this.collectCodexCwds())Pa(e,r);for(let r of await this.collectClaudeCwds())Pa(e,r);let n=new Map;for(let r of e)n.set(nB(r),r);return this.workspaceHashMap=n,n}async collectGeminiProjectPaths(){let e;try{e=await oR(this.geminiProjectsFile,"utf-8")}catch{return[]}try{let r=JSON.parse(e).projects;return!r||typeof r!="object"||Array.isArray(r)?[]:Object.keys(r)}catch{return[]}}async collectCodexCwds(){let e=new Set;for(let n of this.codexSessionDirs){let r=await this.findJsonlFiles(n);for(let s of r){let o=(await Ht(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,n;try{n=await Ma(this.claudeProjectsDir)}catch{return[]}for(let r of n){let s=Gt(this.claudeProjectsDir,r);if(!(await qu(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Ma(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Gt(s,a),u=(await Ht(l,1).catch(()=>[]))[0]?.cwd;u&&e.add(u)}}return[...e]}async findJsonlFiles(e){let n=[];if(!(await qu(e).catch(()=>null))?.isDirectory())return n;let s;try{s=await Ma(e)}catch{return n}for(let i of s){let o=Gt(e,i),a=await qu(o).catch(()=>null);if(a)if(a.isDirectory()){let l=await this.findJsonlFiles(o);n.push(...l)}else i.endsWith(".jsonl")&&n.push(o)}return n}}});import{readFileSync as rB,writeFileSync as sB,mkdirSync as iB}from"node:fs";import{join as oB,dirname as aB}from"node:path";import{randomUUID as lB}from"node:crypto";function eh(t){return new Zg(t)}var Zg,th=L(()=>{"use strict";Li();cR();dt();nt();hc();Zg=class extends we{constructor(e){super({provider:new Gu(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!1,canResumeInteractive:!1,canFork:!0,forkSupport:"automatic",canStructuredTurn:!1,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"skill-file",leaderSetupHint:"Place skill files in the project's .gemini/ directory"},binary:"gemini",seedArgs:["-p",ue,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:()=>Promise.reject(new Error(Hr))})}seed(e,n){return Promise.resolve({success:!1,error:Hr})}sendTurn(e,n){return Promise.reject(new Error(Hr))}openSession(e){return Promise.reject(new Error(Hr))}forkHint(e){return["Gemini fork: copies the session file with a new ID.","The forked session has the same conversation history","but diverges from that point forward."].join(`
|
|
2320
2321
|
`)}seedArgsFor(e){let n=super.seedArgsFor(e);return e?.model?[...n,"--model",e.model]:n}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:Su,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,n){let r=await this.resolvePath(e);if(!r)return{success:!1,error:`Session file not found for ${e}`};try{let s=rB(r,"utf-8"),i=Yo(s),o=ks(s),a=lB();o.sessionId=a,o.kind="main";let l=aB(r),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,m=oB(l,d);return iB(l,{recursive:!0}),sB(m,Mw(o,i),"utf-8"),{success:!0,sessionId:a,filePath:m}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}});import{readdir as uR,readFile as cB,rm as uB,stat as Gi}from"node:fs/promises";import{basename as dB,join as fn}from"node:path";function mB(t){if(!t)return null;let e={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,reasoningTokens:0},n=!1;for(let r of Object.values(t))r?.usage&&(n=!0,e.inputTokens+=r.usage.inputTokens??0,e.outputTokens+=r.usage.outputTokens??0,e.cacheReadTokens+=r.usage.cacheReadTokens??0,e.cacheWriteTokens+=r.usage.cacheWriteTokens??0,e.reasoningTokens+=r.usage.reasoningTokens??0);return n?e:null}function nh(){return{shutdownTotals:null,assistantOutputSum:0}}function mR(t,e){if(e.type==="assistant.message"){let n=e.data?.outputTokens;typeof n=="number"&&(t.assistantOutputSum+=n,t.lastAssistantOutputTokens=n)}else if(e.type==="session.shutdown"){let n=mB(e.data?.modelMetrics);n&&(t.shutdownTotals=n)}}function dR(t){let e=t.shutdownTotals,n=t.lastAssistantOutputTokens!==void 0?{outputTokens:t.lastAssistantOutputTokens}:void 0;return{totalInputTokens:e?.inputTokens,totalCachedInputTokens:e?.cacheReadTokens,totalCacheWriteInputTokens:e?.cacheWriteTokens,totalOutputTokens:e?.outputTokens??(t.lastAssistantOutputTokens===void 0?void 0:t.assistantOutputSum),totalReasoningOutputTokens:e?.reasoningTokens,lastTokenUsage:n}}function pB(t){let e={};for(let n of t.split(`
|
|
2321
2322
|
`)){let r=n.match(/^(\w+):\s*(.*)$/);r&&(e[r[1]]=r[2].trim())}return{id:e.id,cwd:e.cwd,summary_count:e.summary_count?parseInt(e.summary_count,10):void 0,created_at:e.created_at,updated_at:e.updated_at,summary:e.summary}}function qs(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function fB(t){let e=0,n=nh(),r;for await(let s of Ce(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(r=Q(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;mR(n,s)}return{messageCount:e,tokens:n,lastUserMessage:r}}function gB(t){let e=hB(t),n=new Map;for(let r of t){if(r.role!=="tool_use"||r.toolCallId===void 0)continue;if(r.toolName==="bash"){let l=e.get(r.toolCallId),u=[l?.content,l?.toolDetailedContent].filter(m=>typeof m=="string").join(`
|
|
@@ -2375,16 +2376,16 @@ ${i}`:`${n}
|
|
|
2375
2376
|
${t}`:`${n}
|
|
2376
2377
|
`}function gr(t,e){return t.stderr.write(`error: ${e}
|
|
2377
2378
|
`),1}function py(t,e){for(let n of t)n.teamfile!==void 0&&e.stderr.write(`warning: member "${n.alias}" uses deprecated member-level teamfile=; cross-team calls now work at runtime without _CONNECT_
|
|
2378
|
-
`)}var to,JW,VW,KW,eo,zW,nI,rI,gd,sq,iq,lI=L(()=>{"use strict";ra();Qf();xf();kn();Yc();ng();bg();eu();Yi();ir();$s();$x();fd();Uf();nt();to=5,JW={existsSync:XW,statSync:GW,accessSync:qW},VW=async t=>{let{seed:e}=await Promise.resolve().then(()=>(fr(),Cx)),n=await e(t);return n.success?{sessionId:n.sessionId,warnings:n.warnings,usage:or(n)}:{error:n.error??"provider seed failed",errorCode:n.errorCode,usage:or(n),sessionId:n.sessionId}},KW=!0,eo=JW,zW=vu;sq=/^\[([^\]]+)\]\s+(.*)$/s,iq=/^([^:\s][^:]*):\s+(.*)$/s});function
|
|
2379
|
-
`)||`Seed failed with exit code ${m}`,{seeded:r})}catch(i){return H(hr(i),
|
|
2380
|
-
`);return ge({prompts:s?[o.trim()].filter(a=>a.length>0):o.split(/\n\s*\n/u).map(a=>a.trim()).filter(Boolean)})}catch(r){return H(hr(r),
|
|
2379
|
+
`)}var to,JW,VW,KW,eo,zW,nI,rI,gd,sq,iq,lI=L(()=>{"use strict";ra();Qf();xf();kn();Yc();ng();bg();eu();Yi();ir();$s();$x();fd();Uf();nt();to=5,JW={existsSync:XW,statSync:GW,accessSync:qW},VW=async t=>{let{seed:e}=await Promise.resolve().then(()=>(fr(),Cx)),n=await e(t);return n.success?{sessionId:n.sessionId,warnings:n.warnings,usage:or(n)}:{error:n.error??"provider seed failed",errorCode:n.errorCode,usage:or(n),sessionId:n.sessionId}},KW=!0,eo=JW,zW=vu;sq=/^\[([^\]]+)\]\s+(.*)$/s,iq=/^([^:\s][^:]*):\s+(.*)$/s});function fe(t){if(!Ci(t))return H("invalid_argument","Expected a context created by createLmctlContext");if(t.closed)return H("cancelled","Context is closed")}function hr(t){try{let e=t?.code;return e==="ENOENT"?"missing":e==="EACCES"||e==="EPERM"||e==="EISDIR"?"read":"schema"}catch{return"read"}}function mt(t,e){let n=r=>s=>{e?.(s,r),r==="stderr"&&s.startsWith("warning:")?t.onWarning(s):t.onProgress(s,r)};return{cwd:t.cwd,env:{...t.env,LMCTL_DB:t.dbPath},dal:t.dal,stdout:{write:n("stdout")},stderr:{write:n("stderr")}}}function yr(t){return ht.find(e=>e.name===t)?.params.find(e=>e.name==="options")?.keys?.map(e=>e.name)??[]}var rn=L(()=>{"use strict";zn();en();yt()});import{existsSync as gq}from"node:fs";import{resolve as Xa}from"node:path";function hq(t,e){try{let n=fe(t);if(n)return n;if(typeof e!="string"||!e)return H("invalid_argument","Teamfile must be a nonempty string");let r=qt(Xa(t.cwd,e));return ge({members:r.members.map(s=>({alias:s.alias,provider:s.provider,model:s.model,sessionid:s.session,sessiondir:s.sessiondir}))})}catch(n){return H(hr(n),V(n))}}function yq(t,e,n){try{let r=fe(t);if(r)return r;if(typeof e!="string"||!da(e)||typeof n!="string"||!Hf(n))return H("invalid_argument","Expected a teamfile path and valid alias");let s=Lt(Xa(t.cwd,e),n,t.dal);return ge({member:{alias:s.alias,provider:s.provider,model:s.model,sessionid:s.sessionid,sessiondir:s.sessiondir},isLead:s.isLead,teamfile:s.teamfile})}catch(r){let s;try{s=r instanceof Le?r.kind:void 0}catch{}return s==="not_found"&&!V(r).includes("teamfile not found")?{status:"not_found",code:"not_found",error:V(r)}:H(s==="not_found"?"schema":s??hr(r),V(r))}}async function _q(t,e){try{let n=fe(t);if(n)return n;if(typeof e!="string"||!e)return H("invalid_argument","Teamfile must be a nonempty string");let r=await oI(Xa(t.cwd,e),mt(t)),s={errors:r.errors,warnings:r.warnings,counts:r.counts};return r.status==="ok"?ge(s):H("schema",r.errors.map(i=>i.message).join("; "),s)}catch(n){let r=V(n);return H(hr(n),r,{errors:[{alias:"",message:r}],warnings:[],counts:{errors:1,warnings:0}})}}async function vq(t,e,n={}){let r=[],s=!1;try{let i=fe(t);if(i)return i;if(typeof e!="string"||!e)return H("invalid_argument","Teamfile must be a nonempty string");if(!gq(Xa(t.cwd,e)))return H("invalid_argument","Teamfile does not exist: "+e,{seeded:r});if(!n||typeof n!="object"||Array.isArray(n))return H("invalid_argument","Seed options must be a map");let o=ht.find(p=>p.name==="seedTeam").params.find(p=>p.name==="options").keys,a=n.preamble;if(Object.keys(n).some(p=>!o.some(f=>f.name===p))||a!==void 0&&typeof a!="string"&&(typeof a!="object"||a===null||Array.isArray(a)))return H("invalid_argument","Seed options accept a string or alias map preamble only");let l=typeof a=="object"&&a!==null?{...a}:a,c=[],u=cI(c),d=mt(t,(p,f)=>{f==="stderr"&&u(p)});s=!0;let m=await aI(Xa(t.cwd,e),d,{signal:t.signal,...l===void 0?{}:{preamble:l},onSeeded:p=>{r.push({...p})}});return m===0?ge({seeded:r}):H("provider",c.join(`
|
|
2380
|
+
`)||`Seed failed with exit code ${m}`,{seeded:r})}catch(i){return H(hr(i),V(i),{seeded:r})}}function cI(t){return e=>{let n=!1;for(let r of e.split(/\r?\n/))r.startsWith("error:")?(t.push(r.replace(/^error:\s*/,"")),n=!0):n&&r.length>0&&t.push(r)}}var uI=L(()=>{"use strict";zn();kn();Rn();lI();rn();yt()});import{readFileSync as bq}from"node:fs";import{resolve as wq}from"node:path";function Eq(t,e,n={}){try{let r=fe(t);if(r)return r;if(typeof e!="string"||!e)return H("invalid_argument","Prompt path must be a nonempty string");if(!n||typeof n!="object"||Array.isArray(n))return H("invalid_argument","Prompt options must be a map");let s=n.single,i=ht.find(a=>a.name==="readPrompts").params.find(a=>a.name==="options").keys;if(Object.keys(n).some(a=>!i.some(l=>l.name===a))||s!==void 0&&typeof s!="boolean")return H("invalid_argument","Prompt options accept a boolean single only");let o=bq(wq(t.cwd,e),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2381
|
+
`);return ge({prompts:s?[o.trim()].filter(a=>a.length>0):o.split(/\n\s*\n/u).map(a=>a.trim()).filter(Boolean)})}catch(r){return H(hr(r),V(r))}}var dI=L(()=>{"use strict";zn();rn();yt()});import{join as pt}from"node:path";function gn(t){let e=mI.get(t);if(e)return e;let n=t.env.HOME;if(!n)return ur(pr());let r=t.env.XDG_DATA_HOME||pt(n,".local/share"),s=t.env.XDG_CONFIG_HOME||pt(n,".config");return e=ur(pr({museDataHome:r,miniplayerHome:t.env.MINIPLAYER_HOME||pt(r,"miniplayer"),claudeDir:pt(n,".claude"),codexDir:pt(n,".codex"),codeDir:pt(n,".code"),geminiDir:pt(n,".gemini"),copilotDir:pt(n,".copilot"),qwenDir:pt(n,".qwen"),opencodeDbPaths:[pt(r,"opencode/opencode.db"),pt(s,"opencode/opencode.db")],agyDir:pt(n,".gemini/antigravity-cli"),dshHome:pt(n,".dsh"),hermesHome:t.env.HERMES_HOME??pt(n,".hermes"),kimiHome:t.env.KIMI_CODE_HOME??pt(n,".kimi-code"),piDir:pt(n,".pi/agent/sessions"),lmplayerDbPaths:pg(t.env,n)})),mI.set(t,e),e}var mI,Ga=L(()=>{"use strict";fr();ka();mI=new WeakMap});import{resolve as Tq}from"node:path";function pI(t){let e=new Date(t.clock());return[e.getHours(),e.getMinutes(),e.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}async function fI(t,e,n,r,s,i){let o=null,a=!1,l="invalid_argument",c,u,d=new Set,m=(g,y="",b=null,_)=>({status:g,reply:y,error:b,sessionid:o,messageId:null,teamChatLogId:null,..._?{code:_}:{}}),p,f,h={status:"error"};try{let g=fe(t);if(g)return m("error","",g.error,g.code);if(!e||typeof e!="object"||Array.isArray(e))throw Error("promptAgent: member must be a map");let y={};for(let T of["provider","alias","model","effort","sessiondir","sessionid"]){let k=e[T];if(k!=null&&(typeof k!="string"||!k.trim()))throw Error(`promptAgent: ${T} must be a nonempty string when supplied`);k!=null&&(y[T]=k)}if(!y.provider)throw Error("promptAgent: provider is required");if(o=y.sessionid??null,typeof n!="string")throw Error("promptAgent: prompt must be a string");if(!r||typeof r!="object"||Array.isArray(r))throw Error("promptAgent: options must be a map");let{permissionMode:b="yolo",idleTimeoutMs:_}=r;if(Object.keys(r).some(T=>!yr("promptAgent").includes(T)))throw Error("promptAgent: unknown option");if(b!=="yolo"&&b!=="plan")throw Error("promptAgent: permissionMode must be yolo or plan");if(_!=null&&(typeof _!="number"||!Number.isFinite(_)||_<0))throw Error("promptAgent: idleTimeoutMs must be a finite nonnegative number");p=Br(t);let v=o?JSON.stringify([y.provider,o]):void 0;if(s&&(v!==i||!p.handoffSessions.has(v)))return m("error","","Reservation target does not match member","invalid_argument");if(p.activeAgents.has(e)||v!==void 0&&(p.activeSessions.has(v)||!s&&p.handoffSessions.has(v)))return m("busy","","promptAgent: session already has an active turn in this context","busy");p.activeAgents.add(e),a=!0,v&&(p.activeSessions.add(v),d.add(v));let E=mt(t);l="provider",E.stderr.write(`agent ${pI(t)}: prompting ${y.alias??y.provider}
|
|
2381
2382
|
`);let x=t.clock(),S=x,R=setInterval(()=>{try{let T=t.clock();T-S>=5e3&&E.stderr.write(`agent ${pI(t)}: still running (${Math.round((T-x)/1e3)}s elapsed)
|
|
2382
2383
|
`)}catch(T){u=T,clearInterval(R)}},5e3);R.unref(),c={poke(){try{S=t.clock()}catch(T){u=T}},stop(){clearInterval(R)}};let N=y.provider,O=Tq(t.cwd,y.sessiondir??t.cwd);if(!o&&["agy","pi","dsh"].includes(N)){if(b!=="yolo")throw Error(`promptAgent: fresh ${N} sessions require yolo seed; supply sessionid for resume`);let T,k;try{k=await ny({provider:N,cwd:O,model:y.model,effort:y.effort,env:{...t.env},signal:t.signal,onDispatch:()=>{T??=fa(E,{provider:N,cwd:O,modelRequested:y.model??null,sessionId:""},"agent")}}),await T?.finish({status:t.signal.aborted?"cancelled":k.success&&k.sessionId?"ok":"error",sessionId:k.sessionId,usage:or(k)})}catch(C){throw await T?.finish(ga(C,t.signal)),C}for(let C of k.warnings??[])E.stderr.write(`warning: ${C}
|
|
2383
2384
|
`);if(!k.success||!k.sessionId)throw Error(k.error??"promptAgent: provider did not identify the seeded session");o=k.sessionId;let I=JSON.stringify([N,o]);if(p.activeSessions.has(I)||!s&&p.handoffSessions.has(I))return m("busy","","promptAgent: seeded session is already active","busy");p.activeSessions.add(I),d.add(I)}let A=o??"";f=fa(E,{provider:N,cwd:O,modelRequested:y.model??null,sessionId:A},"agent");let w=await Ha({provider:N,cwd:O,sessionId:A,prompt:n,model:y.model,effort:y.effort,alias:y.alias,isLead:!1,permissionMode:b,timeoutMs:_,requireResume:!!A,env:{...t.env},signal:t.signal,onDelta:()=>c?.poke(),onProgress:()=>c?.poke()});if(h={status:t.signal.aborted?"cancelled":w.status??"ok",usage:or(w),sessionId:w.sessionId},u!==void 0)throw u;for(let T of w.warnings??[])E.stderr.write(`warning: ${T}
|
|
2384
|
-
`);return A&&w.sessionId!==A?(h.status=t.signal.aborted?"cancelled":"error",m("error","","promptAgent: provider changed session identity during resume","provider")):(w.sessionId&&(o=w.sessionId),w.status==="stalled"?m("stalled",w.text,"provider stalled"):w.status==="empty"?m("empty","","promptAgent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):w.sessionId?m("ok",w.text):(h.status=t.signal.aborted?"cancelled":"error",m("error",w.text,"promptAgent: provider did not return a session ID","provider")))}catch(g){return h=ga(g,t.signal,h),m("error","",
|
|
2385
|
+
`);return A&&w.sessionId!==A?(h.status=t.signal.aborted?"cancelled":"error",m("error","","promptAgent: provider changed session identity during resume","provider")):(w.sessionId&&(o=w.sessionId),w.status==="stalled"?m("stalled",w.text,"provider stalled"):w.status==="empty"?m("empty","","promptAgent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):w.sessionId?m("ok",w.text):(h.status=t.signal.aborted?"cancelled":"error",m("error",w.text,"promptAgent: provider did not return a session ID","provider")))}catch(g){return h=ga(g,t.signal,h),m("error","",V(g),l)}finally{if(await f?.finish(h),c?.stop(),a&&p){p.activeAgents.delete(e);for(let g of d)p.activeSessions.delete(g)}}}async function gI(t,e,n,r={}){return fI(t,e,n,r,!1)}async function hI(t,e,n,r={},s){return fI(t,e,n,r,!0,s)}var fy=L(()=>{"use strict";fr();en();rn();yt();Qf()});import{randomUUID as Sq}from"node:crypto";import{resolve as kq}from"node:path";function Ja(t){try{if(!t||typeof t!="object"||Array.isArray(t))return H("invalid_argument","Session target requires provider and sessionid");let e=t.provider,n=t.sessionid;return typeof e!="string"||!e.trim()||typeof n!="string"||!n.trim()?H("invalid_argument","Session target requires provider and sessionid"):{provider:e,sessionid:n}}catch(e){return H("invalid_argument",V(e))}}function yd(t){return JSON.stringify([t.provider,t.sessionid])}function yI(t,e){try{let n=fe(t);if(n)return n;let r=Ja(e);if("status"in r)return r;let s=Br(t),i=yd(r);return s.activeAgents.has(e)||s.activeSessions.has(i)?{status:"busy",error:"Session has an active turn in this context",busyReason:"turn"}:s.handoffSessions.has(i)?{status:"busy",error:"Session is reserved for handoff",busyReason:"handoff"}:ge({})}catch(n){return H("invalid_argument",V(n))}}async function _I(t,e,n,r,s={}){let i=e&&typeof e=="object"?hd.get(e):void 0;return!i||i.ctx!==t||Br(t).reservations.get(i.key)!==e?{status:"error",error:"Invalid or released session reservation",code:"invalid_argument",reply:"",sessionid:null,messageId:null,teamChatLogId:null}:hI(t,n,r,s,i.key)}function vI(t,e){try{let n=fe(t);if(n)return n;let r=Ja(e);if("status"in r)return r;let s=Br(t),i=yd(r);if(s.activeSessions.has(i)||s.handoffSessions.has(i))return{status:"busy",error:"Session is already active in this context"};let o=Object.freeze({id:Sq()}),a=!1,l=()=>{},c=()=>{a||(a=!0,s.reservations.get(i)===o&&(s.handoffSessions.delete(i),s.reservations.delete(i)),l())};return l=En(t,{async close(){c()},finalizeSync(){c()}}),hd.set(o,{ctx:t,key:i,release:c}),s.handoffSessions.add(i),s.reservations.set(i,o),ge({reservation:o})}catch(n){return H("invalid_argument",V(n))}}function bI(t,e,n=void 0){try{let r=fe(t);if(r&&!(r.code==="cancelled"&&n))return r;let s=Ja(e);if("status"in s)return s;let i=Br(t),o=yd(s);if(n!==void 0){let l=hd.get(n);return!l||l.ctx!==t||l.key!==o?H("invalid_argument","Reservation target does not match this context and session"):(l.release(),ge({}))}let a=i.reservations.get(o);return a&&hd.get(a)?.release(),ge({})}catch(r){return H("invalid_argument",V(r))}}async function wI(t,e={}){try{let n=fe(t);if(n)return n;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Session options must be a map");let{provider:r,workspace:s,all:i}=e;if(Object.keys(e).some(a=>!yr("listSessions").includes(a))||r!==void 0&&(typeof r!="string"||!r.trim())||s!==void 0&&(typeof s!="string"||!s.trim())||i!==void 0&&typeof i!="boolean")return H("invalid_argument","Expected provider, workspace and all session options");let o=await ry({registry:gn(t),provider:r,workspace:i?void 0:kq(t.cwd,s??t.cwd)});return ge({sessions:o.map(a=>({provider:a.provider,sessionid:a.sessionId,sessiondir:a.cwd,modifiedAt:a.modifiedAt.toISOString()}))})}catch(n){return H("provider",V(n))}}async function EI(t,e){try{let n=fe(t);if(n)return n;let r=Ja(e);if("status"in r)return r;let s=await gn(t).getSession(r.sessionid,r.provider);return s?ge({messages:s.messages.map(i=>({role:i.role,content:i.content}))}):{status:"not_found",error:null}}catch(n){return H("provider",V(n))}}async function TI(t,e,n){try{let r=fe(t);if(r)return r;let s=Ja(e);if("status"in s)return s;if(!n||typeof n!="object"||Array.isArray(n)||n.force!==!0||Object.keys(n).some(a=>!yr("deleteSession").includes(a)))return H("invalid_argument","force: true is required because cross-process turns cannot be detected");let i=Br(t),o=yd(s);if(i.activeAgents.has(e)||i.activeSessions.has(o)||i.handoffSessions.has(o))return{status:"busy",error:"Session has an active turn in this context"};i.activeSessions.add(o);try{return{status:await sy(s.provider,s.sessionid,gn(t))?"deleted":"not_found",error:null}}finally{i.activeSessions.delete(o)}}catch(r){return H("provider",V(r))}}var hd,SI=L(()=>{"use strict";Ga();fy();fr();en();rn();yt();hd=new WeakMap});function Ze(t){if(t==null||typeof t=="boolean")return null;let e=Number(t);return Number.isFinite(e)?Math.round(Math.min(1,Math.max(0,e))*1e6)/1e6:null}function Mn(t,e){if(t==null||typeof t=="boolean")return null;let n=Number(t);return Ze(e==="percent"?n/100:n)}function kI(t){if(t==null||typeof t=="boolean")return null;let e=Number(t);if(!Number.isFinite(e))return null;try{return new Date(Math.trunc(e)*1e3).toISOString().replace(".000Z","Z")}catch{return null}}function RI(t){if(typeof t!="string"||t.trim()==="")return null;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):null}function xI(t){let e=Number(t);return Number.isFinite(e)?e===300||e>=240&&e<=360?"five_hour":e===10080||e>=9e3&&e<=11500?"weekly":e===43200||e===44640||e>=38e3&&e<=46e3?"monthly":"unknown":"unknown"}function II(t){let e=String(t??"").trim().toLowerCase().replace(/-/g,"_").split("_").filter(Boolean);for(let n of[e[0],e.at(-1)]){if(n?.startsWith("5h")||n?.startsWith("five")||n==="session")return"five_hour";if(n?.startsWith("7d")||n?.startsWith("seven")||n?.startsWith("week"))return"weekly";if(n?.startsWith("30d")||n?.startsWith("month"))return"monthly"}return"unknown"}function no(t,e=[]){let n=t==null?"":String(t);for(let r of e)typeof r=="string"&&r.length>=4&&(n=n.replaceAll(r,"***REDACTED***"));for(let r of xq)n=n.replace(r,"***REDACTED***");return n}function ft(t){let e=Ze(t.used_fraction),n=Ze(t.remaining_fraction),r=t.resets_at==null?RI(t.resets_at_iso):Number(t.resets_at),s=t.resets_at_iso==null?kI(r):kI(RI(t.resets_at_iso)),i={bucket_id:t.bucket_id,...t.group_name!=null?{group_name:t.group_name}:{},window_type:t.window_type??"unknown",used_fraction:e??(n===null?null:Ze(1-n)),remaining_fraction:n??(e===null?null:Ze(1-e)),resets_at:r==null||!Number.isFinite(r)?null:Math.trunc(r),resets_at_iso:s,is_exhausted:t.is_exhausted??(n!==null?n<=0:e!==null?e>=1:null)};for(let o of["raw_value","raw_scale","limit_name","metered_feature","allowed","limit_reached"])t[o]!=null&&(i[o]=t[o]);return i}function Je(t,e,n={}){let r={$schema:Rq,provider:t,status:e,source:n.source??null,read_at:n.read_at??Math.floor(Date.now()/1e3),account_id:n.account_id??null,plan_type:n.plan_type??null,ordinary_usage_allowed:n.ordinary_usage_allowed??null,buckets:n.buckets??[]};for(let s of["credits","spend_control","characteristics","reason","detail","retry_after_seconds"])n[s]!=null&&(r[s]=n[s]);return r}function Ue(t,e,n,r,s,i=[],o){return Je(t,e,{source:s??null,reason:n,...r==null?{}:{detail:no(r,i)},...o==null?{}:{retry_after_seconds:o}})}function _d(t){let e=t.get("retry-after");if(e===null)return null;let n=Number.parseFloat(e);return Number.isFinite(n)&&n>=0?Math.trunc(n):null}function St(t,e,n,r=[],s){if(!t.debug&&!t.onRawResponse)return;let i=no(n,[...r].filter(o=>typeof o=="string")).replace(/("(?:access[_-]?token|refresh[_-]?token|authorization|api[_-]?key|password)"\s*:\s*")[^"\r\n]*(")/gi,"$1***REDACTED***$2");t.onRawResponse?.({source:e,...s===void 0?{}:{http_status:s},text:i}),t.debug?.(`[debug] ${e}${s===void 0?"":` HTTP ${s}`} raw response:
|
|
2385
2386
|
${i}`)}function ss(t,e,n=[]){let r;try{let i=JSON.parse(e);r=typeof i?.error=="string"?i.error:i?.error?.message??i?.message??i?.detail}catch{/^\s*[<{[]/.test(e)||(r=e.trim())}if(typeof r!="string"||!r.trim())return t;let s=no(r,n);return{...t,detail:s,provider_message:s}}var Rq,xq,Pn=L(()=>{"use strict";Rq="https://lmctl.com/schemas/lmratelimit-v1.json";xq=[/sk-ant-[A-Za-z0-9_-]{4,}/g,/sk-[A-Za-z0-9_-]{16,}/g,/\bbearer\s+[A-Za-z0-9._-]{8,}/gi,/\boat01[-_][A-Za-z0-9_-]{8,}/g,/\bcsrf[-_][A-Za-z0-9_-]{4,}/gi,/\b(?:csrf[-_]?token|x-codeium-csrf-token)\s*[:=]\s*['"]?[A-Za-z0-9._-]{4,}/gi]});import{spawnSync as Iq}from"node:child_process";import{readdirSync as Aq,readFileSync as Cq}from"node:fs";import{join as Nq}from"node:path";function Uq(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function Bq(t){let e=t.trim().toLowerCase(),n={"gemini models":"gemini","claude and gpt models":"3p",gemini:"gemini","3p models":"3p","3p":"3p"};return n[e]?n[e]:e.replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function Hq(t){let e=t.toLowerCase();return e.includes("weekly")?"weekly":e.includes("five hour")||e.includes("5-hour")||e.includes("5 hour")?"five_hour":e.includes("monthly")||e.includes("month")?"monthly":null}function Wq(t){let e={weekly:"weekly",five_hour:"5h",monthly:"monthly"},n=[];for(let r of t.split(/\r?\n/)){let s=r.trim().split(" ").map(l=>l.trim());if(s.length<3||!s[0]||!s[1])continue;let i=Hq(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=Ze(o/100);n.push(ft({bucket_id:`${Bq(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:Ze(1-a),remaining_fraction:a,resets_at_iso:s[3]||null,raw_value:o,raw_scale:"remaining_percent"}))}return n.sort((r,s)=>String(r.group_name??"").localeCompare(String(s.group_name??""))||String(r.bucket_id??"").localeCompare(String(s.bucket_id??"")))}function Va(t,e,n){return Ue("agy","provider_unavailable",t,e,"agy_cli_print")}function qq(t,e,n={}){try{let r=Fq(Math.max(t,60)*1e3,Uq(e));if(St(n,"agy_cli_print",r.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),r.error?.code==="ENOENT")return Va("agy_not_found","the agy CLI is not on PATH",t);if(r.error?.code==="ETIMEDOUT")return Va("cli_timeout","agy -p /usage did not finish in time",t);if(r.error)return Va("cli_failed",r.error.message,t);let s=Wq(r.stdout??"");return s.length===0?Va("cli_unparseable",`exit ${r.status??1}; no buckets parsed from CLI output`,t):Je("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(r){return Va("cli_failed",r instanceof Error?r.message:String(r),t)}}function NI(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||e.includes("@")||e.includes("/")||e.includes("\\")||e.includes("?")||e.includes("#")||e.includes("://")||/\s/.test(e))return null;let n;try{n=new URL(`http://${e}`)}catch{return null}if(n.username||n.password||n.pathname!=="/"||n.search||n.hash)return null;let r=n.hostname.toLowerCase();if(!(r==="localhost"||r==="127.0.0.1"||r==="[::1]"||r==="::1")||!n.port)return null;let i=Number(n.port);return!Number.isInteger(i)||i<1||i>65535||n.port!==String(i)?null:`${r==="::1"||r==="[::1]"?"[::1]":r}:${i}`}function Xq(t){let e=[],n=new Set,r=(s,i,o)=>{if(!s||!i)return;let a=NI(s);!a||n.has(`${a}\0${i}`)||(n.add(`${a}\0${i}`),e.push([a,i,o]))};r(t[AI],t[CI],-1);try{for(let s of Aq("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of Cq(Nq("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}r(i[AI],i[CI],Number(s))}catch{}}catch{}return e}function Gq(t){if(typeof t!="object"||t===null)return null;let e=t.response;if(typeof e!="object"||e===null)return null;let n=e.groups;if(!Array.isArray(n))return null;let r=[];for(let s of n){if(typeof s!="object"||s===null)continue;let i=s,o=typeof i.displayName=="string"?i.displayName:null;if(Array.isArray(i.buckets))for(let a of i.buckets){if(typeof a!="object"||a===null)continue;let l=a,c=Mn(l.remainingFraction,"fraction");r.push(ft({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:II(l.window),used_fraction:c===null?null:Ze(1-c),remaining_fraction:c,resets_at_iso:l.resetTime??null,raw_value:l.remainingFraction??null,raw_scale:"remaining_fraction"}))}}return r.length===0?null:(r.sort((s,i)=>String(s.group_name??"").localeCompare(String(i.group_name??""))||String(s.bucket_id??"").localeCompare(String(i.bucket_id??""))),Je("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:r}))}async function Jq(t,e,n={}){try{let s=jq(e).map(([a,l,c])=>[NI(a),l,c]).filter(a=>a[0]!==null);if(s.length===0)return Ue("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let i=[],o=Date.now()+t*1e3;for(let[a,l,c]of s){let u=o-Date.now();if(u<=0){i.push("overall connect deadline exceeded");break}try{let d=await $q(`http://${a}${Oq}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":l},u);if(St(n,"agy_connect_rpc",d.body,[l],d.status),d.status===200){let m;try{m=JSON.parse(d.body)}catch{i.push(`pid=${c}: unparseable response`);continue}let p=Gq(m);if(p)return p;i.push(`pid=${c}: response had no quota groups`)}else d.status===401||d.status===403?i.push(`pid=${c}: HTTP ${d.status} unauthorized`):i.push(`pid=${c}: HTTP ${d.status}`)}catch(d){i.push(`pid=${c}: ${d instanceof Error?d.message:String(d)}`)}}return Ue("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${i.slice(0,5).join("; ")}`,"agy_connect_rpc",s.map(([,a])=>a))}catch(r){return Ue("agy","provider_unavailable","connect_failed",r instanceof Error?r.message:String(r),"agy_connect_rpc")}}async function OI(t){let e=await Jq(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let n=qq(t.timeoutSeconds,t.env,t);return n.status==="ok"?n:Ue("agy","provider_unavailable","cli_and_language_server_unavailable",`cli: ${String(n.reason??n.status)} (${String(n.detail??"no detail")}); connect: ${String(e.reason??e.status)} (${String(e.detail??"no detail")})`,"agy_cli_print")}var AI,CI,Oq,Lq,Mq,Pq,Dq,Fq,$q,jq,LI=L(()=>{"use strict";Pn();Pn();AI="ANTIGRAVITY_LS_ADDRESS",CI="ANTIGRAVITY_CSRF_TOKEN",Oq="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",Lq=["-p","/usage"],Mq=(t,e)=>{let n=Iq("agy",Lq,{encoding:"utf8",timeout:t,maxBuffer:16777216,env:e,stdio:["ignore","pipe","ignore"]});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",error:n.error}},Pq=async(t,e,n)=>{let r=await fetch(t,{method:"POST",headers:e,body:"{}",signal:AbortSignal.timeout(n),redirect:"error"});return{status:r.status,body:await r.text()}},Dq=t=>Xq(t),Fq=Mq,$q=Pq,jq=Dq});import{randomUUID as DI}from"node:crypto";import{mkdirSync as Vq,readFileSync as gy,realpathSync as Kq,renameSync as zq,rmSync as hy,statSync as MI,writeFileSync as FI}from"node:fs";import{homedir as Yq}from"node:os";import{join as yy}from"node:path";import{setTimeout as Qq}from"node:timers/promises";function by(t){return yy(t.CLAUDE_CONFIG_DIR??yy(t.HOME??Yq(),".claude"),".credentials.json")}function _y(t){let e=JSON.parse(gy(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function vy(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function $I(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=by(t);try{let n=vy(_y(e));return typeof n?.accessToken=="string"&&n.accessToken?{oauth:n,path:Kq(e)}:{error:"not_claude_ai_subscriber"}}catch(n){return n.code==="ENOENT"?{error:t.ANTHROPIC_API_KEY?"not_claude_ai_subscriber":"no_credentials_found"}:{error:"credentials_unreadable"}}}function vd(t){return typeof t.expiresAt=="number"&&Date.now()+t2>=t.expiresAt}function PI(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function n2(t,e){let n=`${t}.lmctl-refresh.lock`,r=yy(n,"owner.json"),s=DI();for(;;){e.throwIfAborted();try{Vq(n,{mode:448});try{FI(r,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw hy(n,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(gy(r,"utf8")).token===s&&hy(n,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(gy(r,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-MI(n).mtimeMs>6e4}catch{try{o=Date.now()-MI(n).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await Qq(50,void 0,{signal:e})}}}async function jI(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let n=await n2(t.path,e);try{let r=vy(_y(t.path));if(!r||typeof r.accessToken!="string")throw new Error("credentials_changed");if(!PI(r,t.oauth)&&!vd(r))return r;if(typeof r.refreshToken!="string"||!r.refreshToken)throw new Error("no_refresh_token");let s=await fetch(e2,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:r.refreshToken,client_id:Zq})});if(!s.ok)throw new Error(`refresh_http_${s.status}`);let i=await s.json();if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||i.refresh_token!==void 0&&(typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)))throw new Error("invalid_refresh_response");let o=Math.floor(Date.now()+i.expires_in*1e3);if(!Number.isSafeInteger(o)||o<=Date.now())throw new Error("invalid_refresh_response");let a=_y(t.path),l=vy(a);if(!l||!PI(r,l)){if(l&&typeof l.accessToken=="string"&&!vd(l))return l;throw new Error("credentials_changed")}let c={...l,accessToken:i.access_token,refreshToken:i.refresh_token??r.refreshToken,expiresAt:o,...typeof i.scope=="string"?{scopes:i.scope.split(/\s+/).filter(Boolean)}:{}},u=`${t.path}.${DI()}.tmp`;try{FI(u,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),zq(u,t.path)}finally{hy(u,{force:!0})}return c}finally{n()}}var Zq,e2,t2,UI=L(()=>{"use strict";Zq="9d1c250a-e61b-44d9-88ed-5944d1962f5e",e2="https://console.anthropic.com/v1/oauth/token",t2=3e5});import{spawnSync as WI}from"node:child_process";function i2(t){let e=String(t??"").toLowerCase();return e.includes("session")||e.includes("five")||e.includes("5h")?"five_hour":e.includes("week")||e.includes("seven")||e.includes("7d")?"weekly":e.includes("month")||e.includes("30d")?"monthly":"unknown"}function qI(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function o2(t){try{let e=WI("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:qI(t)}),n=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(n)return`claude-code/${n}`}catch{}return"claude-code/unknown"}function hn(t,e,n,r="claude_oauth_api",s){return Ue("claude",t,e,n,r,void 0,s)}function a2(t){let e=t.get("retry-after");if(!e)return;let n=Number.parseInt(e,10);return Number.isFinite(n)?n:void 0}function l2(t){if(!t)return;let e=/^([A-Za-z]{3,9})\s+(\d{1,2}),?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?$/i.exec(t.trim());if(!e)return;let n=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"].indexOf(e[1].slice(0,3).toLowerCase());if(n<0)return;let r=Number(e[3]),s=Number(e[4]??0);(e[5]??"").toLowerCase()==="pm"&&r!==12&&(r+=12),(e[5]??"").toLowerCase()==="am"&&r===12&&(r=0);let i=new Date(Date.UTC(new Date().getUTCFullYear(),n,Number(e[2]),r,s));return Number.isFinite(i.getTime())?Math.floor(i.getTime()/1e3):void 0}function u2(t){let e=[];for(let n of t.split(/\r?\n/)){let r=c2.exec(n.trim());if(!r)continue;let s=r[1].trim(),o=s.toLowerCase()==="session",a=/\(([^)]+)\)/.exec(s)?.[1]?.trim()??s,l=o?"session":a.toLowerCase()==="all models"?"week-all-models":`week-scoped-${a}`,c=o?"five_hour":"weekly";e.push(ft({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:Mn(Number(r[2]),"percent"),raw_value:Number(r[2]),raw_scale:"used_percent",resets_at:l2(r[3])}))}return e.sort((n,r)=>String(n.window_type).localeCompare(String(r.window_type))||String(n.bucket_id).localeCompare(String(r.bucket_id)))}function d2(t){let e={},n;for(let r of t.split(/\r?\n/)){let s=/^Last\s+(\S+)\s*[·-]\s*(\d+)\s+requests?\s*[·-]\s*(\d+)\s+sessions?\s*$/.exec(r.trim());if(s){n={requests:Number(s[2]),sessions:Number(s[3])},e[`window_${s[1].toLowerCase()}`]=n;continue}let i=/^\s+(\d+)%\s+of your usage\s+(.+?)\s*$/.exec(r);if(!i||!n)continue;let o=i[2].toLowerCase(),a=o.includes(">150k context")?"pct_high_context":o.includes("active for 8+ hours")?"pct_long_sessions":o.includes("subagent-heavy")?"pct_subagent_heavy":o.includes("ran in parallel")?"pct_parallel_sessions":void 0;a&&(n[a]=Number(i[1]))}return e}function m2(t,e){let n=t&&typeof t=="object"?t:void 0,r=e&&typeof e=="object"?e:void 0,s=!!(n?.limit||n?.used||n?.percent!==void 0);if(!s&&(!r||r.is_enabled===!1))return;let i=s&&n?.limit&&typeof n.limit=="object"?n.limit:{},o=s&&n?.used&&typeof n.used=="object"?n.used:{},a=y=>{let b=typeof y=="number"?y:typeof y=="string"&&y.trim()!==""?Number(y):NaN;return Number.isSafeInteger(b)&&b>=0&&b<=9?b:void 0},l=y=>{let b=typeof y=="number"?y:typeof y=="string"&&y.trim()!==""?Number(y):NaN;return Number.isFinite(b)?b:void 0},c=a(i.exponent??r?.decimal_places??2),u=a(o.exponent??r?.decimal_places??2),d=s?i.amount_minor:r?.monthly_limit,m=s?o.amount_minor:r?.used_credits,p=(y,b,_)=>b===void 0||_!==void 0&&_!=="USD"||l(y)===void 0?void 0:(l(y)/10**b).toFixed(2),f=Mn(s?n?.percent:r?.utilization,"percent"),h=s?n?.spend_limit_reached??r?.spend_limit_reached:r?.spend_limit_reached,g={limit_usd:p(d,c,i.currency??r?.currency),used_usd:p(m,u,o.currency??r?.currency),remaining_fraction:f==null?void 0:Math.max(0,1-f),resets_at_iso:s?n?.resets_at:void 0,...typeof h=="boolean"?{reached:h}:{}};return Object.values(g).every(y=>y==null)?void 0:g}async function HI(t,e,n,r={}){try{let s=WI("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(n,60)*1e3,input:"",env:qI(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";St(r,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=u2(i);if(!o.length)return;let a=d2(i);return Je("claude",rt.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:o,...Object.keys(a).length?{characteristics:a}:{}})}catch{return}}async function XI({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s=$I(e);if(s.error==="not_claude_ai_subscriber")return hn(rt.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return hn(rt.unavailable,"credentials_missing",`credentials file not found: ${by(e)}`);if(s.error)return hn(rt.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(BI))return hn(rt.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${BI} scope required by the usage endpoint`);let a=new AbortController,l=setTimeout(()=>a.abort(),t*1e3),c,u;try{let y=!1,b=async()=>{try{i=await jI({...s,oauth:i},a.signal),y=!0}catch(v){let E=v instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(v.message)?v.message:"refresh_failed";if(E==="refresh_http_429")return hn(rt.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(E==="refresh_lock_stale")return hn(rt.expired,"oauth_refresh_locked","a previous Claude credential refresh exited without releasing its lock; remove the stale .credentials.json.lmctl-refresh.lock directory before retrying");let x=E==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(E);return hn(x?rt.expired:rt.unavailable,x?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${E})${x?"; renew Claude login":"; try again later"}`)}};if(vd(i)){let v=await b();if(v)return v}let _=()=>fetch(`${r2}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":s2,"Content-Type":"application/json","User-Agent":o2(e)},signal:a.signal});if(c=await _(),u=await c.text(),St({debug:n,onRawResponse:r},"claude_oauth_api",u,[i.accessToken,i.refreshToken],c.status),c.status===401&&!y&&s.path&&i.refreshToken){let v=await b();if(v)return v;c=await _(),u=await c.text(),St({debug:n,onRawResponse:r},"claude_oauth_api",u,[i.accessToken,i.refreshToken],c.status)}}catch(y){let b=await HI(i,e,t,{debug:n,onRawResponse:r});return b||hn(rt.unavailable,"request_failed",`${y instanceof Error?y.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let d=(...y)=>ss(hn(...y),u,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return d(rt.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return d(rt.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let y=a2(c.headers),b=await HI(i,e,t,{debug:n,onRawResponse:r});return b||d(rt.throttled,"rate_limited",`usage endpoint rate limited${y==null?"":`; retry after ${y}s`}`,"claude_oauth_api",y)}if(c.status!==200)return d(rt.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let m;try{m=JSON.parse(u)}catch{return hn(rt.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!m||typeof m!="object"||Array.isArray(m))return hn(rt.unavailable,"malformed_response","response was not an object");let p=m,f=Array.isArray(p.limits)?p.limits:[],h=f.length?f.flatMap(y=>{if(!y||typeof y!="object")return[];let b=y.kind,_=i2(b==="session"?"session":b),v=y.scope?.model?.display_name,E=b==="session"?"session":b==="weekly_all"?"week-all-models":`week-scoped-${v||b}`;return[ft({bucket_id:E,group_name:b==="session"?"session":"weekly",window_type:_,used_fraction:Mn(y.percent,"percent"),resets_at_iso:y.resets_at,raw_value:y.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(y=>{let b=p[y];return!b||typeof b!="object"?[]:[ft({bucket_id:y==="five_hour"?"session":"week-all-models",group_name:y==="five_hour"?"session":"weekly",window_type:y==="five_hour"?"five_hour":"weekly",used_fraction:Mn(b.utilization,"percent"),resets_at_iso:b.resets_at,raw_value:b.utilization,raw_scale:"used_percent"})]}),g=m2(p.spend,p.extra_usage);return Je("claude",rt.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:h.sort((y,b)=>String(y.window_type).localeCompare(String(b.window_type))||String(y.bucket_id).localeCompare(String(b.bucket_id))),...g?{spend_control:g}:{}})}var r2,s2,BI,rt,c2,GI=L(()=>{"use strict";Pn();UI();Pn();r2="https://api.anthropic.com",s2="oauth-2025-04-20",BI="user:profile";rt={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};c2=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/});import{randomUUID as KI}from"node:crypto";import{mkdirSync as p2,readFileSync as wy,realpathSync as f2,renameSync as g2,rmSync as Ey,statSync as JI,writeFileSync as zI}from"node:fs";import{homedir as h2}from"node:os";import{join as Ty}from"node:path";import{setTimeout as y2}from"node:timers/promises";function Ka(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function ky(t){if(t.CODEX_AUTH_PATH)return t.CODEX_AUTH_PATH;let e=t.CODEX_HOME||Ty(t.HOME||h2(),".codex");return Ty(e,"auth.json")}function Sy(t){let e=Ka(JSON.parse(wy(t,"utf8")));if(!e)throw new Error("invalid credential document");return e}function YI(t){if(t.CODEX_ACCESS_TOKEN)return{tokens:{access_token:t.CODEX_ACCESS_TOKEN,account_id:t.CODEX_ACCOUNT_ID}};let e=ky(t);try{let n=Ka(Sy(e).tokens);return typeof n?.access_token=="string"&&n.access_token?{tokens:n,path:f2(e)}:{error:"credentials_missing"}}catch(n){return{error:n.code==="ENOENT"?"credentials_missing":"credentials_unreadable"}}}function VI(t,e){return t.access_token===e.access_token&&t.refresh_token===e.refresh_token&&t.id_token===e.id_token&&t.account_id===e.account_id}async function b2(t,e){let n=`${t}.lmctl-refresh.lock`,r=Ty(n,"owner.json"),s=KI();for(;;){e.throwIfAborted();try{p2(n,{mode:448});try{zI(r,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Ey(n,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(wy(r,"utf8")).token===s&&Ey(n,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(wy(r,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-JI(n).mtimeMs>6e4}catch{try{o=Date.now()-JI(n).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await y2(50,void 0,{signal:e})}}}async function QI(t,e){if(!t.path||typeof t.tokens?.refresh_token!="string"||!t.tokens.refresh_token)throw new Error("no_refresh_token");let n=await b2(t.path,e);try{let r=Sy(t.path),s=Ka(r.tokens);if(!s||typeof s.access_token!="string")throw new Error("credentials_changed");if(!VI(s,t.tokens)&&typeof s.access_token=="string")return s;if(typeof s.refresh_token!="string"||!s.refresh_token)throw new Error("no_refresh_token");let i=await fetch(_2,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:s.refresh_token,client_id:v2})});if(!i.ok)throw new Error(`refresh_http_${i.status}`);let o=Ka(await i.json());if(!o||typeof o.access_token!="string"||!/^\S+$/.test(o.access_token)||o.refresh_token!==void 0&&(typeof o.refresh_token!="string"||!/^\S+$/.test(o.refresh_token))||o.id_token!==void 0&&(typeof o.id_token!="string"||!/^\S+$/.test(o.id_token)))throw new Error("invalid_refresh_response");let a=Sy(t.path),l=Ka(a.tokens);if(!l||!VI(s,l)){if(l&&typeof l.access_token=="string")return l;throw new Error("credentials_changed")}let c={...l,access_token:o.access_token,...o.refresh_token===void 0?{}:{refresh_token:o.refresh_token},...o.id_token===void 0?{}:{id_token:o.id_token}},u={...a,tokens:c,last_refresh:new Date().toISOString()},d=`${t.path}.${KI()}.tmp`;try{zI(d,JSON.stringify(u),{flag:"wx",mode:384}),g2(d,t.path)}finally{Ey(d,{force:!0})}return c}finally{n()}}var _2,v2,ZI=L(()=>{"use strict";_2="https://auth.openai.com/oauth/token",v2="app_EMoamEEZ73f0CkXaXp7hrann"});function Dn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function eA(t){let e=typeof t=="number"?t:Number(t);if(!Number.isFinite(e)||e<=0)return"unknown";let n=e/60;return n>=240&&n<=360?"five_hour":n>=9e3&&n<=11500?"weekly":n>=38e3&&n<=46e3?"monthly":"unknown"}function tA(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function T2(t){if(Dn(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function S2(t){let e=[],n=Dn(t.rate_limit)?t.rate_limit:{},r=typeof n.allowed=="boolean"?n.allowed:void 0,s=typeof n.limit_reached=="boolean"?n.limit_reached:void 0;for(let o of["primary_window","secondary_window"]){let a=Dn(n[o])?n[o]:void 0;if(!a)continue;let l=eA(a.limit_window_seconds);e.push(ft({bucket_id:`codex-${tA(l)}`,group_name:"codex",window_type:l,used_fraction:Mn(a.used_percent,"percent"),resets_at:a.reset_at,raw_value:a.used_percent,raw_scale:"used_percent",...r===void 0?{}:{allowed:r},...s===void 0?{}:{limit_reached:s}}))}let i=Array.isArray(t.additional_rate_limits)?t.additional_rate_limits:[];for(let o of i){if(!Dn(o))continue;let a=Dn(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,u=c||l||"additional",d=typeof a.allowed=="boolean"?a.allowed:void 0,m=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let p of["primary_window","secondary_window"]){let f=Dn(a[p])?a[p]:void 0;if(!f)continue;let h=eA(f.limit_window_seconds);e.push(ft({bucket_id:`${u}-${tA(h)}`,group_name:l||u,window_type:h,used_fraction:Mn(f.used_percent,"percent"),resets_at:f.reset_at,raw_value:f.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...d===void 0?{}:{allowed:d},...m===void 0?{}:{limit_reached:m}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function k2(t){let e=Dn(t.rate_limit)?t.rate_limit:{},n=typeof e.allowed=="boolean"?e.allowed:void 0,r=Dn(t.spend_control)?t.spend_control:void 0,s=Dn(t.credits)?t.credits:void 0;return Je("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...n===void 0?{}:{ordinary_usage_allowed:n},buckets:S2(t),...s?{credits:T2(s)}:{},...r?{spend_control:r}:{}})}async function nA(t){let{timeoutSeconds:e,env:n,debug:r,onRawResponse:s}=t,i=YI(n),o=i.tokens;if(!o||typeof o.access_token!="string")return Je("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:`no access_token in ${ky(n)} (or $CODEX_ACCESS_TOKEN)`});let a=new AbortController,l=setTimeout(()=>a.abort(),Math.ceil(e*1e3)),c=o.access_token,u=new Set([o.access_token,o.refresh_token,o.id_token].filter(d=>typeof d=="string"&&!!d));try{let d=typeof o.account_id=="string"?o.account_id:void 0,m=typeof o.refresh_token=="string"?o.refresh_token:void 0,p=typeof o.id_token=="string"?o.id_token:void 0,f="",h=()=>[...u],g=(x,S)=>ss(Je("codex",x,S),f,h()),y=!1,b=async()=>{if(!(y||!i.path||typeof o.refresh_token!="string"))try{let x=await QI({...i,tokens:{...o,refresh_token:m}},a.signal);typeof x.access_token=="string"&&(u.add(x.access_token),c=x.access_token),d=typeof x.account_id=="string"?x.account_id:d,typeof x.refresh_token=="string"&&(u.add(x.refresh_token),m=x.refresh_token),typeof x.id_token=="string"&&(u.add(x.id_token),p=x.id_token),y=!0;return}catch(x){let S=x instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(x.message)?x.message:"refresh_failed",R=S==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(S);return Je("codex",R?"auth_expired":"provider_unavailable",{source:"codex_http",reason:R?"oauth_token_expired_or_invalid":"oauth_refresh_failed",detail:`Codex OAuth refresh failed (${S})${R?"; renew Codex login":"; try again later"}`})}},_=()=>{let x={Authorization:`Bearer ${c}`,"User-Agent":E2,"Content-Type":"application/json",Accept:"application/json"};d&&(x["ChatGPT-Account-Id"]=d);let S=(n.CODEX_BASE_URL||w2).replace(/\/$/,"");return fetch(`${S}/wham/usage`,{headers:x,signal:a.signal})},v=await _();if(f=await v.text(),St({debug:r,onRawResponse:s},"codex_http",f,h(),v.status),v.status===401&&i.path&&m){let x=await b();if(x)return x;v=await _(),f=await v.text(),St({debug:r,onRawResponse:s},"codex_http",f,h(),v.status)}if(v.status===401)return g("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(v.status===429){let x=v.headers.get("retry-after"),S=x===null?void 0:Number.parseInt(x,10);return g("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...S!==void 0&&Number.isFinite(S)&&S>=0?{retry_after_seconds:S}:{}})}if(!v.ok)return g("provider_unavailable",{source:"codex_http",reason:`http_${v.status}`,detail:"codex usage endpoint returned an unexpected status"});let E;try{E=JSON.parse(f)}catch(x){return Je("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:no(String(x),u)})}return Dn(E)?k2(E):Je("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(d){let m=d instanceof Error?`${d.name}: ${d.message}`:String(d);return Je("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:no(m,u)})}finally{clearTimeout(l)}}var w2,E2,rA=L(()=>{"use strict";Pn();ZI();Pn();w2="https://chatgpt.com/backend-api",E2="codex-cli"});import{createHash as R2,randomUUID as x2}from"node:crypto";import{readFileSync as lA,openSync as I2,fsyncSync as A2,closeSync as C2,mkdirSync as sA,writeFileSync as cA,renameSync as N2,rmSync as O2,rmdirSync as L2,statSync as Ry,utimesSync as M2}from"node:fs";import{homedir as P2}from"node:os";import{basename as D2,dirname as F2,join as bd}from"node:path";import{setTimeout as uA}from"node:timers/promises";function j2(t){let e;try{e=lA(t,"utf8")}catch(s){if(s.code==="ENOENT")return{};throw new Error("config_unreadable")}let n={},r="other";for(let s of e.split(/\r?\n/)){let i=/^\s*\[providers\.(?:"managed:kimi-code"|'managed:kimi-code')(\.oauth)?\]\s*(?:#.*)?$/.exec(s);if(i){r=i[1]?"oauth.":"";continue}if(/^\s*\[/.test(s)){if(s.includes("managed:kimi-code"))throw new Error("config_format_unsupported");r="other";continue}if(r==="other")continue;if(/^\s*oauth\s*=/.test(s))throw new Error("config_format_unsupported");let o=/^\s*(base_url|oauth_host|storage|key)\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(s);if(!o&&/^\s*(base_url|oauth_host|storage|key)\s*=/.test(s))throw new Error("config_malformed");if(o)try{n[r+o[1]]=o[2].startsWith('"')?JSON.parse(o[2]):o[2].slice(1,-1)}catch{throw new Error("config_malformed")}}return n}function wd(t){let e;try{e=JSON.parse(lA(t,"utf8"))}catch(n){throw new Error(n.code==="ENOENT"?"credentials_missing":"credentials_malformed")}if(e&&typeof e=="object"&&e.access_token===""&&e.refresh_token==="")throw new Error("credentials_revoked");if(!e||typeof e!="object"||Array.isArray(e)||typeof e.access_token!="string"||!e.access_token.trim())throw new Error("credentials_malformed");return e}function dA(t){let e=t.KIMI_CODE_HOME??bd(t.HOME??P2(),".kimi-code"),n=j2(t.KIMI_CODE_CONFIG_PATH??bd(e,"config.toml")),r=t.KIMI_CODE_BASE_URL!==void 0||t.KIMI_CODE_OAUTH_HOST!==void 0||t.KIMI_OAUTH_HOST!==void 0,s=oA(t.KIMI_CODE_BASE_URL??n.base_url??iA),i=oA(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(r?xy:n["oauth.oauth_host"]??xy)),o=s===iA&&i===xy?"kimi-code":`kimi-code-env-${R2("sha256").update(JSON.stringify({oauthHost:i,baseUrl:s})).digest("hex").slice(0,16)}`;if(!t.KIMI_CREDENTIALS_PATH&&!r&&n["oauth.key"]===`oauth/${o}`&&n["oauth.storage"]&&n["oauth.storage"]!=="file")throw new Error("credential_storage_unsupported");let a=t.KIMI_CREDENTIALS_PATH??bd(e,"credentials",`${o}.json`),l=wd(a),c=a,u=D2(a,".json");return{home:e,path:c,lockTarget:bd(e,"oauth",u),baseUrl:s,oauthHost:i,token:l}}function Ed(t){if(typeof t.expires_at!="number")return!1;let e=typeof t.expires_in=="number"?t.expires_in:0;return t.expires_at-Date.now()/1e3<Math.max(300,e*.5)}function aA(t,e){return t.access_token===e.access_token&&t.refresh_token===e.refresh_token&&t.expires_at===e.expires_at&&t.expires_in===e.expires_in}async function U2(t,e){sA(F2(t),{recursive:!0}),cA(t,"",{flag:"a",mode:384});let n=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{sA(n);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-Ry(n).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await uA(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let r=Ry(n),s=()=>{let o;try{o=Ry(n)}catch{throw new Error("refresh_lock_lost")}if(o.ino!==r.ino||o.dev!==r.dev)throw new Error("refresh_lock_lost")},i=setInterval(()=>{try{s();let o=new Date;M2(n,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),L2(n)}catch{}}}}async function mA(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let n=await U2(t.lockTarget,e);try{let r=wd(t.path);if(!aA(r,t.token)&&!Ed(r))return r;if(typeof r.refresh_token!="string"||!r.refresh_token)throw new Error("no_refresh_token");let s;for(let d=0;d<3;d++){try{if(s=await fetch(`${t.oauthHost}/api/oauth/token`,{method:"POST",signal:e,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":"lmctl"},body:new URLSearchParams({client_id:$2,grant_type:"refresh_token",refresh_token:r.refresh_token})}),![429,500,502,503,504].includes(s.status)||d===2)break;await s.body?.cancel()}catch{if(e.aborted||d===2)throw new Error("refresh_request_failed")}await uA(1e3*2**d,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let d=wd(t.path);if(d.refresh_token!==r.refresh_token)return d}catch{}throw new Error(`refresh_http_${s.status}`)}let i=await s.json(),o=Number(i?.expires_in);if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)||!Number.isFinite(o)||o<=0)throw new Error("invalid_refresh_response");let a=Math.floor(Date.now()/1e3)+o;if(!Number.isSafeInteger(a))throw new Error("invalid_refresh_response");n.assertOwned();let l=wd(t.path);if(!aA(l,r)){if(!Ed(l))return l;throw new Error("credentials_changed")}let c={...l,access_token:i.access_token,refresh_token:i.refresh_token,expires_at:a,expires_in:o,...typeof i.scope=="string"?{scope:i.scope}:{},...typeof i.token_type=="string"?{token_type:i.token_type}:{}},u=`${t.path}.${x2()}.tmp`;try{let d=I2(u,"wx",384);try{cA(d,JSON.stringify(c,null,2)+`
|
|
2386
|
-
`),A2(d)}finally{C2(d)}n.assertOwned(),N2(u,t.path)}finally{O2(u,{force:!0})}return c}finally{n.release()}}var iA,xy,$2,oA,pA=L(()=>{"use strict";iA="https://api.kimi.com/coding/v1",xy="https://auth.kimi.com",$2="17e5f671-d194-4dfb-9706-5516cb48c098",oA=t=>t.trim().replace(/\/+$/,"")});function fA(t){let e=o=>{if(typeof o!="number"&&typeof o!="string"||typeof o=="string"&&o.trim()==="")return;let a=Number(o);return Number.isFinite(a)&&a>=0?a:void 0},n=e(t.limit),r=e(t.used),s=e(t.remaining);if(n===void 0||n<=0||r===void 0&&(s===void 0||s>n))return;let i=r??n-s;return{used:i,limit:n,remaining:Math.max(0,n-i)}}async function gA({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s;try{s=dA(e)}catch(h){let g=h instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(h.message)?h.message:"credentials_unreadable";return Ue("kimi",g==="credentials_revoked"?"auth_expired":"provider_unavailable",g,g==="credentials_revoked"?"Kimi login was revoked; run kimi login":g.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let h=!1,g=async()=>{i=await mA({...s,token:i},o.signal),h=!0};Ed(i)&&await g();let y=()=>fetch(`${s.baseUrl}/usages`,{headers:{Authorization:`Bearer ${i.access_token}`,Accept:"application/json"},signal:o.signal});l=await y(),c=await l.text(),St({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!h&&i.refresh_token&&(await g(),l=await y(),c=await l.text(),St({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(h){let g=h instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(h.message)?h.message:"request_failed",y=g==="credentials_revoked"||g==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(g),b=g==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":y?`Kimi credential renewal failed (${g}); run kimi login`:`Kimi quota request failed (${g})`;return Ue("kimi",y?"auth_expired":"provider_unavailable",g,b,"kimi_http")}finally{clearTimeout(a)}let u=(h,g,y)=>ss(Ue("kimi",h,g,g,"kimi_http",[],y),c,[i.access_token]);if(l.status===401)return u("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return u("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let h=_d(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",h)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return Ue("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return Ue("kimi","provider_unavailable","malformed_response","response was not an object");let m=[],p=new Set;function f(h){let g=String(h.bucket_id),y=g,b=2;for(;p.has(g);)g=`${y}-${b}`,b++;p.add(g),h.bucket_id=g,m.push(ft(h))}if(Array.isArray(d.limits))for(let h of d.limits){if(!h||typeof h!="object")continue;let g=h.window,y=h.detail;if(!g||typeof g!="object"||!y||typeof y!="object")continue;let b=0;if(g.timeUnit==="TIME_UNIT_MINUTE")b=Number(g.duration);else if(g.timeUnit==="TIME_UNIT_HOUR")b=Number(g.duration)*60;else if(g.timeUnit==="TIME_UNIT_DAY")b=Number(g.duration)*1440;else if(g.timeUnit==="TIME_UNIT_WEEK")b=Number(g.duration)*10080;else if(g.timeUnit==="TIME_UNIT_MONTH")b=Number(g.duration)*43200;else continue;let _=xI(b),v="window";_==="five_hour"&&(v="5h"),_==="weekly"&&(v="weekly"),_==="monthly"&&(v="monthly");let E=fA(y);if(!E)continue;let{used:x,limit:S,remaining:R}=E;f({bucket_id:`kimi-${v}`,window_type:_,used_fraction:Ze(x/S),remaining_fraction:Ze(R/S),resets_at_iso:y.resetTime,raw_value:x,raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let h=fA(d.usage);h&&f({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:Ze(h.used/h.limit),remaining_fraction:Ze(h.remaining/h.limit),resets_at_iso:d.usage.resetTime,raw_value:h.used,raw_scale:"count"})}if(d.usages&&typeof d.usages=="object"){let h=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:g,id:y,type:b}of h){let _=d.usages[g];if(!_||typeof _!="object"||_.used_ratio==null||_.used_ratio===""||typeof _.used_ratio=="boolean")continue;let v=Number(_.used_ratio);!Number.isFinite(v)||v<0||p.has(y)||(p.add(y),m.push(ft({bucket_id:y,window_type:b,used_fraction:Ze(v),resets_at_iso:typeof _.reset_time=="string"&&_.reset_time?_.reset_time:null,raw_value:v,raw_scale:"ratio"})))}}return Je("kimi","ok",{source:"kimi_http",buckets:m})}var hA=L(()=>{"use strict";Pn();pA();Pn()});function za(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Td(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);if(Number.isFinite(e))return e}}async function yA(t){let{timeoutSeconds:e,env:n,debug:r,onRawResponse:s,fetchFn:i=fetch}=t,o=n.OLLAMA_API_KEY?.trim();if(!o)return Ue("ollama-cloud","provider_unavailable","credentials_missing","$OLLAMA_API_KEY is missing","ollama_http");let a="https://ollama.com/api/balance",l=new AbortController,c=setTimeout(()=>l.abort(),Math.ceil(e*1e3)),u,d="";try{u=await i(a,{method:"GET",redirect:"error",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:l.signal}),d=await u.text();let g=d;try{g=JSON.stringify(JSON.parse(d))}catch{}St({debug:r,onRawResponse:s},"ollama_http",g,[o],u.status)}catch(g){let y=g instanceof Error&&g.name==="AbortError",b=y?`Ollama quota request timed out after ${e}s`:`Ollama quota request failed (${g instanceof Error?g.message:String(g)})`;return Ue("ollama-cloud","provider_unavailable",y?"request_timeout":"request_failed",b,"ollama_http",[o])}finally{clearTimeout(c)}let m=(g,y,b)=>ss(Ue("ollama-cloud",g,y,y,"ollama_http",[o],b),d,[o]);if(u.status===401)return m("auth_expired","HTTP 401 from Ollama balance endpoint");if(u.status===403)return m("not_applicable","HTTP 403 from Ollama balance endpoint");if(u.status===429){let g=_d(u.headers);return m("reader_throttled","HTTP 429 from Ollama balance endpoint",g)}if(u.status!==200)return m("provider_unavailable",`HTTP ${u.status} from Ollama balance endpoint`);let p;try{p=JSON.parse(d)}catch{return Ue("ollama-cloud","provider_unavailable","malformed_response","SyntaxError: malformed JSON","ollama_http")}if(!za(p))return Ue("ollama-cloud","provider_unavailable","malformed_response","response was not an object","ollama_http");let f=[];if(za(p.included)){let g=p.included,y=Td(g.allowance_usd),b=Td(g.balance_usd),_=za(g.period)?g.period:void 0,v=typeof _?.from=="string"?Date.parse(_.from):NaN,E=typeof _?.until=="string"?Date.parse(_.until):NaN,x=Number.isFinite(v)&&Number.isFinite(E)&&E>v,S=x?new Date(E).toISOString():null;if(y!==void 0&&y>0&&b!==void 0){let R=Math.max(0,y-b);f.push({...ft({bucket_id:"ollama-cloud-monthly",group_name:"ollama-cloud",window_type:"monthly",used_fraction:Ze(R/y),remaining_fraction:Ze(b/y),resets_at_iso:S,is_exhausted:b<=0,raw_value:b,raw_scale:"balance_usd"}),window_start_iso:x?new Date(Math.floor(v/1e3)*1e3).toISOString().replace(".000Z","Z"):null})}if(y===void 0&&b===void 0)for(let[R,N,O]of[["session","five_hour","5h"],["weekly","weekly","weekly"]]){let A=g[R];if(!za(A))continue;let w=Td(A.remaining_percent);w===void 0||w<0||w>100||f.push(ft({bucket_id:`ollama-cloud-${O}`,group_name:"ollama-cloud",window_type:N,remaining_fraction:w/100,resets_at_iso:typeof A.resets_at=="string"?A.resets_at:null,raw_value:w,raw_scale:"remaining_percent"}))}}let h;if(za(p.purchased)){let g=p.purchased,y=Td(g.balance_usd);y!==void 0&&(h={has_credits:y>0,balance:y})}return f.length===0&&h===void 0?Ue("ollama-cloud","provider_unavailable","malformed_response","response has no usable included allowance or purchased balance","ollama_http"):Je("ollama-cloud","ok",{source:"ollama_http",buckets:f,...h?{credits:h}:{}})}var _A=L(()=>{"use strict";Pn()});async function bA(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(d=>typeof d!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let d of e)if(!vA.includes(d))return{status:"error",error:`unknown provider: ${d} (valid targets: ${vA.join(", ")})`,readings:[]};let n=t.timeoutSeconds??B2;if(!Number.isFinite(n)||n<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let r=t.env??process.env,s=["codex","agy","claude","kimi"];(r.OLLAMA_API_KEY?.trim()||e.includes("ollama-cloud"))&&s.push("ollama-cloud");let i=new Set(e.includes("all")?s:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${n}s per provider) ...`);let a=Object.entries({codex:nA,agy:OI,claude:XI,kimi:gA,"ollama-cloud":yA}).filter(([d])=>i.has(d)).map(async([,d])=>{let m=[],p=await d({timeoutSeconds:n,env:r,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:h=>m.push(h)}:{}}),f=t.includeRaw?{...p,raw_responses:m}:p;return f&&t.onReading?.(f),f}),l=await Promise.allSettled(a),c=l.find(d=>d.status==="rejected");return c?{status:"error",error:String(c.reason),readings:[]}:{status:"ok",readings:l.filter(d=>d.status==="fulfilled").map(d=>d.value).filter(Boolean)}}var vA,B2,wA=L(()=>{"use strict";LI();GI();rA();hA();_A();vA=["all","codex","agy","claude","kimi","ollama-cloud"],B2=15});async function H2(t,e={}){try{let n=pe(t);if(n)return n;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Ratelimit options must be a map");let{providers:r,provider:s,timeoutSeconds:i=15}=e,o=r??(s===void 0?["all"]:[s]);if(Object.keys(e).some(l=>!yr("readRatelimits").includes(l))||!Array.isArray(o)||o.some(l=>typeof l!="string"||!l||l.startsWith("-")))return H("invalid_argument","providers must be a list of provider names");if(typeof i!="number"||!Number.isFinite(i)||i<=0)return H("invalid_argument","timeoutSeconds must be a positive finite number");let a=await bA({providers:o.length?[...o]:["all"],timeoutSeconds:i,env:{...t.env},progress:l=>t.onProgress(l+`
|
|
2387
|
-
`,"stderr")});return a.status==="ok"?ge({readings:a.readings}):H("provider",a.error,{readings:[]})}catch(n){return H("provider",G(n),{readings:[]})}}var EA=L(()=>{"use strict";wA();rn();yt()});function Iy(t){return t.trim().toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function J2(t,e,n,r){let s=new Set,i=[];for(let o of e){let a=n===null?null:Ic(t,o,n,r),l=a?.kind==="priced"||a?.kind==="estimated"?`id:${a.model.normalizedId}`:a?.kind==="known-unpriced"?`id:${a.id}`:`raw:${o.trim().toLowerCase()}`;s.has(l)||(s.add(l),i.push(o))}return i}async function TA(t,e,n){let r=[...new Set([...n.messages.map(A=>A.model),...(n.responses??[]).map(A=>A.model??void 0)].filter(A=>A!==void 0&&A!=="<synthetic>"))],s=[...n.messages].reverse().find(A=>A.model!==void 0&&A.model!=="<synthetic>")?.model,i=n.model??s??null,o=Rr(n.responses??[],n.captureStatus!=="partial"),a=t==="gemini"&&(n.totalOutputTokens!==void 0||n.totalReasoningOutputTokens!==void 0)?(n.totalOutputTokens??0)+(n.totalReasoningOutputTokens??0):n.totalOutputTokens??null,l={input:n.responses?o.input_uncached:n.totalInputTokens??null,output:n.responses?o.output:a,cachedInput:n.responses?o.input_cached:n.totalCachedInputTokens??null},c=await As(),u=J2(t,r,c.catalog,c.aliases),d=n.responses===void 0&&u.length>1,m="unavailable",p=null,f=null,h=null,g=null,y=!1,b=null,_=null;if(i!==null&&c.catalog!==null){let A=Ei(t,i,c.catalog,c.aliases);if(m=A.state.kind,A.offer!==null)_=A.offer.pricing,p=A.offer.route,f=A.offer.source,h=A.offer.sourceModelId,g=A.provenance,y=A.offer.estimated;else switch(A.state.kind){case"unresolved":b=`alias "${A.state.alias}" is deliberately unresolved in the lmprice alias table`;break;case"known-unpriced":b=`"${A.state.id}" is a known model with no published price row`;break;case"unknown":b=`model "${i}" not found in lmprice catalog for provider "${t}"`;break;case"wrong-provider":b=`model "${i}" is not offered by provider "${t}" (found under: ${A.state.otherProviders.join(", ")})`;break;default:b=`no lmprice catalog coverage for provider "${t}"`;break}}else i!==null&&(b="lmprice catalog unavailable");let v=_===null?null:{inputPer1m:_.input_per_1m_tokens,outputPer1m:_.output_per_1m_tokens,cachedInputPer1m:_.input_cache_read_per_1m_tokens},E=l.cachedInput??0,x=n.totalCacheWriteInputTokens??0,S=["claude","codex","gemini","qwen","copilot"].includes(t),R=l.input===null?null:Math.max(0,l.input-(S?E:0)-(t==="claude"||t==="copilot"?x:0)),N=l.input===null||l.output===null?null:ea({input:R,output:l.output,cachedInput:E,...x>0?{cacheWrite:x,...n.totalCacheWrite5mInputTokens===void 0?{}:{cacheWrite5m:n.totalCacheWrite5mInputTokens},...n.totalCacheWrite1hInputTokens===void 0?{}:{cacheWrite1h:n.totalCacheWrite1hInputTokens}}:{}},_);if(N===null&&E>0&&_!==null&&_.input_cache_read_per_1m_tokens==null&&(b="no applicable cache-read price rate"),n.responses)if(N=null,!n.responses.length||n.captureStatus==="partial"||new Set(n.responses.map(A=>A.response_id)).size!==n.responses.length)b="session accounting coverage is incomplete";else if(!c.catalog)b="lmprice catalog unavailable";else{let A=0,w=null;for(let T of n.responses){let k=T.tokens;if(!T.model){w="a response lacks a model";break}let I=n.turns?.flatMap(Ve=>Ve.rawUsage??[]).find(Ve=>Ve.responseId===T.response_id)?.values,C=I?.promptTokens??I?.prompt_tokens,M=I?.input_tokens,D=I?.cache_read_tokens??I?.input_cache_read_tokens,j=I?.cache_write_tokens??I?.input_cache_write_tokens;if(typeof M=="number"&&typeof D=="number"&&D>M||typeof C=="number"&&typeof D=="number"&&D>C||typeof C=="number"&&typeof j=="number"&&j>C||typeof C=="number"&&typeof D=="number"&&typeof j=="number"&&D+j>C){w=`${t} reported contradictory token counters`;break}if(k.output===null){w=`${t} does not record output tokens`;break}if(k.input_cached===null){w=`${t} does not record cached input tokens`;break}let F=T.model_provider??t,Z=Iy(T.model??""),q=(F==="deepseek"||T.model_provider==="deepseek")&&(T.model_provider===void 0||T.model_provider==="deepseek")&&G2.has(Z),Y=k.input_cache_write;if(Y===null&&!q){w=`${t} does not record cache-write input tokens`;break}if(t==="agy"&&(Y??0)>0){w="cache-write inclusion in input is not verified";break}let ne=["kimi","opencode","miniplayer"].includes(t),me=Ei(F,T.model,c.catalog,c.aliases),ee=me.offer??Ei(t,T.model,c.catalog,c.aliases).offer;if(ee===null){switch(me.state.kind){case"no-catalog":w=`no lmprice catalog coverage for provider "${t}"`;break;case"unresolved":w=`alias "${me.state.alias}" is deliberately unresolved in the lmprice alias table`;break;case"known-unpriced":w=`"${me.state.id}" is a known model with no published price row`;break;case"unknown":w=`model "${T.model}" not found in lmprice catalog for provider "${t}"`;break;case"wrong-provider":w=`model "${T.model}" is not offered by provider "${t}" (found under: ${me.state.otherProviders.join(", ")})`;break;default:w=`no applicable price for response model "${T.model}"`;break}break}if(Y===null){let Ve=(ee.route??"").toLowerCase(),B=/^(openrouter|ollama|together|fireworks|groq|azure|bedrock|vertex)[:\/]/i.test(Ve),W=Iy(ee.sourceModelId??""),V=ee.provider==="deepseek"&&ee.source!=="openrouter"&&!B&&W===Z;if(q&&V)Y=0;else{w=`${t} does not record cache-write input tokens`;break}}if(k.input_uncached===null){w=`${t} does not record uncached input tokens`;break}let st=ea({input:Math.max(0,k.input_uncached-(ne?Y:0)),cachedInput:k.input_cached,cacheWrite:Y,output:k.output},ee?.pricing??null);if(st===null){w=`no applicable price for response model "${T.model}"`;break}A+=st,!p&&ee&&(p=ee.route,m="priced")}N=w?null:A,b=w}return N===null&&(!n.responses&&l.input===null&&l.output===null?b=`${t} does not record token usage`:!n.responses&&l.input===null&&!b?b=`${t} does not record input tokens`:!n.responses&&l.output===null&&!b?b=`${t} does not record output tokens`:b||(b=`no lmprice entry for "${i??"unknown"}"`),(m==="priced"||m==="estimated")&&(m="unavailable",p=null,f=null,h=null,g=null,v=null)),{schema_version:V2,provider:t,sessionId:e,model:i,modelsUsed:u,approximate:d,tokens:l,pricePerModel:v,costUsd:N,priceResolution:m,priceRoute:p,priceSource:f,priceSourceModelId:h,priceProvenance:g,priceEstimated:y,costUnavailableReason:b,priceDataSource:c.source,priceDataGeneratedAt:c.generatedAt}}var Sd,G2,V2,SA=L(()=>{"use strict";Uo();Yi();Sd=tm(iu(),1);eu();Cs();Ac();ir();bp();Rn();Yc();G2=new Set([...Kc,...zc,"deepseek-v4.1-flash","deepseek-chat","deepseek-reasoner","deepseek-coder","deepseek-v3","deepseek-v3.2","deepseek-r1"].map(Iy));V2=1});async function kA(t,e,n,r){let s={role:"assistant",content:r,provider:e,sessionid:n,model:null,usage:{input:null,cachedInput:null,cacheWrite:null,output:null},costUsd:null,costUnavailableReason:null,priceRoute:null,priceDataSource:"unavailable"};try{let i=await ts(n,e);if(!i)return{...s,costUnavailableReason:"session not readable after the turn"};let o=i.turns?.at(-1),a=new Set(o?.responseIds??[]),l=(i.responses??[]).filter(m=>a.has(m.response_id));if(!o||!l.length)return{...s,costUnavailableReason:`${e} does not record per-turn accounting`};let c={...i,turns:[o],responses:l,messages:[],model:l.at(-1)?.model??o.model??i.model},u=await TA(e,n,c),d=m=>l.some(p=>p.tokens[m]===null)?null:l.reduce((p,f)=>p+f.tokens[m],0);return{...s,model:u.model,usage:{input:d("input_uncached"),cachedInput:d("input_cached"),cacheWrite:d("input_cache_write"),output:d("output")},costUsd:u.costUsd,costUnavailableReason:u.costUnavailableReason,priceRoute:u.priceRoute,priceDataSource:u.priceDataSource}}catch(i){return{...s,costUnavailableReason:`cost unavailable: ${i instanceof Error?i.message:String(i)}`}}}var RA=L(()=>{"use strict";Yi();SA()});import{basename as K2}from"node:path";function AA(t,e){let n=new Date(e.now.getTime()-is()).toISOString(),r=OA(t,n).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=Z2(e.sender,r),i=eX(e.sender,r);i!==null&&i.teamfile===e.root&&!IA(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>IA(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,f)=>f-p)[0]??null,u=c!==null&&e.now.getTime()-c<z2,d=Ay(e.sender,r).length;return{stop:l.length>=1&&u&&d>=Y2,chain:tX(a)}}function CA(t,e){let n=new Date(e.now.getTime()-is()).toISOString(),r=OA(t,n),s=Ay(e.sender,r);if(s.length===0)return null;let i=s[0];return i.sender.teamfile.startsWith("prompt:")?i.receiver.teamfile:i.sender.teamfile}function is(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return xA;let n=Number(e);return!Number.isFinite(n)||n<=0?xA:n}function NA(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function Q2(t){return{sender:{teamfile:t.sender_teamfile,alias:t.sender_alias},receiver:{teamfile:t.receiver_teamfile,alias:t.receiver_alias},at:Date.parse(t.started_at)}}function OA(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(Q2).filter(n=>Number.isFinite(n.at)&&new Date(n.at).toISOString()>=e).sort((n,r)=>n.at-r.at)}function Z2(t,e,n={}){let r=new Map;for(let a of e)r.set(Js(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([Js(t)]);for(let a=0;a<64;a+=1){let l=r.get(Js(i));if(l===void 0)break;s[0]={...s[0],at:s[0].at??l.at};let c={...l.sender,at:l.at};if(l.sender.teamfile.startsWith("prompt:")&&n.includePromptSender!==!0)break;let u=Js(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function Ay(t,e){let n=Js(t),r=new Set([n]),s=[n],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=Js(l.sender),u=Js(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),r.has(c)||(r.add(c),s.push(c)),r.has(u)||(r.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function eX(t,e){let n=Ay(t,e);if(n.length===0)return null;let r=n[0];return r.sender.teamfile.startsWith("prompt:")?r.receiver:r.sender}function IA(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function Js(t){return`${t.teamfile}\0${t.alias}`}function tX(t){return t.map(e=>`${K2(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var z2,Y2,xA,kd=L(()=>{"use strict";z2=6e4,Y2=2,xA=8*60*60*1e3});function Cy(t,e){if(Dc(e)!=="dead")return null;let n=`holder process verified not alive; reconciled to aborted (invocation #${e.id}, holder pid ${e.holder_pid??"unknown"} on ${e.holder_host??"unknown"})`;return t.abortTrackedInvocationAndTerminalizeMessage(e.id,{holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat_at:e.last_heartbeat_at},n)}function Rd(t,e,n){let r=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
2387
|
+
`),A2(d)}finally{C2(d)}n.assertOwned(),N2(u,t.path)}finally{O2(u,{force:!0})}return c}finally{n.release()}}var iA,xy,$2,oA,pA=L(()=>{"use strict";iA="https://api.kimi.com/coding/v1",xy="https://auth.kimi.com",$2="17e5f671-d194-4dfb-9706-5516cb48c098",oA=t=>t.trim().replace(/\/+$/,"")});function fA(t){let e=o=>{if(typeof o!="number"&&typeof o!="string"||typeof o=="string"&&o.trim()==="")return;let a=Number(o);return Number.isFinite(a)&&a>=0?a:void 0},n=e(t.limit),r=e(t.used),s=e(t.remaining);if(n===void 0||n<=0||r===void 0&&(s===void 0||s>n))return;let i=r??n-s;return{used:i,limit:n,remaining:Math.max(0,n-i)}}async function gA({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s;try{s=dA(e)}catch(h){let g=h instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(h.message)?h.message:"credentials_unreadable";return Ue("kimi",g==="credentials_revoked"?"auth_expired":"provider_unavailable",g,g==="credentials_revoked"?"Kimi login was revoked; run kimi login":g.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let h=!1,g=async()=>{i=await mA({...s,token:i},o.signal),h=!0};Ed(i)&&await g();let y=()=>fetch(`${s.baseUrl}/usages`,{headers:{Authorization:`Bearer ${i.access_token}`,Accept:"application/json"},signal:o.signal});l=await y(),c=await l.text(),St({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!h&&i.refresh_token&&(await g(),l=await y(),c=await l.text(),St({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(h){let g=h instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(h.message)?h.message:"request_failed",y=g==="credentials_revoked"||g==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(g),b=g==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":y?`Kimi credential renewal failed (${g}); run kimi login`:`Kimi quota request failed (${g})`;return Ue("kimi",y?"auth_expired":"provider_unavailable",g,b,"kimi_http")}finally{clearTimeout(a)}let u=(h,g,y)=>ss(Ue("kimi",h,g,g,"kimi_http",[],y),c,[i.access_token]);if(l.status===401)return u("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return u("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let h=_d(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",h)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return Ue("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return Ue("kimi","provider_unavailable","malformed_response","response was not an object");let m=[],p=new Set;function f(h){let g=String(h.bucket_id),y=g,b=2;for(;p.has(g);)g=`${y}-${b}`,b++;p.add(g),h.bucket_id=g,m.push(ft(h))}if(Array.isArray(d.limits))for(let h of d.limits){if(!h||typeof h!="object")continue;let g=h.window,y=h.detail;if(!g||typeof g!="object"||!y||typeof y!="object")continue;let b=0;if(g.timeUnit==="TIME_UNIT_MINUTE")b=Number(g.duration);else if(g.timeUnit==="TIME_UNIT_HOUR")b=Number(g.duration)*60;else if(g.timeUnit==="TIME_UNIT_DAY")b=Number(g.duration)*1440;else if(g.timeUnit==="TIME_UNIT_WEEK")b=Number(g.duration)*10080;else if(g.timeUnit==="TIME_UNIT_MONTH")b=Number(g.duration)*43200;else continue;let _=xI(b),v="window";_==="five_hour"&&(v="5h"),_==="weekly"&&(v="weekly"),_==="monthly"&&(v="monthly");let E=fA(y);if(!E)continue;let{used:x,limit:S,remaining:R}=E;f({bucket_id:`kimi-${v}`,window_type:_,used_fraction:Ze(x/S),remaining_fraction:Ze(R/S),resets_at_iso:y.resetTime,raw_value:x,raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let h=fA(d.usage);h&&f({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:Ze(h.used/h.limit),remaining_fraction:Ze(h.remaining/h.limit),resets_at_iso:d.usage.resetTime,raw_value:h.used,raw_scale:"count"})}if(d.usages&&typeof d.usages=="object"){let h=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:g,id:y,type:b}of h){let _=d.usages[g];if(!_||typeof _!="object"||_.used_ratio==null||_.used_ratio===""||typeof _.used_ratio=="boolean")continue;let v=Number(_.used_ratio);!Number.isFinite(v)||v<0||p.has(y)||(p.add(y),m.push(ft({bucket_id:y,window_type:b,used_fraction:Ze(v),resets_at_iso:typeof _.reset_time=="string"&&_.reset_time?_.reset_time:null,raw_value:v,raw_scale:"ratio"})))}}return Je("kimi","ok",{source:"kimi_http",buckets:m})}var hA=L(()=>{"use strict";Pn();pA();Pn()});function za(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Td(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){let e=Number(t);if(Number.isFinite(e))return e}}async function yA(t){let{timeoutSeconds:e,env:n,debug:r,onRawResponse:s,fetchFn:i=fetch}=t,o=n.OLLAMA_API_KEY?.trim();if(!o)return Ue("ollama-cloud","provider_unavailable","credentials_missing","$OLLAMA_API_KEY is missing","ollama_http");let a="https://ollama.com/api/balance",l=new AbortController,c=setTimeout(()=>l.abort(),Math.ceil(e*1e3)),u,d="";try{u=await i(a,{method:"GET",redirect:"error",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:l.signal}),d=await u.text();let g=d;try{g=JSON.stringify(JSON.parse(d))}catch{}St({debug:r,onRawResponse:s},"ollama_http",g,[o],u.status)}catch(g){let y=g instanceof Error&&g.name==="AbortError",b=y?`Ollama quota request timed out after ${e}s`:`Ollama quota request failed (${g instanceof Error?g.message:String(g)})`;return Ue("ollama-cloud","provider_unavailable",y?"request_timeout":"request_failed",b,"ollama_http",[o])}finally{clearTimeout(c)}let m=(g,y,b)=>ss(Ue("ollama-cloud",g,y,y,"ollama_http",[o],b),d,[o]);if(u.status===401)return m("auth_expired","HTTP 401 from Ollama balance endpoint");if(u.status===403)return m("not_applicable","HTTP 403 from Ollama balance endpoint");if(u.status===429){let g=_d(u.headers);return m("reader_throttled","HTTP 429 from Ollama balance endpoint",g)}if(u.status!==200)return m("provider_unavailable",`HTTP ${u.status} from Ollama balance endpoint`);let p;try{p=JSON.parse(d)}catch{return Ue("ollama-cloud","provider_unavailable","malformed_response","SyntaxError: malformed JSON","ollama_http")}if(!za(p))return Ue("ollama-cloud","provider_unavailable","malformed_response","response was not an object","ollama_http");let f=[];if(za(p.included)){let g=p.included,y=Td(g.allowance_usd),b=Td(g.balance_usd),_=za(g.period)?g.period:void 0,v=typeof _?.from=="string"?Date.parse(_.from):NaN,E=typeof _?.until=="string"?Date.parse(_.until):NaN,x=Number.isFinite(v)&&Number.isFinite(E)&&E>v,S=x?new Date(E).toISOString():null;if(y!==void 0&&y>0&&b!==void 0){let R=Math.max(0,y-b);f.push({...ft({bucket_id:"ollama-cloud-monthly",group_name:"ollama-cloud",window_type:"monthly",used_fraction:Ze(R/y),remaining_fraction:Ze(b/y),resets_at_iso:S,is_exhausted:b<=0,raw_value:b,raw_scale:"balance_usd"}),window_start_iso:x?new Date(Math.floor(v/1e3)*1e3).toISOString().replace(".000Z","Z"):null})}if(y===void 0&&b===void 0)for(let[R,N,O]of[["session","five_hour","5h"],["weekly","weekly","weekly"]]){let A=g[R];if(!za(A))continue;let w=Td(A.remaining_percent);w===void 0||w<0||w>100||f.push(ft({bucket_id:`ollama-cloud-${O}`,group_name:"ollama-cloud",window_type:N,remaining_fraction:w/100,resets_at_iso:typeof A.resets_at=="string"?A.resets_at:null,raw_value:w,raw_scale:"remaining_percent"}))}}let h;if(za(p.purchased)){let g=p.purchased,y=Td(g.balance_usd);y!==void 0&&(h={has_credits:y>0,balance:y})}return f.length===0&&h===void 0?Ue("ollama-cloud","provider_unavailable","malformed_response","response has no usable included allowance or purchased balance","ollama_http"):Je("ollama-cloud","ok",{source:"ollama_http",buckets:f,...h?{credits:h}:{}})}var _A=L(()=>{"use strict";Pn()});async function bA(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(d=>typeof d!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let d of e)if(!vA.includes(d))return{status:"error",error:`unknown provider: ${d} (valid targets: ${vA.join(", ")})`,readings:[]};let n=t.timeoutSeconds??B2;if(!Number.isFinite(n)||n<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let r=t.env??process.env,s=["codex","agy","claude","kimi"];(r.OLLAMA_API_KEY?.trim()||e.includes("ollama-cloud"))&&s.push("ollama-cloud");let i=new Set(e.includes("all")?s:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${n}s per provider) ...`);let a=Object.entries({codex:nA,agy:OI,claude:XI,kimi:gA,"ollama-cloud":yA}).filter(([d])=>i.has(d)).map(async([,d])=>{let m=[],p=await d({timeoutSeconds:n,env:r,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:h=>m.push(h)}:{}}),f=t.includeRaw?{...p,raw_responses:m}:p;return f&&t.onReading?.(f),f}),l=await Promise.allSettled(a),c=l.find(d=>d.status==="rejected");return c?{status:"error",error:String(c.reason),readings:[]}:{status:"ok",readings:l.filter(d=>d.status==="fulfilled").map(d=>d.value).filter(Boolean)}}var vA,B2,wA=L(()=>{"use strict";LI();GI();rA();hA();_A();vA=["all","codex","agy","claude","kimi","ollama-cloud"],B2=15});async function H2(t,e={}){try{let n=fe(t);if(n)return n;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Ratelimit options must be a map");let{providers:r,provider:s,timeoutSeconds:i=15}=e,o=r??(s===void 0?["all"]:[s]);if(Object.keys(e).some(l=>!yr("readRatelimits").includes(l))||!Array.isArray(o)||o.some(l=>typeof l!="string"||!l||l.startsWith("-")))return H("invalid_argument","providers must be a list of provider names");if(typeof i!="number"||!Number.isFinite(i)||i<=0)return H("invalid_argument","timeoutSeconds must be a positive finite number");let a=await bA({providers:o.length?[...o]:["all"],timeoutSeconds:i,env:{...t.env},progress:l=>t.onProgress(l+`
|
|
2388
|
+
`,"stderr")});return a.status==="ok"?ge({readings:a.readings}):H("provider",a.error,{readings:[]})}catch(n){return H("provider",V(n),{readings:[]})}}var EA=L(()=>{"use strict";wA();rn();yt()});function Iy(t){return t.trim().toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function J2(t,e,n,r){let s=new Set,i=[];for(let o of e){let a=n===null?null:Ic(t,o,n,r),l=a?.kind==="priced"||a?.kind==="estimated"?`id:${a.model.normalizedId}`:a?.kind==="known-unpriced"?`id:${a.id}`:`raw:${o.trim().toLowerCase()}`;s.has(l)||(s.add(l),i.push(o))}return i}async function TA(t,e,n){let r=[...new Set([...n.messages.map(A=>A.model),...(n.responses??[]).map(A=>A.model??void 0)].filter(A=>A!==void 0&&A!=="<synthetic>"))],s=[...n.messages].reverse().find(A=>A.model!==void 0&&A.model!=="<synthetic>")?.model,i=n.model??s??null,o=Rr(n.responses??[],n.captureStatus!=="partial"),a=t==="gemini"&&(n.totalOutputTokens!==void 0||n.totalReasoningOutputTokens!==void 0)?(n.totalOutputTokens??0)+(n.totalReasoningOutputTokens??0):n.totalOutputTokens??null,l={input:n.responses?o.input_uncached:n.totalInputTokens??null,output:n.responses?o.output:a,cachedInput:n.responses?o.input_cached:n.totalCachedInputTokens??null},c=await As(),u=J2(t,r,c.catalog,c.aliases),d=n.responses===void 0&&u.length>1,m="unavailable",p=null,f=null,h=null,g=null,y=!1,b=null,_=null;if(i!==null&&c.catalog!==null){let A=Ei(t,i,c.catalog,c.aliases);if(m=A.state.kind,A.offer!==null)_=A.offer.pricing,p=A.offer.route,f=A.offer.source,h=A.offer.sourceModelId,g=A.provenance,y=A.offer.estimated;else switch(A.state.kind){case"unresolved":b=`alias "${A.state.alias}" is deliberately unresolved in the lmprice alias table`;break;case"known-unpriced":b=`"${A.state.id}" is a known model with no published price row`;break;case"unknown":b=`model "${i}" not found in lmprice catalog for provider "${t}"`;break;case"wrong-provider":b=`model "${i}" is not offered by provider "${t}" (found under: ${A.state.otherProviders.join(", ")})`;break;default:b=`no lmprice catalog coverage for provider "${t}"`;break}}else i!==null&&(b="lmprice catalog unavailable");let v=_===null?null:{inputPer1m:_.input_per_1m_tokens,outputPer1m:_.output_per_1m_tokens,cachedInputPer1m:_.input_cache_read_per_1m_tokens},E=l.cachedInput??0,x=n.totalCacheWriteInputTokens??0,S=["claude","codex","gemini","qwen","copilot"].includes(t),R=l.input===null?null:Math.max(0,l.input-(S?E:0)-(t==="claude"||t==="copilot"?x:0)),N=l.input===null||l.output===null?null:ea({input:R,output:l.output,cachedInput:E,...x>0?{cacheWrite:x,...n.totalCacheWrite5mInputTokens===void 0?{}:{cacheWrite5m:n.totalCacheWrite5mInputTokens},...n.totalCacheWrite1hInputTokens===void 0?{}:{cacheWrite1h:n.totalCacheWrite1hInputTokens}}:{}},_);if(N===null&&E>0&&_!==null&&_.input_cache_read_per_1m_tokens==null&&(b="no applicable cache-read price rate"),n.responses)if(N=null,!n.responses.length||n.captureStatus==="partial"||new Set(n.responses.map(A=>A.response_id)).size!==n.responses.length)b="session accounting coverage is incomplete";else if(!c.catalog)b="lmprice catalog unavailable";else{let A=0,w=null;for(let T of n.responses){let k=T.tokens;if(!T.model){w="a response lacks a model";break}let I=n.turns?.flatMap(Ve=>Ve.rawUsage??[]).find(Ve=>Ve.responseId===T.response_id)?.values,C=I?.promptTokens??I?.prompt_tokens,M=I?.input_tokens,D=I?.cache_read_tokens??I?.input_cache_read_tokens,j=I?.cache_write_tokens??I?.input_cache_write_tokens;if(typeof M=="number"&&typeof D=="number"&&D>M||typeof C=="number"&&typeof D=="number"&&D>C||typeof C=="number"&&typeof j=="number"&&j>C||typeof C=="number"&&typeof D=="number"&&typeof j=="number"&&D+j>C){w=`${t} reported contradictory token counters`;break}if(k.output===null){w=`${t} does not record output tokens`;break}if(k.input_cached===null){w=`${t} does not record cached input tokens`;break}let $=T.model_provider??t,Z=Iy(T.model??""),q=($==="deepseek"||T.model_provider==="deepseek")&&(T.model_provider===void 0||T.model_provider==="deepseek")&&G2.has(Z),Y=k.input_cache_write;if(Y===null&&!q){w=`${t} does not record cache-write input tokens`;break}if(t==="agy"&&(Y??0)>0){w="cache-write inclusion in input is not verified";break}let ne=["kimi","opencode","miniplayer"].includes(t),me=Ei($,T.model,c.catalog,c.aliases),ee=me.offer??Ei(t,T.model,c.catalog,c.aliases).offer;if(ee===null){switch(me.state.kind){case"no-catalog":w=`no lmprice catalog coverage for provider "${t}"`;break;case"unresolved":w=`alias "${me.state.alias}" is deliberately unresolved in the lmprice alias table`;break;case"known-unpriced":w=`"${me.state.id}" is a known model with no published price row`;break;case"unknown":w=`model "${T.model}" not found in lmprice catalog for provider "${t}"`;break;case"wrong-provider":w=`model "${T.model}" is not offered by provider "${t}" (found under: ${me.state.otherProviders.join(", ")})`;break;default:w=`no applicable price for response model "${T.model}"`;break}break}if(Y===null){let Ve=(ee.route??"").toLowerCase(),B=/^(openrouter|ollama|together|fireworks|groq|azure|bedrock|vertex)[:\/]/i.test(Ve),W=Iy(ee.sourceModelId??""),J=ee.provider==="deepseek"&&ee.source!=="openrouter"&&!B&&W===Z;if(q&&J)Y=0;else{w=`${t} does not record cache-write input tokens`;break}}if(k.input_uncached===null){w=`${t} does not record uncached input tokens`;break}let st=ea({input:Math.max(0,k.input_uncached-(ne?Y:0)),cachedInput:k.input_cached,cacheWrite:Y,output:k.output},ee?.pricing??null);if(st===null){w=`no applicable price for response model "${T.model}"`;break}A+=st,!p&&ee&&(p=ee.route,m="priced")}N=w?null:A,b=w}return N===null&&(!n.responses&&l.input===null&&l.output===null?b=`${t} does not record token usage`:!n.responses&&l.input===null&&!b?b=`${t} does not record input tokens`:!n.responses&&l.output===null&&!b?b=`${t} does not record output tokens`:b||(b=`no lmprice entry for "${i??"unknown"}"`),(m==="priced"||m==="estimated")&&(m="unavailable",p=null,f=null,h=null,g=null,v=null)),{schema_version:V2,provider:t,sessionId:e,model:i,modelsUsed:u,approximate:d,tokens:l,pricePerModel:v,costUsd:N,priceResolution:m,priceRoute:p,priceSource:f,priceSourceModelId:h,priceProvenance:g,priceEstimated:y,costUnavailableReason:b,priceDataSource:c.source,priceDataGeneratedAt:c.generatedAt}}var Sd,G2,V2,SA=L(()=>{"use strict";Uo();Yi();Sd=tm(iu(),1);eu();Cs();Ac();ir();bp();Rn();Yc();G2=new Set([...Kc,...zc,"deepseek-v4.1-flash","deepseek-chat","deepseek-reasoner","deepseek-coder","deepseek-v3","deepseek-v3.2","deepseek-r1"].map(Iy));V2=1});async function kA(t,e,n,r){let s={role:"assistant",content:r,provider:e,sessionid:n,model:null,usage:{input:null,cachedInput:null,cacheWrite:null,output:null},costUsd:null,costUnavailableReason:null,priceRoute:null,priceDataSource:"unavailable"};try{let i=await ts(n,e);if(!i)return{...s,costUnavailableReason:"session not readable after the turn"};let o=i.turns?.at(-1),a=new Set(o?.responseIds??[]),l=(i.responses??[]).filter(m=>a.has(m.response_id));if(!o||!l.length)return{...s,costUnavailableReason:`${e} does not record per-turn accounting`};let c={...i,turns:[o],responses:l,messages:[],model:l.at(-1)?.model??o.model??i.model},u=await TA(e,n,c),d=m=>l.some(p=>p.tokens[m]===null)?null:l.reduce((p,f)=>p+f.tokens[m],0);return{...s,model:u.model,usage:{input:d("input_uncached"),cachedInput:d("input_cached"),cacheWrite:d("input_cache_write"),output:d("output")},costUsd:u.costUsd,costUnavailableReason:u.costUnavailableReason,priceRoute:u.priceRoute,priceDataSource:u.priceDataSource}}catch(i){return{...s,costUnavailableReason:`cost unavailable: ${i instanceof Error?i.message:String(i)}`}}}var RA=L(()=>{"use strict";Yi();SA()});import{basename as K2}from"node:path";function AA(t,e){let n=new Date(e.now.getTime()-is()).toISOString(),r=OA(t,n).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=Z2(e.sender,r),i=eX(e.sender,r);i!==null&&i.teamfile===e.root&&!IA(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>IA(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,f)=>f-p)[0]??null,u=c!==null&&e.now.getTime()-c<z2,d=Ay(e.sender,r).length;return{stop:l.length>=1&&u&&d>=Y2,chain:tX(a)}}function CA(t,e){let n=new Date(e.now.getTime()-is()).toISOString(),r=OA(t,n),s=Ay(e.sender,r);if(s.length===0)return null;let i=s[0];return i.sender.teamfile.startsWith("prompt:")?i.receiver.teamfile:i.sender.teamfile}function is(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return xA;let n=Number(e);return!Number.isFinite(n)||n<=0?xA:n}function NA(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function Q2(t){return{sender:{teamfile:t.sender_teamfile,alias:t.sender_alias},receiver:{teamfile:t.receiver_teamfile,alias:t.receiver_alias},at:Date.parse(t.started_at)}}function OA(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(Q2).filter(n=>Number.isFinite(n.at)&&new Date(n.at).toISOString()>=e).sort((n,r)=>n.at-r.at)}function Z2(t,e,n={}){let r=new Map;for(let a of e)r.set(Js(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([Js(t)]);for(let a=0;a<64;a+=1){let l=r.get(Js(i));if(l===void 0)break;s[0]={...s[0],at:s[0].at??l.at};let c={...l.sender,at:l.at};if(l.sender.teamfile.startsWith("prompt:")&&n.includePromptSender!==!0)break;let u=Js(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function Ay(t,e){let n=Js(t),r=new Set([n]),s=[n],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=Js(l.sender),u=Js(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),r.has(c)||(r.add(c),s.push(c)),r.has(u)||(r.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function eX(t,e){let n=Ay(t,e);if(n.length===0)return null;let r=n[0];return r.sender.teamfile.startsWith("prompt:")?r.receiver:r.sender}function IA(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function Js(t){return`${t.teamfile}\0${t.alias}`}function tX(t){return t.map(e=>`${K2(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var z2,Y2,xA,kd=L(()=>{"use strict";z2=6e4,Y2=2,xA=8*60*60*1e3});function Cy(t,e){if(Dc(e)!=="dead")return null;let n=`holder process verified not alive; reconciled to aborted (invocation #${e.id}, holder pid ${e.holder_pid??"unknown"} on ${e.holder_host??"unknown"})`;return t.abortTrackedInvocationAndTerminalizeMessage(e.id,{holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat_at:e.last_heartbeat_at},n)}function Rd(t,e,n){let r=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
2388
2389
|
FROM tracked_invocation
|
|
2389
2390
|
WHERE target_teamfile = ?
|
|
2390
2391
|
AND target_alias = ?
|
|
@@ -2398,39 +2399,39 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
2398
2399
|
`),null}}async function XA(t,e,n){let r=Za(n.message),s=n.response===null?null:Za(n.response);try{await ye(t,i=>i.finishTeamChatLog(e,{usage:n.usage,root_teamfile:n.root_teamfile,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,receiver_provider:n.receiver_provider,receiver_session_id:n.receiver_session_id,provider_prompt:n.message,message:r.text,response:s?.text??null,origin:n.origin,status:n.status,error_detail:n.error_detail,truncated:r.truncated||s?.truncated?1:0,created_at:new Date().toISOString()}))}catch(i){t.stderr.write(`warning: failed to finish chat log ${e}: ${i instanceof Error?i.message:String(i)}
|
|
2399
2400
|
`)}}async function MX(t,e,n){if(e!==null)try{await ye(t,r=>{r.clearCurrentlyHandlingMessage(e.receiver_teamfile,e.receiver_alias,n)})}catch(r){t.stderr.write(`warning: failed to clear chat causal pointer: ${r instanceof Error?r.message:String(r)}
|
|
2400
2401
|
`)}}async function GA(t,e){let n=Za(e.message),r=e.response===null?null:Za(e.response);try{return await ye(t,s=>s.insertTeamChatLog({usage:e.usage,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:n.text,response:r?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:n.truncated||r?.truncated?1:0,message_type:e.message_type??null,created_at:e.started_at??new Date().toISOString()}))}catch(s){return t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
2401
|
-
`),null}}function Ks(t,e,n,r,s){t!==null||e===null||X({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:r,message_preview:Nd(n)})}function Za(t){return t.length<=WA?{text:t,truncated:!1}:{text:t.slice(0,WA),truncated:!0}}var WA,JA,Od=L(()=>{"use strict";ra();Yf();dn();Zt();Rn();kn();fd();$s();kd();Re();ir();tr();xd();PA();FA();Ya();My();Py();Fy();jc();WA=256*1024,JA=3e4});function Md(t,e){let n=!1,r=()=>{if(n)return;n=!0;let s=Ld.get(t);s||(s={pending:0,timeout:t.db.pragma("busy_timeout",{simple:!0})},Ld.set(t,s)),s.pending++,t.db.pragma("busy_timeout=0")};return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),()=>{if(e.removeEventListener("abort",r),!n)return;let s=Ld.get(t);if(--s.pending===0){Ld.delete(t);try{t.db.pragma("busy_timeout="+s.timeout)}catch{}}}}var Ld,jy=L(()=>{"use strict";Ld=new WeakMap});import{resolve as PX}from"node:path";async function YA(t,e){let n=(d,m)=>({status:"error",error:d,code:m,reply:"",messageId:null,teamChatLogId:null}),r="invalid_argument",s,i,o=()=>{},a=()=>{},l,c,u=()=>{if(c)throw c;if(!l||!i)return;let d=l,m=i.db.pragma("busy_timeout",{simple:!0});try{if(i.db.pragma("busy_timeout=0"),!i.releaseAgentInflight(d.row,d.leaseId)){let p=i.getAgentInflight(d.row.receiver_teamfile,d.row.receiver_alias);if(p&&p.active_count>0)throw Error("Prompt lease release was not acknowledged")}l=void 0}catch(p){throw c=p instanceof Error?p:Error(
|
|
2402
|
-
`):t.rootFinish.error),result_summary:t.completed+"/"+t.request.promptCount+" prompts completed"},!0)}catch(c){a.push(
|
|
2403
|
-
`));t.untrack()})().then(r,s),t.closing}function sC(t,e,n=!0){t.closed=!0,t.terminal=!0;let r=[];try{By(t,!0)}catch(s){r.push(
|
|
2404
|
-
`),Error(t.criticalFailure);t.untrack()}function iC(t,e){try{let n=Fd(t,e);return n?(sC(n,"SIGTERM",!1),ge({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(n){return H("provider",
|
|
2402
|
+
`),null}}function Ks(t,e,n,r,s){t!==null||e===null||X({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:r,message_preview:Nd(n)})}function Za(t){return t.length<=WA?{text:t,truncated:!1}:{text:t.slice(0,WA),truncated:!0}}var WA,JA,Od=L(()=>{"use strict";ra();Yf();dn();Zt();Rn();kn();fd();$s();kd();Re();ir();tr();xd();PA();FA();Ya();My();Py();Fy();jc();WA=256*1024,JA=3e4});function Md(t,e){let n=!1,r=()=>{if(n)return;n=!0;let s=Ld.get(t);s||(s={pending:0,timeout:t.db.pragma("busy_timeout",{simple:!0})},Ld.set(t,s)),s.pending++,t.db.pragma("busy_timeout=0")};return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),()=>{if(e.removeEventListener("abort",r),!n)return;let s=Ld.get(t);if(--s.pending===0){Ld.delete(t);try{t.db.pragma("busy_timeout="+s.timeout)}catch{}}}}var Ld,jy=L(()=>{"use strict";Ld=new WeakMap});import{resolve as PX}from"node:path";async function YA(t,e){let n=(d,m)=>({status:"error",error:d,code:m,reply:"",messageId:null,teamChatLogId:null}),r="invalid_argument",s,i,o=()=>{},a=()=>{},l,c,u=()=>{if(c)throw c;if(!l||!i)return;let d=l,m=i.db.pragma("busy_timeout",{simple:!0});try{if(i.db.pragma("busy_timeout=0"),!i.releaseAgentInflight(d.row,d.leaseId)){let p=i.getAgentInflight(d.row.receiver_teamfile,d.row.receiver_alias);if(p&&p.active_count>0)throw Error("Prompt lease release was not acknowledged")}l=void 0}catch(p){throw c=p instanceof Error?p:Error(V(p)),c}finally{i.db.pragma("busy_timeout="+m)}};try{let d=fe(t);if(d)return n(d.error,d.code);if(s=t.dal,!e||typeof e!="object"||Array.isArray(e))return n("promptMember: request must be a map","invalid_argument");let m={...e},p=ht.find(y=>y.name==="promptMember").params.find(y=>y.name==="request").keys;if(Object.keys(m).some(y=>!p.some(b=>b.name===y)))return n("promptMember: unknown request key","invalid_argument");if(typeof m.teamfile!="string"||typeof m.alias!="string"||typeof m.prompt!="string")return n("promptMember: teamfile, alias and prompt must be strings","invalid_argument");let f=m.permissionMode??"yolo";if(f!=="yolo"&&f!=="plan")return n("promptMember: permissionMode must be yolo or plan","invalid_argument");if(m.idleTimeoutMs!=null&&(typeof m.idleTimeoutMs!="number"||!Number.isFinite(m.idleTimeoutMs)||m.idleTimeoutMs<0))return n("promptMember: idleTimeoutMs must be finite and nonnegative","invalid_argument");if(m.messageType!==void 0&&typeof m.messageType!="string")return n("promptMember: messageType must be a string","invalid_argument");r="provider";let h=mt(t);Object.defineProperty(h,"dal",{enumerable:!0,get(){return i||(i=s??ut({path:t.dbPath}),o=Md(i,t.signal)),i}}),a=En(t,{async close(){u()},finalizeSync(){u()}});let g=await ro({signal:t.signal,onInflightAcquired:y=>{l=y,t.closed&&u()},onInflightReleased:y=>{l?.leaseId===y&&(l=void 0)},teamfile:PX(t.cwd,m.teamfile),alias:m.alias,prompt:m.prompt,permissionMode:f,idleTimeoutMs:m.idleTimeoutMs,messageType:m.messageType,env:h.env,io:h});return u(),{status:g.status,reply:"replyText"in g?g.replyText:"",error:"message"in g?g.message:null,messageId:"messageId"in g?g.messageId:null,teamChatLogId:g.teamChatLogId}}catch(d){return n(V(d),r)}finally{try{u()}catch{}o(),c||(a(),s||i?.close())}}var QA=L(()=>{"use strict";Od();rn();en();Zt();jy();zn();yt()});import{performance as ZA}from"node:perf_hooks";import{randomUUID as DX}from"node:crypto";import{resolve as FX,join as $X}from"node:path";function Uy(t){let e=eC.get(t);if(e)return e;let n,r,s=new Promise((i,o)=>{n=i,r=o});eC.set(t,s);try{Promise.resolve(t.close()).then(n,r)}catch(i){r(i)}return s}function Pd(t){let e=new Date(t.clock());return[e.getHours(),e.getMinutes(),e.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}function nC(t,e){let n=mt(t),r=t.clock(),s=r,i=setInterval(()=>{try{t.clock()-s>=5e3&&n.stderr.write(e(Math.round((t.clock()-r)/1e3)))}catch{}},5e3);return i.unref(),{poke(){s=t.clock()},stop(){clearInterval(i)}}}async function jX(t,e){let n=e.provider.trim().toLowerCase(),r=Kr(t.env.HOME?$X(t.env.HOME,".lmctl/config.toml"):void 0);return bu(n,r,ud())}function UX(t,e){let n=Ad(t,e);if(n.ok)return Cd(n.identity);if(n.reason==="unset")return null;throw Error(Id("batch",t,e))}function rC(t,e,n=!1){let r=un(t.ctx),s=n?r.db.pragma("busy_timeout",{simple:!0}):void 0;n&&r.db.pragma("busy_timeout=0");try{e(r)}finally{n&&r.db.pragma("busy_timeout="+s)}}function Dd(t,e,n=!1){t.rootId===null||t.rootFinished||(rC(t,r=>{if(!r.finishTrackedInvocation(t.rootId,e)){let i=r.getTrackedInvocation(t.rootId);if(!i||i.status==="running")throw Error("Batch invocation could not be finalized")}},n),t.rootFinished=!0)}function By(t,e=!1){t.timer?.stop(),t.timer=void 0;for(let n of["lease","turnLease"]){let r=t[n];r&&(rC(t,s=>{if(!s.releaseAgentInflight(r.row,r.leaseId))throw Error("Batch lease release refused: ownership changed")},e),t[n]=void 0)}}async function el(t,e,n){if(t.closing)return t.closing;let r,s;t.closing=new Promise((a,l)=>{r=a,s=l});let i=ZA.now();t.closed=!0,t.controller.abort();let o=async a=>{let l,c=5e3-(ZA.now()-i);if(c<=0)throw Error("Batch cleanup exceeded its 5 second total deadline");try{await Promise.race([a,new Promise((u,d)=>{l=setTimeout(()=>d(Error("Batch cleanup exceeded its 5 second total deadline")),c)})])}finally{clearTimeout(l)}};return(async()=>{let a=[];try{t.bundle&&await o(Uy(t.bundle))}catch(l){a.push(V(l))}finally{t.bundle=void 0}if(t.turnDone)try{await o(t.turnDone)}catch(l){a.push(V(l))}if(!t.terminal){try{By(t,!0)}catch(c){a.push(V(c))}let l=(t.failed||a.length)&&e==="done"?"error":e;try{Dd(t,{...t.rootFinish,status:l,exit_code:l==="done"?0:1,error:l==="done"?void 0:n??t.failed??(a.length?a.join(`
|
|
2403
|
+
`):t.rootFinish.error),result_summary:t.completed+"/"+t.request.promptCount+" prompts completed"},!0)}catch(c){a.push(V(c))}}if(t.criticalFailure&&a.push(t.criticalFailure),a.length)throw Error(a.join(`
|
|
2404
|
+
`));t.untrack()})().then(r,s),t.closing}function sC(t,e,n=!0){t.closed=!0,t.terminal=!0;let r=[];try{By(t,!0)}catch(s){r.push(V(s))}try{Dd(t,{status:n?"cancelled":"error",...n?{signal:e}:{},error:n?"batch interrupted by "+e:"batch cleanup deadline exceeded",result_summary:t.completed+"/"+t.request.promptCount+" prompts completed"},!0)}catch(s){r.push(V(s))}if(t.controller.abort(e),t.bundle&&Uy(t.bundle).catch(()=>{}),t.bundle=void 0,r.length)throw t.criticalFailure=r.join(`
|
|
2405
|
+
`),Error(t.criticalFailure);t.untrack()}function iC(t,e){try{let n=Fd(t,e);return n?(sC(n,"SIGTERM",!1),ge({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(n){return H("provider",V(n))}}function Fd(t,e){if(!e||typeof e!="object")return;let n=tC.get(e);return n?.ctx===t?n:void 0}function oC(t,e){let n=Fd(t,e);return!n||!n.member?H("invalid_argument","Invalid or unmanaged batch handle"):ge({id:n.ref.id,teamfile:n.request.teamfile,alias:n.request.alias,batchfile:n.request.label,member:{...n.member},promptCount:n.request.promptCount,useBundle:!!n.bundleActive,rootId:n.rootId,rootFinish:{...n.rootFinish},closed:n.closed,env:{...n.env}})}async function aC(t,e){let n;try{let r=fe(t);if(r)return r;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Batch request must be a map");let s={...e};if(typeof s.teamfile!="string"||typeof s.alias!="string"||typeof s.label!="string"||!Number.isFinite(s.promptCount)||s.promptCount<0)return H("invalid_argument","Batch requires teamfile, alias, label and nonnegative promptCount");if(s.permissionMode!==void 0&&s.permissionMode!=="yolo"&&s.permissionMode!=="plan")return H("invalid_argument","permissionMode must be yolo or plan");if(s.idleTimeoutMs!==void 0&&(!Number.isFinite(s.idleTimeoutMs)||s.idleTimeoutMs<0))return H("invalid_argument","idleTimeoutMs must be nonnegative");let i;try{i=Lt(FX(t.cwd,s.teamfile),s.alias,t.dal)}catch(m){let p;try{p=m instanceof Le?m.kind:void 0}catch{}return H(p??hr(m),V(m))}let o=Object.freeze({id:`batch-${t.clock()}-${DX().slice(0,6)}`});n={ctx:t,controller:new AbortController,ref:o,request:s,rootId:null,completed:0,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},closed:!1,inFlight:!1,env:{...t.env,LMCTL_DB:t.dbPath},untrack(){}};let a=n;tC.set(o,a),a.untrack=En(t,{close:()=>el(a,"error","script execution interrupted or terminated without orderly close"),finalizeSync:m=>sC(a,m)}),a.member=i;let l=un(t),c=mt(t),u=a.member,d=!s.legacy&&s.promptCount>1&&await jX(t,u);if(t.closed)throw Error("Context is closed");try{a.rootId=l.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:u.teamfile,from_identity:`${u.teamfile}:batch`,target_teamfile:u.teamfile,target_alias:u.alias,root_teamfile:u.teamfile,cwd:u.sessiondir,command:`lmctl batch ${u.teamfile} ${u.alias} ${s.label}`,holder_pid:t.pid??null,launch_source:"exec",parent_invocation_id:a.env.LMCTL_INVOCATION_ID?Number(a.env.LMCTL_INVOCATION_ID):null,meta:JSON.stringify({batchfile:s.label,prompt_count:s.promptCount,provider:u.provider,sessionid:u.sessionid,...u.model!==void 0?{model:u.model}:{}})}).id}catch(m){c.stderr.write(`warning: failed to start batch root invocation: ${V(m)}
|
|
2405
2406
|
`)}if(a.rootId!==null&&(a.env.LMCTL_INVOCATION_ID=String(a.rootId)),c.stderr.write(`batch ${Pd(t)}: starting ${s.promptCount} prompt${s.promptCount===1?"":"s"} -> ${u.alias} (teamfile=${s.teamfile} input=${s.label})
|
|
2406
2407
|
`),d){Rd(l,u.teamfile,u.alias);let m=Ri(l,u.teamfile,u.alias);if(m.busy){let b=m.reason==="in-flight"?`${u.alias} is servicing ${m.inFlight.sender_alias} (${m.inFlight.sender_teamfile}) since ${m.inFlight.started_at} \u2014 wait and retry`:m.source==="terminal-lock"?Vs(m.terminalLock):`${u.alias} is busy (interactive terminal); wait and retry`;return Dd(a,{status:"busy",exit_code:1,error:b,result_summary:"0 prompts completed"}),await el(a,"error"),{status:"busy",error:`cannot start bundle: ${b}`}}let p=UX(a.env,l),f=$r(l,{receiver_teamfile:u.teamfile,receiver_alias:u.alias,sender_teamfile:p?.teamfile??u.teamfile,sender_alias:p?.alias??"operator",ttlMs:is(a.env)});if(!f.acquired){let b=`${u.alias} is servicing ${f.current.sender_alias} (${f.current.sender_teamfile}) since ${f.current.started_at} \u2014 wait and retry`;return Dd(a,{status:"busy",exit_code:1,error:b,result_summary:"0 prompts completed"}),await el(a,"error"),{status:"busy",error:`cannot start bundle: ${b}`}}a.lease={row:f.lease,leaseId:f.leaseId};let h=a.lease,g=ki(b=>l.heartbeatAgentInflight(h.row,h.leaseId,b),{intervalMs:Pc(a.env)});a.timer={stop:()=>clearInterval(g)};let y=nC(t,b=>`batch ${Pd(t)}: opening provider session (${b}s elapsed)
|
|
2407
|
-
`);try{let b={...a.env},_=l.getRootTeam(u.teamfile)?.name;_&&(b.LMBEE_TEAM_NAME=_);let v=ey({provider:u.provider,sessionId:u.sessionid,cwd:u.sessiondir,env:b,model:u.model,effort:u.effort,alias:u.alias,isLead:u.isLead,permissionMode:s.permissionMode??"yolo",holdOpen:Dy(c,{teamfile:u.teamfile,alias:u.alias},b)});v.then(S=>{a.closed&&Uy(S).catch(()=>{})}).catch(()=>{});let E,x=new Promise((S,R)=>{E=()=>R(Error("Context is closed")),t.signal.addEventListener("abort",E,{once:!0}),t.signal.aborted&&E()});try{a.bundle=await Promise.race([v,x])}finally{t.signal.removeEventListener("abort",E)}}catch(b){if(t.closed)throw b;X({event:"persistent_session_open_failed",provider:u.provider,session_id:u.sessionid,error_message:
|
|
2408
|
+
`);try{let b={...a.env},_=l.getRootTeam(u.teamfile)?.name;_&&(b.LMBEE_TEAM_NAME=_);let v=ey({provider:u.provider,sessionId:u.sessionid,cwd:u.sessiondir,env:b,model:u.model,effort:u.effort,alias:u.alias,isLead:u.isLead,permissionMode:s.permissionMode??"yolo",holdOpen:Dy(c,{teamfile:u.teamfile,alias:u.alias},b)});v.then(S=>{a.closed&&Uy(S).catch(()=>{})}).catch(()=>{});let E,x=new Promise((S,R)=>{E=()=>R(Error("Context is closed")),t.signal.addEventListener("abort",E,{once:!0}),t.signal.aborted&&E()});try{a.bundle=await Promise.race([v,x])}finally{t.signal.removeEventListener("abort",E)}}catch(b){if(t.closed)throw b;X({event:"persistent_session_open_failed",provider:u.provider,session_id:u.sessionid,error_message:V(b)}),By(a)}finally{y.stop()}}if(t.closed)throw Error("Context is closed");return a.bundleActive=a.bundle!==void 0,ge({batch:o})}catch(r){if(n){n.rootFinish={...n.rootFinish,result_summary:"0 prompts completed"};try{await el(n,"error",V(r))}catch{}}return H(t?.closed?"cancelled":"provider",V(r))}}async function lC(t,e,n,r,s){let i=(m,p="invalid_argument")=>({status:"error",error:m,code:p,reply:"",messageId:null,teamChatLogId:null}),o=fe(t);if(o)return i(o.error,o.code);let a=Fd(t,e);if(!a||a.closed||!a.member)return i("Invalid or closed batch handle");if(typeof n!="string"||!Number.isFinite(r)||!Number.isFinite(s))return i("prompt, index and total must be valid");if(a.inFlight)return{status:"busy",error:"Batch already has an active turn",reply:"",messageId:null,teamChatLogId:null};a.inFlight=!0,a.turnDone=new Promise(m=>{a.turnFinished=m});let l=t.dal,c,u=()=>{},d;try{c=l??ut({path:t.dbPath});let m={...mt(t),dal:c},p=AbortSignal.any([t.signal,a.controller.signal]);u=Md(c,p),m.stderr.write(`batch ${Pd(t)}: prompt ${r}/${s} -> ${a.member.alias}
|
|
2408
2409
|
`),d=nC(t,g=>`batch ${Pd(t)}: prompt ${r}/${s} still running (${g}s elapsed)
|
|
2409
2410
|
`);let f=await ro({signal:p,onInflightAcquired:g=>{a.turnLease=g},onInflightReleased:g=>{a.turnLease?.leaseId===g&&(a.turnLease=void 0)},teamfile:a.member.teamfile,alias:a.member.alias,prompt:n,expectedSession:{provider:a.member.provider,sessionid:a.member.sessionid},permissionMode:a.request.permissionMode??"yolo",idleTimeoutMs:a.request.idleTimeoutMs,env:{...a.env},messageType:"batch",heldLease:a.lease,bundleSession:a.bundle,io:m,onEvent:g=>{d?.poke(),g.kind==="warning"&&m.stderr.write(g.message)}}),h="replyText"in f?f.replyText.replace(/\n+$/u,""):"";if(f.status!=="ok"){let g=f.status==="stalled"?"provider stalled":f.status==="empty"?"provider returned no content and no observed activity for this turn":f.message,y=`batch: stopped at prompt ${r}/${s} (${r-1} completed): ${g}; later prompts were not sent`;return a.failed=y,a.rootFinish={status:f.status==="busy"?"busy":"error",exit_code:1,error:y,result_summary:`${r-1}/${s} prompts completed`},m.stderr.write(`error: ${y}
|
|
2410
|
-
`),{status:f.status,error:y,reply:h,messageId:"messageId"in f?f.messageId:null,teamChatLogId:f.teamChatLogId}}return a.completed++,{status:"ok",error:null,reply:h,messageId:f.messageId,teamChatLogId:f.teamChatLogId}}catch(m){let p=`batch: stopped at prompt ${r}/${s} (${r-1} completed): ${
|
|
2411
|
-
`)}catch{}return i(p,"provider")}finally{d?.stop(),a.inFlight=!1,a.turnFinished?.(),a.turnDone=void 0,u(),l||c?.close()}}async function cC(t,e,n){try{let r=Fd(t,e);return r?!n||!["done","error","cancelled"].includes(n.status)?H("invalid_argument","Invalid batch close status"):(await el(r,n.status,n.error),ge({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(r){return H("provider",G(r))}}var eC,tC,uC=L(()=>{"use strict";jy();Zt();tr();xd();fr();Re();Bi();Od();Rn();Fy();Ya();kd();My();Py();en();rn();yt();eC=new WeakMap;tC=new WeakMap});import{readdirSync as BX}from"node:fs";import{join as dC,resolve as HX}from"node:path";import{randomUUID as WX}from"node:crypto";function Wy(t,e){let n=e&&typeof e=="object"?mC.get(e):void 0;return n?.ctx===t?n:void 0}function qy(t,e,n,r){let s=new Set(e.listRootTeams().map(a=>a.teamfile_path));for(let a of new Set([t.cwd,r]))try{for(let l of BX(a,{withFileTypes:!0}))l.isFile()&&/\.(?:lmctl|lmc)$/i.test(l.name)&&s.add(dC(a,l.name))}catch(l){if(l.code!=="ENOENT")throw l}let i=new Map;for(let a of s){let l;try{l=Pi(a,e)}catch(c){if(/missing on disk|teamfile not found/.test(G(c)))continue;throw c}if(l.parseErrors.length)throw Error("Cannot resolve native ownership: "+l.parseErrors.join("; "));for(let c of l.members){if(c.teamfile===void 0&&(c.provider!==n.provider||c.session!==n.sessionid))continue;let u=Lt(a,c.alias,e);u.provider===n.provider&&u.sessionid===n.sessionid&&i.set(JSON.stringify([Ot(u.teamfile,e),u.alias]),u)}}if(i.size>1)throw Error("Native session owner is ambiguous");let o=i.values().next().value;return o?{member:{...o,...n.model?{model:n.model}:{},...n.effort?{effort:n.effort}:{}},known:!0}:{member:{teamfile:"native:"+n.provider+":"+n.sessionid,alias:n.sessionid,provider:n.provider,sessionid:n.sessionid,sessiondir:r,isLead:!1,...n.model?{model:n.model}:{},...n.effort?{effort:n.effort}:{}},known:!1}}function Hy(t,e){return t.alias+" is servicing "+e.sender_alias+" ("+e.sender_teamfile+") since "+e.started_at+" \u2014 wait and retry"}function pC(t,e=!1){if(t.released)return;let n=e?t.dal.db.pragma("busy_timeout",{simple:!0}):void 0;e&&t.dal.db.pragma("busy_timeout=0");try{if(!t.dal.releaseAgentInflight(t.lease.row,t.lease.leaseId))throw Error("Native session lease release refused: ownership changed");t.released=!0}finally{e&&t.dal.db.pragma("busy_timeout="+n)}}async function $d(t){return t.closing||(t.closed=!0,t.serviceHosted||t.controller.abort(),t.closing=(async()=>{if(t.serviceHosted&&t.opening)try{t.conversation??=await t.opening}catch{}t.serviceHosted&&await t.active,await t.conversation?.close(),await t.active,t.stopHeartbeat(),pC(t,!0),t.untrack()})()),t.closing}function fC(t){if(t.serviceHosted)return t.controller.abort(),$d(t);t.closed=!0,t.stopHeartbeat(),t.controller.abort(),t.conversation&&t.conversation.close().catch(()=>{}),pC(t,!0),t.untrack()}async function so(t,e,n={},r,s=!1){let i;try{let o=pe(t);if(o)return o;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Native session member must be a map");for(let N of["provider","sessionid"])if(typeof e[N]!="string"||!e[N].trim())return H("invalid_argument","Native session requires provider and sessionid");for(let N of["sessiondir","model","effort"])if(e[N]!==void 0&&(typeof e[N]!="string"||!e[N].trim()))return H("invalid_argument","Native session "+N+" must be a nonempty string");if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(N=>!["permissionMode","idleTimeoutMs"].includes(N)))return H("invalid_argument","Native session options must contain permissionMode or idleTimeoutMs");if(n.permissionMode!==void 0&&!["yolo","plan"].includes(n.permissionMode))return H("invalid_argument","permissionMode must be yolo or plan");if(n.idleTimeoutMs!==void 0&&(!Number.isFinite(n.idleTimeoutMs)||n.idleTimeoutMs<0))return H("invalid_argument","idleTimeoutMs must be finite and nonnegative");let a=un(t),l=HX(t.cwd,e.sessiondir??t.cwd),c;try{c=qy(t,a,e,l)}catch(N){return H("invalid_argument",G(N))}let u=gn(t);if(!await u.getSession(e.sessionid,e.provider))return H("not_found","Native session was not found");if(t.closed)return H("cancelled","Context is closed");let m=c.member,p=Ri(a,m.teamfile,m.alias);if(p.busy)return{status:"busy",error:p.reason==="in-flight"?Hy(m,p.inFlight):p.source==="terminal-lock"?Vs(p.terminalLock):m.alias+" is busy (interactive terminal); wait and retry"};let f={receiver_teamfile:m.teamfile,receiver_alias:m.alias,sender_teamfile:m.teamfile,sender_alias:"operator",started_at:new Date().toISOString()},h=a.getAgentInflight(m.teamfile,m.alias),g=h!==null&&(h.native_provider!==null&&h.native_provider!==void 0||h.native_session_id!==null&&h.native_session_id!==void 0);if(g&&!r)return{status:"busy",error:Hy(m,h)};let y=r&&g?a.tryAcquireNativeHolder(f,r):void 0,b=y?y.acquired?{acquired:!0,lease:y.current,leaseId:y.lease_id}:{acquired:!1,current:y.current}:$r(a,{...f,ttlMs:jr(t.env),...r?{nativeHolder:r}:{}});if(!b.acquired)return{status:"busy",error:Hy(m,b.current)};let _=Object.freeze({id:"native-session-"+WX()});i={ctx:t,dal:a,ref:_,member:m,ownerKnown:c.known,options:{...n},lease:{row:b.lease,leaseId:b.leaseId},controller:new AbortController,serviceHosted:s,closed:!1,released:!1,stopHeartbeat(){},untrack(){}};let v=i;v.untrack=En(t,{close:()=>$d(v),finalizeSync:()=>fC(v)});let E=ki(N=>a.heartbeatAgentInflight(v.lease.row,v.lease.leaseId,N),{intervalMs:Pc(t.env)});v.stopHeartbeat=()=>clearInterval(E);let x=ty({provider:e.provider,sessionId:e.sessionid,cwd:m.sessiondir,env:{...t.env},model:m.model,effort:m.effort,permissionMode:n.permissionMode??"yolo",timeoutMs:s?0:n.idleTimeoutMs??0,serviceHosted:s,execution:s?"persistent":"auto",requireResume:!0,registry:u,userConfig:Kr(t.env.HOME?dC(t.env.HOME,".lmctl/config.toml"):void 0)});v.opening=x,x.then(N=>{v.closed&&N.close().catch(()=>{})}).catch(()=>{});let S,R=new Promise((N,O)=>{S=()=>O(Error("Context is closed")),t.signal.addEventListener("abort",S,{once:!0}),t.signal.aborted&&S()});try{v.conversation=await Promise.race([x,R])}finally{t.signal.removeEventListener("abort",S)}if(t.closed||v.closed)throw Error("Context is closed");return mC.set(_,v),ge({session:_})}catch(o){if(i)try{await $d(i)}catch(a){return H("provider",G(o)+"; "+G(a))}return H(t?.closed?"cancelled":"provider",G(o))}}async function io(t,e,n,r=void 0){let s=(l,c="invalid_argument")=>({status:"error",reply:"",error:l,code:c,messageId:null,teamChatLogId:null}),i=pe(t);if(i)return s(i.error,i.code);let o=Wy(t,e);if(!o||o.closed||!o.conversation)return s("Invalid or closed native session reference");if(typeof n!="string")return s("Native session prompt must be a string");if(o.active)return{status:"busy",reply:"",error:"Batch already has an active turn",messageId:null,teamChatLogId:null};let a;o.active=new Promise(l=>{a=l});try{if(o.ownerKnown){let c=Lt(o.member.teamfile,o.member.alias,o.dal);if(c.provider!==o.member.provider||c.sessionid!==o.member.sessionid)throw Error("Session binding changed; native turn cancelled")}let l=await ro({signal:AbortSignal.any([t.signal,o.controller.signal]),teamfile:o.member.teamfile,alias:o.member.alias,resolvedNativeTarget:o.member,prompt:n,expectedSession:{provider:o.member.provider,sessionid:o.member.sessionid},permissionMode:o.options.permissionMode??"yolo",idleTimeoutMs:o.serviceHosted?0:o.options.idleTimeoutMs,heldLease:o.lease,conversation:o.conversation,registry:gn(t),onAccepted:r?.onAccepted,env:{...t.env,...r?.attribution},io:{...mt(t),dal:o.dal}});return{status:l.status,reply:"replyText"in l?l.replyText:"",error:l.status==="ok"?null:"message"in l?l.message:"provider "+l.status,messageId:"messageId"in l?l.messageId:null,teamChatLogId:l.teamChatLogId}}catch(l){return s(G(l),"provider")}finally{a(),o.active=void 0}}async function zs(t,e){try{let n=Wy(t,e);return n?(await $d(n),ge({})):H("invalid_argument","Invalid native session reference")}catch(n){return H("provider",G(n))}}function gC(t,e){try{let n=Wy(t,e);if(!n)return H("invalid_argument","Invalid native session reference");let r=fC(n);return r&&r.catch(s=>t.onWarning(G(s))),ge({})}catch(n){return H("provider",G(n))}}var mC,jd=L(()=>{"use strict";fr();Bi();Ga();en();rn();Rn();$s();tr();Ya();yt();Od();mC=new WeakMap});import{randomUUID as qX}from"node:crypto";import{join as XX,resolve as hC}from"node:path";function Bd(t){if(!t||!["turn","close"].includes(t.operation))throw Error("Expected a native turn or close operation");let{member:e,options:n={}}=t;if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!["provider","sessionid","sessiondir","model","effort"].includes(r)))throw Error("Native session member must be a map");for(let r of["provider","sessionid"])if(typeof e[r]!="string"||!e[r].trim())throw Error("Native session requires provider and sessionid");for(let r of["sessiondir","model","effort"])if(e[r]!==void 0&&(typeof e[r]!="string"||!e[r].trim()))throw Error("Invalid native session "+r);if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(r=>!["permissionMode","idleTimeoutMs"].includes(r)))throw Error("Unknown native session option");if(n.permissionMode!==void 0&&!["yolo","plan"].includes(n.permissionMode))throw Error("permissionMode must be yolo or plan");if(n.idleTimeoutMs!==void 0&&(!Number.isFinite(n.idleTimeoutMs)||n.idleTimeoutMs<0||n.idleTimeoutMs>2147483647))throw Error("idleTimeoutMs must be a nonnegative retention interval");if(t.operation==="turn"&&typeof t.prompt!="string")throw Error("Native session prompt must be a string");if(t.attribution!==void 0&&(!t.attribution||typeof t.attribution!="object"||Array.isArray(t.attribution)||Object.entries(t.attribution).some(([r,s])=>!["LMCTL_SELF_SESSIONID","LMCTL_INVOCATION_ID"].includes(r)||s!==void 0&&typeof s!="string")))throw Error("Invalid native request attribution")}var GX,Ud,Xy=L(()=>{"use strict";en();jd();Ga();Bi();Vr();GX={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)};Ud=class{entries=new Map;service_epoch=qX();nextEpoch=0;stopping=!1;drained;clock;idleMs;context;ownsContext;constructor(e){this.context=e.context,this.clock=e.clock??GX,this.idleMs=e.idleMs??3e5,this.ownsContext=e.ownsContext??!1}fields(e,n=null){return{outcome:"not_sent",service_epoch:this.service_epoch,connection_epoch:e?.epoch??null,connection_state:n}}async request(e){let n=(i,o,a="error",l)=>({...this.fields(l),status:a,code:i,reply:"",error:o,messageId:null,teamChatLogId:null});try{Bd(e)}catch(i){return n("invalid_argument",String(i))}if(this.stopping)return n("closed","Native conversation service is shutting down");let r=JSON.stringify([e.member.provider,e.member.sessionid]),s=this.entries.get(r);if(s?.active||s?.closing)return n("busy","Native conversation has active or closing work","busy",s);if(e.operation==="close"){if(!s)return{...n("",""),status:"ok",code:void 0,error:null,outcome:"completed"};let i=this.fields(s);try{await this.closeEntry(r,s)}catch(o){return n("provider",String(o),"error",s)}return{...i,status:"ok",reply:"",error:null,messageId:null,teamChatLogId:null,outcome:"completed"}}try{let i=gn(this.context).getAdapter(e.member.provider),o=Kr(this.context.env.HOME?XX(this.context.env.HOME,".lmctl/config.toml"):void 0);if(!i||!wu(i,o))return n("provider","Provider is not qualified for service-hosted native resume");if(s){let l=e.member,c=e.options??{};if(l.sessiondir!==void 0&&hC(this.context.cwd,l.sessiondir)!==s.member.sessiondir||["model","effort"].some(u=>l[u]!==void 0&&l[u]!==s.member[u])||c.permissionMode!==void 0&&c.permissionMode!==s.options.permissionMode||c.idleTimeoutMs!==void 0&&c.idleTimeoutMs!==s.options.idleTimeoutMs)return n("invalid_argument","Native conversation configuration conflicts with retained connection","error",s)}let a=s?s.session?"reused":"reinitialized":"new";if(!s){let l=qy(this.context,un(this.context),e.member,hC(this.context.cwd,e.member.sessiondir??this.context.cwd));s={member:{...e.member,sessiondir:l.member.sessiondir,model:l.member.model,effort:l.member.effort},options:{permissionMode:e.options?.permissionMode??"yolo",idleTimeoutMs:e.options?.idleTimeoutMs??this.idleMs},epoch:0,active:!1,phase:"opening"},this.entries.set(r,s)}return s.active=!0,this.cancelIdle(s),s.work=this.perform(r,s,e,a),s.work}catch(i){return n("invalid_argument",String(i),"error",s)}}async perform(e,n,r,s){try{if(!n.session){n.phase="opening",n.epoch=++this.nextEpoch;let o=n.member,a=await so(this.context,o,n.options,{provider:o.provider,sessionId:o.sessionid,endpoint:null,phase:"starting",processIdentity:null,configJson:null},!0);if(a.status!=="ok")return this.entries.get(e)===n&&this.entries.delete(e),{...this.fields(n,s),status:a.status,code:"code"in a?a.code:"busy",reply:"",error:a.error,messageId:null,teamChatLogId:null};n.session=a.session}n.phase="active";let i=await io(this.context,n.session,r.prompt,{attribution:{LMCTL_SELF_SESSIONID:r.attribution?.LMCTL_SELF_SESSIONID,LMCTL_INVOCATION_ID:r.attribution?.LMCTL_INVOCATION_ID}});if(i.status==="error"){let o=await zs(this.context,n.session);return o.status!=="ok"?(n.phase="closing",n.closing=Promise.reject(Error(o.error)),n.closing.catch(()=>{}),{...i,...this.fields(n,s),code:i.messageId?"outcome_unknown":i.code??"provider",outcome:i.messageId?"unknown":"not_sent",error:(i.error??"Provider turn failed")+"; cleanup: "+o.error}):(n.session=void 0,n.phase="disconnected",{...i,...this.fields(n,s),code:i.messageId?"outcome_unknown":i.code??"provider",outcome:i.messageId?"unknown":"not_sent"})}return{...i,...this.fields(n,s),outcome:"completed",...i.status!=="ok"?{code:i.status==="busy"?"busy":i.code??"provider"}:{},...i.status==="busy"?{outcome:"not_sent"}:{}}}catch(i){return{...this.fields(n,s),status:"error",code:"provider",reply:"",error:String(i),messageId:null,teamChatLogId:null}}finally{n.active=!1,n.closing||(n.phase=n.session?"ready":"disconnected",this.stopping||this.armIdle(e,n))}}cancelIdle(e){e.idle!==void 0&&(this.clock.clearTimeout(e.idle),e.idle=void 0)}armIdle(e,n){if(this.cancelIdle(n),this.entries.get(e)!==n||n.active||n.closing)return;let r=n.options.idleTimeoutMs??this.idleMs;r>0&&(n.idle=this.clock.setTimeout(()=>{this.closeEntry(e,n).catch(s=>this.context.onWarning("Native conversation idle close failed: "+String(s)))},r))}closeEntry(e,n){return n.closing||(this.cancelIdle(n),n.phase="closing",n.closing=(async()=>{if(n.active&&await n.work,n.session){let r=await zs(this.context,n.session);if(r.status!=="ok")throw Error(r.error)}this.entries.get(e)===n&&this.entries.delete(e)})()),n.closing}shutdown(){return this.drained?this.drained:(this.stopping=!0,this.drained=Promise.allSettled([...this.entries].map(([e,n])=>this.closeEntry(e,n))).then(async e=>{let n=e.flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(n.length)throw new AggregateError(n,"Native cleanup failed: "+n.map(String).join("; "));if(this.ownsContext){let r=await this.context.close();if(r.errors.length)throw Error(r.errors.join("; "))}}),this.drained)}cancel(){this.stopping=!0;for(let e of this.entries.values())this.cancelIdle(e);this.context.finalizeSync("SIGTERM")}}});import{request as JX}from"node:http";import{request as VX}from"node:https";import{join as KX,resolve as zX}from"node:path";function yC(t,e){let n=gn(t).getAdapter(e.provider),r=Kr(t.env.HOME?KX(t.env.HOME,".lmctl/config.toml"):void 0);return n?wu(n,r)?"hosted":n.openSession!==void 0&&r.tools[e.provider]?.agent===void 0?"unsupported":"local":"unsupported"}function _C(t,e){let n=t.env.LMCTL_SERVICE_ENDPOINT;if(!n)return Promise.resolve(Fn("service_unavailable","LMCTL_SERVICE_ENDPOINT is required; start lmbee serve and configure its loopback endpoint"));let r;try{if(r=new URL(n),!["http:","https:"].includes(r.protocol))throw Error("Expected HTTP endpoint");r.pathname=r.pathname.replace(/\/+$/,"")+"/api/native-session/request"}catch{return Promise.resolve(Fn("service_unavailable","Invalid service endpoint "+n+"; start lmbee serve"))}let s={...e,member:{...e.member,...e.member.sessiondir!==void 0?{sessiondir:zX(t.cwd,e.member.sessiondir)}:{}},attribution:{LMCTL_SELF_SESSIONID:t.env.LMCTL_SELF_SESSIONID,LMCTL_INVOCATION_ID:t.env.LMCTL_INVOCATION_ID}},i=JSON.stringify(s);return new Promise(o=>{let a=!1,l=!1,c=!1,u=p=>{c||(c=!0,o(p))},d=p=>Fn(a||l?"outcome_unknown":"service_unavailable",a||l?p:"lmbee service unavailable at "+n+"; start lmbee serve ("+p+")",a||l?"unknown":"not_sent"),m=(r.protocol==="https:"?VX:JX)(r,{method:"POST",headers:{"content-type":"application/json","content-length":Buffer.byteLength(i)}},p=>{let f="";p.setTimeout(0),p.setEncoding("utf8"),p.on("data",h=>f+=h),p.on("end",()=>{try{let h=JSON.parse(f);if(!h||typeof h.status!="string")throw Error("Invalid native service result");u({...Gy,...h})}catch{u(d("Native service returned invalid JSON or HTTP "+p.statusCode))}}),p.on("aborted",()=>u(d("Native service reply lost; prior accepted outcome is unknown"))),p.on("error",h=>u(d(h.message)))});m.setTimeout(0),m.on("socket",p=>{p.setTimeout(0),p.once("connect",()=>{l=!0})}),m.once("finish",()=>{a=!0}),m.on("error",p=>u(d(p.message))),m.on("close",()=>{c||u(d("Native service connection closed before reply"))}),m.end(i)})}async function vC(t,e,n,r={}){try{let s=pe(t);if(s)return Fn(s.code,s.error);let i={operation:"turn",member:e,prompt:n,options:r};Bd(i);let o=yC(t,e);if(o==="hosted")return await _C(t,i);if(o==="unsupported")return Fn("provider","Provider is not qualified for service-hosted native resume");let a=await so(t,e,r);if(a.status!=="ok")return{...Fn("code"in a?a.code:"busy",a.error),status:a.status};try{let l=await io(t,a.session,n);return l.status==="ok"?l:{...l,code:l.status==="busy"?"busy":l.code??"provider"}}finally{await zs(t,a.session)}}catch(s){return Fn("invalid_argument",String(s))}}async function bC(t,e){try{let n=pe(t);if(n)return Fn(n.code,n.error);let r={operation:"close",member:e};Bd(r);let s=yC(t,e);return s==="hosted"?await _C(t,r):s==="unsupported"?Fn("provider","Provider is not qualified for service-hosted native resume"):{...Gy,status:"ok",error:null,reply:"",messageId:null,teamChatLogId:null,outcome:"completed"}}catch(n){return Fn("invalid_argument",String(n))}}var Gy,Fn,wC=L(()=>{"use strict";rn();Ga();Bi();Vr();jd();Xy();Gy={outcome:"not_sent",service_epoch:null,connection_epoch:null,connection_state:null},Fn=(t,e,n="not_sent")=>({...Gy,status:"error",reply:"",error:e,code:t,messageId:null,teamChatLogId:null,outcome:n})});var EC=L(()=>{"use strict";ir()});var TC=L(()=>{"use strict"});import{constants as YX}from"node:os";import{spawn as QX}from"node:child_process";async function SC(t,e,n,r,s){let i=await ZX(t,e,n,r,!1,s);return{code:s.signalObserved?null:i,signal:s.signalObserved??null}}async function ZX(t,e,n,r,s,i){let o;try{o=Lt(e,n,r)}catch(T){return T instanceof Le?sr(t,T.message):pS(t,T)}let a=$r(r,{receiver_teamfile:o.teamfile,receiver_alias:o.alias,sender_teamfile:o.teamfile,sender_alias:"terminal",ttlMs:is(i?.env??t.env)});if(!a.acquired){let T=a.current.holder_pid,k=T===null?null:vt(T)?"live":"dead",I=`${o.alias} is busy/held by ${a.current.sender_alias} (${a.current.sender_teamfile}) since ${a.current.started_at} `+(T===null?"(holder_pid=unavailable)":`(holder_pid=${T}, ${k})`);return s?(Gf(t,{status:"error",errorKind:"busy",message:I,holder_pid:T,holder_liveness:k}),1):sr(t,I)}let l=jA({teamfile:o.teamfile,alias:o.alias,pid:i?.pid}),c=null,u=null,d=null,m=[],p={...i?.env??t.env??process.env},f=!1,h=null,g=!1,y,b,_,v=T=>{c!==null&&(clearInterval(c),c=null);try{let k=r.getTerminalLock(l.teamfile,l.alias);!r.clearTerminalLock(l.teamfile,l.alias,l.lock_id)&&k!==null&&T.push("terminal lock release was not acknowledged")}catch(k){T.push(`terminal lock release: ${k instanceof Error?k.message:String(k)}`)}try{let k=r.getAgentInflight(l.teamfile,l.alias);!r.releaseAgentInflight(a.lease,a.leaseId)&&k!==null&&T.push("inflight release was not acknowledged")}catch(k){T.push(`inflight release: ${k instanceof Error?k.message:String(k)}`)}},E=(T,k)=>{let I=r.db.pragma("busy_timeout",{simple:!0});r.db.pragma("busy_timeout=0");try{T(k)}finally{try{r.db.pragma(`busy_timeout=${I}`)}catch(C){k.push(`busy timeout restore: ${C instanceof Error?C.message:String(C)}`)}}},x=(T,k)=>{if(!(u===null||g))try{if(r.finishTrackedInvocation(u,T)===null){let C=r.getTrackedInvocation(u);C==null||C.status==="running"?k.push("tracked terminal finish was not acknowledged"):g=!0}else g=!0}catch(I){k.push(`tracked terminal finish: ${I instanceof Error?I.message:String(I)}`)}},S=T=>{if(f)return;f=!0;let k=[];try{E(I=>{v(I),x({status:"cancelled",signal:T,exit_code:T==="SIGINT"?130:143,error:`terminal interrupted by ${T}`},I)},k)}catch(I){k.push(I instanceof Error?I.message:String(I))}k.length>0&&(h=Error(k.join("; ")))},R=!i,N=R?new AbortController:void 0,O=()=>N?.abort("SIGINT"),A=()=>N?.abort("SIGTERM");R&&(process.once("SIGINT",O),process.once("SIGTERM",A));let w=i??{env:p,signal:N?.signal};w.env=p;try{if(w.cancel=S,w.cleanupError=()=>h,i&&i.onResource?.({close(){if(b)return b;let I,C;b=new Promise((D,j)=>{I=D,C=j});let M=performance.now();return(async()=>{if(S("SIGTERM"),i.stop?.("SIGTERM"),h)throw h;if(y){let D=5e3-(performance.now()-M),j;try{if(D<=0)throw Error("terminal close deadline exceeded");await Promise.race([y.catch(()=>{}),new Promise((F,Z)=>{j=setTimeout(()=>Z(Error("terminal close deadline exceeded")),D)})])}catch(F){throw h=F instanceof Error?F:Error(String(F)),h}finally{clearTimeout(j)}}})().then(I,C),b},finalizeSync(I){if(S(I),i.stop?.(I),h)throw h}}),f||w.signal?.aborted){let I=w.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM";return S(I),I==="SIGINT"?130:143}r.setTerminalLock(l),u=eG(r,o,p,i?.pid),u!==null&&(p.LMCTL_INVOCATION_ID=String(u));let T=r.getRootTeam(o.teamfile)?.name??null;T!==null&&(p.LMBEE_TEAM_NAME=T),c=setInterval(()=>{try{let I=new Date().toISOString(),C=r.heartbeatTerminalLock(l.teamfile,l.alias,l.lock_id,I);C&&r.heartbeatAgentInflight(a.lease,a.leaseId,I),!C&&c!==null&&(clearInterval(c),c=null)}catch{}},UA(p)),c.unref?.();try{Zi(t,qt(o.teamfile),o.teamfile)}catch{}let k=w;return y=tG(t,{provider:o.provider,sessionid:o.sessionid,sessiondir:o.sessiondir,...o.model!==void 0?{model:o.model}:{},isLead:o.isLead},I=>{m.push(`${I.provider} terminal ignored model=${I.model}: ${I.reason}`)},k),d=await y,d}catch(T){throw _=T,T}finally{if(R&&(process.removeListener("SIGINT",O),process.removeListener("SIGTERM",A)),!f){f=!0;let T=[];try{E(k=>{v(k),x({status:d===0?"done":"error",exit_code:d,result_summary:d===0?"terminal session ended":null,error:d===0?null:`terminal exited with code ${d??"unknown"}`,...m.length>0?{config_warnings:JSON.stringify(m)}:{}},k)},T)}catch(k){T.push(k instanceof Error?k.message:String(k))}T.length>0&&(h=Error(T.join("; ")))}if(h){if(_===void 0)throw h;try{t.stderr.write("error: terminal cleanup: "+h.message+`
|
|
2411
|
+
`),{status:f.status,error:y,reply:h,messageId:"messageId"in f?f.messageId:null,teamChatLogId:f.teamChatLogId}}return a.completed++,{status:"ok",error:null,reply:h,messageId:f.messageId,teamChatLogId:f.teamChatLogId}}catch(m){let p=`batch: stopped at prompt ${r}/${s} (${r-1} completed): ${V(m)}; later prompts were not sent`;a.failed=p,a.rootFinish={status:"error",exit_code:1,error:p,result_summary:`${r-1}/${s} prompts completed`};try{mt(t).stderr.write(`error: ${p}
|
|
2412
|
+
`)}catch{}return i(p,"provider")}finally{d?.stop(),a.inFlight=!1,a.turnFinished?.(),a.turnDone=void 0,u(),l||c?.close()}}async function cC(t,e,n){try{let r=Fd(t,e);return r?!n||!["done","error","cancelled"].includes(n.status)?H("invalid_argument","Invalid batch close status"):(await el(r,n.status,n.error),ge({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(r){return H("provider",V(r))}}var eC,tC,uC=L(()=>{"use strict";jy();Zt();tr();xd();fr();Re();Bi();Od();Rn();Fy();Ya();kd();My();Py();en();rn();yt();eC=new WeakMap;tC=new WeakMap});import{readdirSync as BX}from"node:fs";import{join as dC,resolve as HX}from"node:path";import{randomUUID as WX}from"node:crypto";function Wy(t,e){let n=e&&typeof e=="object"?mC.get(e):void 0;return n?.ctx===t?n:void 0}function qy(t,e,n,r){let s=new Set(e.listRootTeams().map(a=>a.teamfile_path));for(let a of new Set([t.cwd,r]))try{for(let l of BX(a,{withFileTypes:!0}))l.isFile()&&/\.(?:lmctl|lmc)$/i.test(l.name)&&s.add(dC(a,l.name))}catch(l){if(l.code!=="ENOENT")throw l}let i=new Map;for(let a of s){let l;try{l=Pi(a,e)}catch(c){if(/missing on disk|teamfile not found/.test(V(c)))continue;throw c}if(l.parseErrors.length)throw Error("Cannot resolve native ownership: "+l.parseErrors.join("; "));for(let c of l.members){if(c.teamfile===void 0&&(c.provider!==n.provider||c.session!==n.sessionid))continue;let u=Lt(a,c.alias,e);u.provider===n.provider&&u.sessionid===n.sessionid&&i.set(JSON.stringify([Ot(u.teamfile,e),u.alias]),u)}}if(i.size>1)throw Error("Native session owner is ambiguous");let o=i.values().next().value;return o?{member:{...o,...n.model?{model:n.model}:{},...n.effort?{effort:n.effort}:{}},known:!0}:{member:{teamfile:"native:"+n.provider+":"+n.sessionid,alias:n.sessionid,provider:n.provider,sessionid:n.sessionid,sessiondir:r,isLead:!1,...n.model?{model:n.model}:{},...n.effort?{effort:n.effort}:{}},known:!1}}function Hy(t,e){return t.alias+" is servicing "+e.sender_alias+" ("+e.sender_teamfile+") since "+e.started_at+" \u2014 wait and retry"}function pC(t,e=!1){if(t.released)return;let n=e?t.dal.db.pragma("busy_timeout",{simple:!0}):void 0;e&&t.dal.db.pragma("busy_timeout=0");try{if(!t.dal.releaseAgentInflight(t.lease.row,t.lease.leaseId))throw Error("Native session lease release refused: ownership changed");t.released=!0}finally{e&&t.dal.db.pragma("busy_timeout="+n)}}async function $d(t){return t.closing||(t.closed=!0,t.serviceHosted||t.controller.abort(),t.closing=(async()=>{if(t.serviceHosted&&t.opening)try{t.conversation??=await t.opening}catch{}t.serviceHosted&&await t.active,await t.conversation?.close(),await t.active,t.stopHeartbeat(),pC(t,!0),t.untrack()})()),t.closing}function fC(t){if(t.serviceHosted)return t.controller.abort(),$d(t);t.closed=!0,t.stopHeartbeat(),t.controller.abort(),t.conversation&&t.conversation.close().catch(()=>{}),pC(t,!0),t.untrack()}async function so(t,e,n={},r,s=!1){let i;try{let o=fe(t);if(o)return o;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Native session member must be a map");for(let N of["provider","sessionid"])if(typeof e[N]!="string"||!e[N].trim())return H("invalid_argument","Native session requires provider and sessionid");for(let N of["sessiondir","model","effort"])if(e[N]!==void 0&&(typeof e[N]!="string"||!e[N].trim()))return H("invalid_argument","Native session "+N+" must be a nonempty string");if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(N=>!["permissionMode","idleTimeoutMs"].includes(N)))return H("invalid_argument","Native session options must contain permissionMode or idleTimeoutMs");if(n.permissionMode!==void 0&&!["yolo","plan"].includes(n.permissionMode))return H("invalid_argument","permissionMode must be yolo or plan");if(n.idleTimeoutMs!==void 0&&(!Number.isFinite(n.idleTimeoutMs)||n.idleTimeoutMs<0))return H("invalid_argument","idleTimeoutMs must be finite and nonnegative");let a=un(t),l=HX(t.cwd,e.sessiondir??t.cwd),c;try{c=qy(t,a,e,l)}catch(N){return H("invalid_argument",V(N))}let u=gn(t);if(!await u.getSession(e.sessionid,e.provider))return H("not_found","Native session was not found");if(t.closed)return H("cancelled","Context is closed");let m=c.member,p=Ri(a,m.teamfile,m.alias);if(p.busy)return{status:"busy",error:p.reason==="in-flight"?Hy(m,p.inFlight):p.source==="terminal-lock"?Vs(p.terminalLock):m.alias+" is busy (interactive terminal); wait and retry"};let f={receiver_teamfile:m.teamfile,receiver_alias:m.alias,sender_teamfile:m.teamfile,sender_alias:"operator",started_at:new Date().toISOString()},h=a.getAgentInflight(m.teamfile,m.alias),g=h!==null&&(h.native_provider!==null&&h.native_provider!==void 0||h.native_session_id!==null&&h.native_session_id!==void 0);if(g&&!r)return{status:"busy",error:Hy(m,h)};let y=r&&g?a.tryAcquireNativeHolder(f,r):void 0,b=y?y.acquired?{acquired:!0,lease:y.current,leaseId:y.lease_id}:{acquired:!1,current:y.current}:$r(a,{...f,ttlMs:jr(t.env),...r?{nativeHolder:r}:{}});if(!b.acquired)return{status:"busy",error:Hy(m,b.current)};let _=Object.freeze({id:"native-session-"+WX()});i={ctx:t,dal:a,ref:_,member:m,ownerKnown:c.known,options:{...n},lease:{row:b.lease,leaseId:b.leaseId},controller:new AbortController,serviceHosted:s,closed:!1,released:!1,stopHeartbeat(){},untrack(){}};let v=i;v.untrack=En(t,{close:()=>$d(v),finalizeSync:()=>fC(v)});let E=ki(N=>a.heartbeatAgentInflight(v.lease.row,v.lease.leaseId,N),{intervalMs:Pc(t.env)});v.stopHeartbeat=()=>clearInterval(E);let x=ty({provider:e.provider,sessionId:e.sessionid,cwd:m.sessiondir,env:{...t.env},model:m.model,effort:m.effort,permissionMode:n.permissionMode??"yolo",timeoutMs:s?0:n.idleTimeoutMs??0,serviceHosted:s,execution:s?"persistent":"auto",requireResume:!0,registry:u,userConfig:Kr(t.env.HOME?dC(t.env.HOME,".lmctl/config.toml"):void 0)});v.opening=x,x.then(N=>{v.closed&&N.close().catch(()=>{})}).catch(()=>{});let S,R=new Promise((N,O)=>{S=()=>O(Error("Context is closed")),t.signal.addEventListener("abort",S,{once:!0}),t.signal.aborted&&S()});try{v.conversation=await Promise.race([x,R])}finally{t.signal.removeEventListener("abort",S)}if(t.closed||v.closed)throw Error("Context is closed");return mC.set(_,v),ge({session:_})}catch(o){if(i)try{await $d(i)}catch(a){return H("provider",V(o)+"; "+V(a))}return H(t?.closed?"cancelled":"provider",V(o))}}async function io(t,e,n,r=void 0){let s=(l,c="invalid_argument")=>({status:"error",reply:"",error:l,code:c,messageId:null,teamChatLogId:null}),i=fe(t);if(i)return s(i.error,i.code);let o=Wy(t,e);if(!o||o.closed||!o.conversation)return s("Invalid or closed native session reference");if(typeof n!="string")return s("Native session prompt must be a string");if(o.active)return{status:"busy",reply:"",error:"Batch already has an active turn",messageId:null,teamChatLogId:null};let a;o.active=new Promise(l=>{a=l});try{if(o.ownerKnown){let c=Lt(o.member.teamfile,o.member.alias,o.dal);if(c.provider!==o.member.provider||c.sessionid!==o.member.sessionid)throw Error("Session binding changed; native turn cancelled")}let l=await ro({signal:AbortSignal.any([t.signal,o.controller.signal]),teamfile:o.member.teamfile,alias:o.member.alias,resolvedNativeTarget:o.member,prompt:n,expectedSession:{provider:o.member.provider,sessionid:o.member.sessionid},permissionMode:o.options.permissionMode??"yolo",idleTimeoutMs:o.serviceHosted?0:o.options.idleTimeoutMs,heldLease:o.lease,conversation:o.conversation,registry:gn(t),onAccepted:r?.onAccepted,env:{...t.env,...r?.attribution},io:{...mt(t),dal:o.dal}});return{status:l.status,reply:"replyText"in l?l.replyText:"",error:l.status==="ok"?null:"message"in l?l.message:"provider "+l.status,messageId:"messageId"in l?l.messageId:null,teamChatLogId:l.teamChatLogId}}catch(l){return s(V(l),"provider")}finally{a(),o.active=void 0}}async function zs(t,e){try{let n=Wy(t,e);return n?(await $d(n),ge({})):H("invalid_argument","Invalid native session reference")}catch(n){return H("provider",V(n))}}function gC(t,e){try{let n=Wy(t,e);if(!n)return H("invalid_argument","Invalid native session reference");let r=fC(n);return r&&r.catch(s=>t.onWarning(V(s))),ge({})}catch(n){return H("provider",V(n))}}var mC,jd=L(()=>{"use strict";fr();Bi();Ga();en();rn();Rn();$s();tr();Ya();yt();Od();mC=new WeakMap});import{randomUUID as qX}from"node:crypto";import{join as XX,resolve as hC}from"node:path";function Bd(t){if(!t||!["turn","close"].includes(t.operation))throw Error("Expected a native turn or close operation");let{member:e,options:n={}}=t;if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!["provider","sessionid","sessiondir","model","effort"].includes(r)))throw Error("Native session member must be a map");for(let r of["provider","sessionid"])if(typeof e[r]!="string"||!e[r].trim())throw Error("Native session requires provider and sessionid");for(let r of["sessiondir","model","effort"])if(e[r]!==void 0&&(typeof e[r]!="string"||!e[r].trim()))throw Error("Invalid native session "+r);if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(r=>!["permissionMode","idleTimeoutMs"].includes(r)))throw Error("Unknown native session option");if(n.permissionMode!==void 0&&!["yolo","plan"].includes(n.permissionMode))throw Error("permissionMode must be yolo or plan");if(n.idleTimeoutMs!==void 0&&(!Number.isFinite(n.idleTimeoutMs)||n.idleTimeoutMs<0||n.idleTimeoutMs>2147483647))throw Error("idleTimeoutMs must be a nonnegative retention interval");if(t.operation==="turn"&&typeof t.prompt!="string")throw Error("Native session prompt must be a string");if(t.attribution!==void 0&&(!t.attribution||typeof t.attribution!="object"||Array.isArray(t.attribution)||Object.entries(t.attribution).some(([r,s])=>!["LMCTL_SELF_SESSIONID","LMCTL_INVOCATION_ID"].includes(r)||s!==void 0&&typeof s!="string")))throw Error("Invalid native request attribution")}var GX,Ud,Xy=L(()=>{"use strict";en();jd();Ga();Bi();Vr();GX={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)};Ud=class{entries=new Map;service_epoch=qX();nextEpoch=0;stopping=!1;drained;clock;idleMs;context;ownsContext;constructor(e){this.context=e.context,this.clock=e.clock??GX,this.idleMs=e.idleMs??3e5,this.ownsContext=e.ownsContext??!1}fields(e,n=null){return{outcome:"not_sent",service_epoch:this.service_epoch,connection_epoch:e?.epoch??null,connection_state:n}}async request(e){let n=(i,o,a="error",l)=>({...this.fields(l),status:a,code:i,reply:"",error:o,messageId:null,teamChatLogId:null});try{Bd(e)}catch(i){return n("invalid_argument",String(i))}if(this.stopping)return n("closed","Native conversation service is shutting down");let r=JSON.stringify([e.member.provider,e.member.sessionid]),s=this.entries.get(r);if(s?.active||s?.closing)return n("busy","Native conversation has active or closing work","busy",s);if(e.operation==="close"){if(!s)return{...n("",""),status:"ok",code:void 0,error:null,outcome:"completed"};let i=this.fields(s);try{await this.closeEntry(r,s)}catch(o){return n("provider",String(o),"error",s)}return{...i,status:"ok",reply:"",error:null,messageId:null,teamChatLogId:null,outcome:"completed"}}try{let i=gn(this.context).getAdapter(e.member.provider),o=Kr(this.context.env.HOME?XX(this.context.env.HOME,".lmctl/config.toml"):void 0);if(!i||!wu(i,o))return n("provider","Provider is not qualified for service-hosted native resume");if(s){let l=e.member,c=e.options??{};if(l.sessiondir!==void 0&&hC(this.context.cwd,l.sessiondir)!==s.member.sessiondir||["model","effort"].some(u=>l[u]!==void 0&&l[u]!==s.member[u])||c.permissionMode!==void 0&&c.permissionMode!==s.options.permissionMode||c.idleTimeoutMs!==void 0&&c.idleTimeoutMs!==s.options.idleTimeoutMs)return n("invalid_argument","Native conversation configuration conflicts with retained connection","error",s)}let a=s?s.session?"reused":"reinitialized":"new";if(!s){let l=qy(this.context,un(this.context),e.member,hC(this.context.cwd,e.member.sessiondir??this.context.cwd));s={member:{...e.member,sessiondir:l.member.sessiondir,model:l.member.model,effort:l.member.effort},options:{permissionMode:e.options?.permissionMode??"yolo",idleTimeoutMs:e.options?.idleTimeoutMs??this.idleMs},epoch:0,active:!1,phase:"opening"},this.entries.set(r,s)}return s.active=!0,this.cancelIdle(s),s.work=this.perform(r,s,e,a),s.work}catch(i){return n("invalid_argument",String(i),"error",s)}}async perform(e,n,r,s){try{if(!n.session){n.phase="opening",n.epoch=++this.nextEpoch;let o=n.member,a=await so(this.context,o,n.options,{provider:o.provider,sessionId:o.sessionid,endpoint:null,phase:"starting",processIdentity:null,configJson:null},!0);if(a.status!=="ok")return this.entries.get(e)===n&&this.entries.delete(e),{...this.fields(n,s),status:a.status,code:"code"in a?a.code:"busy",reply:"",error:a.error,messageId:null,teamChatLogId:null};n.session=a.session}n.phase="active";let i=await io(this.context,n.session,r.prompt,{attribution:{LMCTL_SELF_SESSIONID:r.attribution?.LMCTL_SELF_SESSIONID,LMCTL_INVOCATION_ID:r.attribution?.LMCTL_INVOCATION_ID}});if(i.status==="error"){let o=await zs(this.context,n.session);return o.status!=="ok"?(n.phase="closing",n.closing=Promise.reject(Error(o.error)),n.closing.catch(()=>{}),{...i,...this.fields(n,s),code:i.messageId?"outcome_unknown":i.code??"provider",outcome:i.messageId?"unknown":"not_sent",error:(i.error??"Provider turn failed")+"; cleanup: "+o.error}):(n.session=void 0,n.phase="disconnected",{...i,...this.fields(n,s),code:i.messageId?"outcome_unknown":i.code??"provider",outcome:i.messageId?"unknown":"not_sent"})}return{...i,...this.fields(n,s),outcome:"completed",...i.status!=="ok"?{code:i.status==="busy"?"busy":i.code??"provider"}:{},...i.status==="busy"?{outcome:"not_sent"}:{}}}catch(i){return{...this.fields(n,s),status:"error",code:"provider",reply:"",error:String(i),messageId:null,teamChatLogId:null}}finally{n.active=!1,n.closing||(n.phase=n.session?"ready":"disconnected",this.stopping||this.armIdle(e,n))}}cancelIdle(e){e.idle!==void 0&&(this.clock.clearTimeout(e.idle),e.idle=void 0)}armIdle(e,n){if(this.cancelIdle(n),this.entries.get(e)!==n||n.active||n.closing)return;let r=n.options.idleTimeoutMs??this.idleMs;r>0&&(n.idle=this.clock.setTimeout(()=>{this.closeEntry(e,n).catch(s=>this.context.onWarning("Native conversation idle close failed: "+String(s)))},r))}closeEntry(e,n){return n.closing||(this.cancelIdle(n),n.phase="closing",n.closing=(async()=>{if(n.active&&await n.work,n.session){let r=await zs(this.context,n.session);if(r.status!=="ok")throw Error(r.error)}this.entries.get(e)===n&&this.entries.delete(e)})()),n.closing}shutdown(){return this.drained?this.drained:(this.stopping=!0,this.drained=Promise.allSettled([...this.entries].map(([e,n])=>this.closeEntry(e,n))).then(async e=>{let n=e.flatMap(r=>r.status==="rejected"?[r.reason]:[]);if(n.length)throw new AggregateError(n,"Native cleanup failed: "+n.map(String).join("; "));if(this.ownsContext){let r=await this.context.close();if(r.errors.length)throw Error(r.errors.join("; "))}}),this.drained)}cancel(){this.stopping=!0;for(let e of this.entries.values())this.cancelIdle(e);this.context.finalizeSync("SIGTERM")}}});import{request as JX}from"node:http";import{request as VX}from"node:https";import{join as KX,resolve as zX}from"node:path";function yC(t,e){let n=gn(t).getAdapter(e.provider),r=Kr(t.env.HOME?KX(t.env.HOME,".lmctl/config.toml"):void 0);return n?wu(n,r)?"hosted":n.openSession!==void 0&&r.tools[e.provider]?.agent===void 0?"unsupported":"local":"unsupported"}function _C(t,e){let n=t.env.LMCTL_SERVICE_ENDPOINT;if(!n)return Promise.resolve(Fn("service_unavailable","LMCTL_SERVICE_ENDPOINT is required; start lmbee serve and configure its loopback endpoint"));let r;try{if(r=new URL(n),!["http:","https:"].includes(r.protocol))throw Error("Expected HTTP endpoint");r.pathname=r.pathname.replace(/\/+$/,"")+"/api/native-session/request"}catch{return Promise.resolve(Fn("service_unavailable","Invalid service endpoint "+n+"; start lmbee serve"))}let s={...e,member:{...e.member,...e.member.sessiondir!==void 0?{sessiondir:zX(t.cwd,e.member.sessiondir)}:{}},attribution:{LMCTL_SELF_SESSIONID:t.env.LMCTL_SELF_SESSIONID,LMCTL_INVOCATION_ID:t.env.LMCTL_INVOCATION_ID}},i=JSON.stringify(s);return new Promise(o=>{let a=!1,l=!1,c=!1,u=p=>{c||(c=!0,o(p))},d=p=>Fn(a||l?"outcome_unknown":"service_unavailable",a||l?p:"lmbee service unavailable at "+n+"; start lmbee serve ("+p+")",a||l?"unknown":"not_sent"),m=(r.protocol==="https:"?VX:JX)(r,{method:"POST",headers:{"content-type":"application/json","content-length":Buffer.byteLength(i)}},p=>{let f="";p.setTimeout(0),p.setEncoding("utf8"),p.on("data",h=>f+=h),p.on("end",()=>{try{let h=JSON.parse(f);if(!h||typeof h.status!="string")throw Error("Invalid native service result");u({...Gy,...h})}catch{u(d("Native service returned invalid JSON or HTTP "+p.statusCode))}}),p.on("aborted",()=>u(d("Native service reply lost; prior accepted outcome is unknown"))),p.on("error",h=>u(d(h.message)))});m.setTimeout(0),m.on("socket",p=>{p.setTimeout(0),p.once("connect",()=>{l=!0})}),m.once("finish",()=>{a=!0}),m.on("error",p=>u(d(p.message))),m.on("close",()=>{c||u(d("Native service connection closed before reply"))}),m.end(i)})}async function vC(t,e,n,r={}){try{let s=fe(t);if(s)return Fn(s.code,s.error);let i={operation:"turn",member:e,prompt:n,options:r};Bd(i);let o=yC(t,e);if(o==="hosted")return await _C(t,i);if(o==="unsupported")return Fn("provider","Provider is not qualified for service-hosted native resume");let a=await so(t,e,r);if(a.status!=="ok")return{...Fn("code"in a?a.code:"busy",a.error),status:a.status};try{let l=await io(t,a.session,n);return l.status==="ok"?l:{...l,code:l.status==="busy"?"busy":l.code??"provider"}}finally{await zs(t,a.session)}}catch(s){return Fn("invalid_argument",String(s))}}async function bC(t,e){try{let n=fe(t);if(n)return Fn(n.code,n.error);let r={operation:"close",member:e};Bd(r);let s=yC(t,e);return s==="hosted"?await _C(t,r):s==="unsupported"?Fn("provider","Provider is not qualified for service-hosted native resume"):{...Gy,status:"ok",error:null,reply:"",messageId:null,teamChatLogId:null,outcome:"completed"}}catch(n){return Fn("invalid_argument",String(n))}}var Gy,Fn,wC=L(()=>{"use strict";rn();Ga();Bi();Vr();jd();Xy();Gy={outcome:"not_sent",service_epoch:null,connection_epoch:null,connection_state:null},Fn=(t,e,n="not_sent")=>({...Gy,status:"error",reply:"",error:e,code:t,messageId:null,teamChatLogId:null,outcome:n})});var EC=L(()=>{"use strict";ir()});var TC=L(()=>{"use strict"});import{constants as YX}from"node:os";import{spawn as QX}from"node:child_process";async function SC(t,e,n,r,s){let i=await ZX(t,e,n,r,!1,s);return{code:s.signalObserved?null:i,signal:s.signalObserved??null}}async function ZX(t,e,n,r,s,i){let o;try{o=Lt(e,n,r)}catch(T){return T instanceof Le?sr(t,T.message):pS(t,T)}let a=$r(r,{receiver_teamfile:o.teamfile,receiver_alias:o.alias,sender_teamfile:o.teamfile,sender_alias:"terminal",ttlMs:is(i?.env??t.env)});if(!a.acquired){let T=a.current.holder_pid,k=T===null?null:vt(T)?"live":"dead",I=`${o.alias} is busy/held by ${a.current.sender_alias} (${a.current.sender_teamfile}) since ${a.current.started_at} `+(T===null?"(holder_pid=unavailable)":`(holder_pid=${T}, ${k})`);return s?(Gf(t,{status:"error",errorKind:"busy",message:I,holder_pid:T,holder_liveness:k}),1):sr(t,I)}let l=jA({teamfile:o.teamfile,alias:o.alias,pid:i?.pid}),c=null,u=null,d=null,m=[],p={...i?.env??t.env??process.env},f=!1,h=null,g=!1,y,b,_,v=T=>{c!==null&&(clearInterval(c),c=null);try{let k=r.getTerminalLock(l.teamfile,l.alias);!r.clearTerminalLock(l.teamfile,l.alias,l.lock_id)&&k!==null&&T.push("terminal lock release was not acknowledged")}catch(k){T.push(`terminal lock release: ${k instanceof Error?k.message:String(k)}`)}try{let k=r.getAgentInflight(l.teamfile,l.alias);!r.releaseAgentInflight(a.lease,a.leaseId)&&k!==null&&T.push("inflight release was not acknowledged")}catch(k){T.push(`inflight release: ${k instanceof Error?k.message:String(k)}`)}},E=(T,k)=>{let I=r.db.pragma("busy_timeout",{simple:!0});r.db.pragma("busy_timeout=0");try{T(k)}finally{try{r.db.pragma(`busy_timeout=${I}`)}catch(C){k.push(`busy timeout restore: ${C instanceof Error?C.message:String(C)}`)}}},x=(T,k)=>{if(!(u===null||g))try{if(r.finishTrackedInvocation(u,T)===null){let C=r.getTrackedInvocation(u);C==null||C.status==="running"?k.push("tracked terminal finish was not acknowledged"):g=!0}else g=!0}catch(I){k.push(`tracked terminal finish: ${I instanceof Error?I.message:String(I)}`)}},S=T=>{if(f)return;f=!0;let k=[];try{E(I=>{v(I),x({status:"cancelled",signal:T,exit_code:T==="SIGINT"?130:143,error:`terminal interrupted by ${T}`},I)},k)}catch(I){k.push(I instanceof Error?I.message:String(I))}k.length>0&&(h=Error(k.join("; ")))},R=!i,N=R?new AbortController:void 0,O=()=>N?.abort("SIGINT"),A=()=>N?.abort("SIGTERM");R&&(process.once("SIGINT",O),process.once("SIGTERM",A));let w=i??{env:p,signal:N?.signal};w.env=p;try{if(w.cancel=S,w.cleanupError=()=>h,i&&i.onResource?.({close(){if(b)return b;let I,C;b=new Promise((D,j)=>{I=D,C=j});let M=performance.now();return(async()=>{if(S("SIGTERM"),i.stop?.("SIGTERM"),h)throw h;if(y){let D=5e3-(performance.now()-M),j;try{if(D<=0)throw Error("terminal close deadline exceeded");await Promise.race([y.catch(()=>{}),new Promise(($,Z)=>{j=setTimeout(()=>Z(Error("terminal close deadline exceeded")),D)})])}catch($){throw h=$ instanceof Error?$:Error(String($)),h}finally{clearTimeout(j)}}})().then(I,C),b},finalizeSync(I){if(S(I),i.stop?.(I),h)throw h}}),f||w.signal?.aborted){let I=w.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM";return S(I),I==="SIGINT"?130:143}r.setTerminalLock(l),u=eG(r,o,p,i?.pid),u!==null&&(p.LMCTL_INVOCATION_ID=String(u));let T=r.getRootTeam(o.teamfile)?.name??null;T!==null&&(p.LMBEE_TEAM_NAME=T),c=setInterval(()=>{try{let I=new Date().toISOString(),C=r.heartbeatTerminalLock(l.teamfile,l.alias,l.lock_id,I);C&&r.heartbeatAgentInflight(a.lease,a.leaseId,I),!C&&c!==null&&(clearInterval(c),c=null)}catch{}},UA(p)),c.unref?.();try{Zi(t,qt(o.teamfile),o.teamfile)}catch{}let k=w;return y=tG(t,{provider:o.provider,sessionid:o.sessionid,sessiondir:o.sessiondir,...o.model!==void 0?{model:o.model}:{},isLead:o.isLead},I=>{m.push(`${I.provider} terminal ignored model=${I.model}: ${I.reason}`)},k),d=await y,d}catch(T){throw _=T,T}finally{if(R&&(process.removeListener("SIGINT",O),process.removeListener("SIGTERM",A)),!f){f=!0;let T=[];try{E(k=>{v(k),x({status:d===0?"done":"error",exit_code:d,result_summary:d===0?"terminal session ended":null,error:d===0?null:`terminal exited with code ${d??"unknown"}`,...m.length>0?{config_warnings:JSON.stringify(m)}:{}},k)},T)}catch(k){T.push(k instanceof Error?k.message:String(k))}T.length>0&&(h=Error(T.join("; ")))}if(h){if(_===void 0)throw h;try{t.stderr.write("error: terminal cleanup: "+h.message+`
|
|
2412
2413
|
`)}catch{}}}}function eG(t,e,n=process.env,r=process.pid){try{return t.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:e.teamfile,from_identity:`${e.teamfile}:terminal`,target_teamfile:e.teamfile,target_alias:e.alias,root_teamfile:e.teamfile,cwd:e.sessiondir,command:`lmctl terminal ${e.teamfile} ${e.alias}`,holder_pid:r,launch_source:"terminal",parent_invocation_id:ou(n.LMCTL_INVOCATION_ID),meta:JSON.stringify({provider:e.provider,sessionid:e.sessionid,...e.model!==void 0?{model:e.model}:{}})}).id}catch{return null}}async function tG(t,e,n,r){let{provider:s,sessionid:i,sessiondir:o,model:a}=e;if(!oy(s))return sr(t,`no resume incantation for provider "${s}"`);if(!Ox.test(i))return sr(t,"refusing to resume: malformed sessionid");let l=Lx(s,i,{isLead:e.isLead,model:a,onModelIgnored:f=>{let h=`warning: ${f.provider} terminal ignored model=${f.model}: ${f.reason}`;t.stderr.write(`${h}
|
|
2413
2414
|
`),wt({event:"model_ignored",provider:f.provider,model:f.model,reason:f.reason}),n?.(f)}});if(l===null||l.length===0)return sr(t,`no resume incantation for provider "${s}"`);let c=He(r?.env??t.env??process.env,o,i,"terminal"),u=await Mx(s,{binary:l[0],cwd:o,env:c,signal:r?.signal});if(r?.signal?.aborted){let f=r.signal.reason==="SIGINT"?"SIGINT":"SIGTERM";return r.cancel?.(f),f==="SIGINT"?130:143}let[d,...m]=l,p=u.kind==="use-binary"?u.binary:d;return u.message&&t.stderr.write(u.message+`
|
|
2414
2415
|
`),await new Promise(f=>{if(r?.signal?.aborted){let R=r.signal.reason==="SIGINT"?"SIGINT":"SIGTERM";return r.cancel?.(R),f(R==="SIGINT"?130:143)}let h=r?.streams,g=h?[h.stdin,h.stdout,h.stderr].map(R=>R.fd):void 0,y=g?.every(R=>typeof R=="number"),b=QX(p,m,{stdio:h?y?g:["pipe","pipe","pipe"]:"inherit",cwd:o,env:c}),_=h?.stdin?.readableFlowing;h&&!y&&(h.stdin.pipe(b.stdin),b.stdout?.pipe(h.stdout,{end:!1}),b.stderr?.pipe(h.stderr,{end:!1}));let v=!1,E=R=>{if(!v){v=!0;try{r?.cancel?.(R)}catch{}{try{b.kill(R)}catch{}be(b,{stdinEnd:!1,softDelayMs:0,killDelayMs:100}).catch(()=>{})}}},x=()=>E(r?.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r&&(r.stop=E);let S=()=>{r?.signal?.removeEventListener("abort",x),h&&!y&&(h.stdin.unpipe(b.stdin),_||h.stdin.pause(),b.stdout?.unpipe(h.stdout),b.stderr?.unpipe(h.stderr))};r?.signal?.addEventListener("abort",x,{once:!0}),r?.signal?.aborted&&x(),b.stdin?.on("error",()=>{}),b.on("error",R=>{S(),f(sr(t,`failed to launch ${p}: ${R.message}`))}),b.on("exit",(R,N)=>{S(),r&&(r.signalObserved=N);let O=R??(N?128+(YX.signals[N]??1):1),A=Px(s);A&&O!==0&&O!==130&&O!==143&&!v&&!r?.signal?.aborted&&t.stderr.write(s+" exited with status "+O+". "+A+`
|
|
2415
|
-
`),f(O)})})}var kC=L(()=>{"use strict";Us();Zt();Yi();ir();EC();Rn();kn();mn();fd();tr();kd();Ya();TC();Re();Ds()});import{resolve as nG}from"node:path";async function RC(t,e,n){let r=(l,c)=>({status:"error",error:l,errorCode:c,code:null,signal:null}),s,i=!1,o,a;try{let l=
|
|
2416
|
-
`)||`terminal exited with code ${m.code}`,code:m.code,signal:m.signal}}catch(l){return o?.cleanupError?.()&&(i=!0),r(G(l),"provider")}finally{i||s?.()}}var xC=L(()=>{"use strict";kC();en();rn();yt()});import{isAbsolute as rG,resolve as sG}from"node:path";function Wd(t){return Number.isFinite(t)&&Math.abs(t)<=iG}function oG(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(Po.includes(e))return e;if(e==="SQLITE_BUSY"||e==="SQLITE_LOCKED")return"busy";if(e==="SQLITE_READONLY"||e.startsWith("SQLITE_READONLY")||e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT"||e==="SQLITE_CANTOPEN")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}let n=t.message;if(typeof n=="string"){if(n.includes("readonly database")||n.includes("SQLITE_READONLY"))return"read";if(n.includes("database is locked")||n.includes("SQLITE_BUSY"))return"busy"}}return"internal"}function Ky(t,e=Date.now()){if(t===void 0)return{windowMs:qd};let n=/^(\d+)([smhd])$/.exec(t);if(n!==null){let i=Number(n[1]),o=n[2],l=(o==="s"?i:o==="m"?i*60:o==="h"?i*3600:i*86400)*1e3;return!Number.isFinite(l)||l<0||!Wd(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!Wd(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return Wd(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function Hd(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Vy(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return Jy;let s=e.get(n);if(s===void 0){try{s=qt(n)}catch{s=null}e.set(n,s)}return s===null?Jy:nu(s,r)?.model??Jy}async function IC(t,e={}){let n=pe(t);if(n)return{status:"error",error:n.error,code:n.code,running:[],dead:[],idle:[]};if(e!=null){if(typeof e!="object"||Array.isArray(e))return{status:"error",error:"Options must be a map",code:"invalid_argument",running:[],dead:[],idle:[]};let i=yr("listRunning");if(i.length>0){for(let o of Object.keys(e))if(!i.includes(o))return{status:"error",error:`Unknown option: ${o}`,code:"invalid_argument",running:[],dead:[],idle:[]}}if(e.teamfile!==void 0&&(typeof e.teamfile!="string"||!e.teamfile.trim()))return{status:"error",error:"teamfile must be a nonempty string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.member!==void 0&&typeof e.member!="string")return{status:"error",error:"member must be a string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.tree!==void 0&&typeof e.tree!="boolean")return{status:"error",error:"tree must be a boolean",code:"invalid_argument",running:[],dead:[],idle:[]}}let r=t.clock(),s=qd;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!Wd(r-e.since))return{status:"error",error:"since must be a non-negative number of milliseconds within representable date range",code:"invalid_argument",running:[],dead:[],idle:[]};s=e.since}else if(typeof e.since=="string"){let i=Ky(e.since,r);if("error"in i)return{status:"error",error:i.error,code:"invalid_argument",running:[],dead:[],idle:[]};s=i.windowMs}else return{status:"error",error:"since must be a duration string or number",code:"invalid_argument",running:[],dead:[],idle:[]};try{let i=un(t),o=e?.teamfile!==void 0?rG(e.teamfile)?e.teamfile:sG(t.cwd,e.teamfile):void 0,a=o!==void 0?Ot(o,i):void 0,l=e?.member!==void 0?e.member.toLowerCase():void 0,c=_=>!(a!==void 0&&_.target_teamfile!==a||l!==void 0&&(_.target_alias??"").toLowerCase()!==l),u=i.listAllRunningTrackedInvocations().filter(c),d=new Map,m=[],p=[];for(let _ of u){let v=Dc(_),E=r-new Date(_.started_at).getTime(),x={id:_.id,kind:_.kind,origin:_.origin,from_identity:_.from_identity,target:Hd(_),model:Vy(_,d),started_at:_.started_at,parent_invocation_id:_.parent_invocation_id};if(v==="dead"){if(Cy(i,_)!==null)continue;p.push({...x,stale_for_ms:E})}else m.push({...x,running_for_ms:E,holder_liveness:v??"unknown"})}let f=new Set(u.map(Hd).filter(_=>_!==null)),h=new Date(r-s).toISOString(),g=i.listRecentlyFinishedTrackedInvocations(h).filter(c),y=new Set,b=[];for(let _ of g){let v=Hd(_);v===null||f.has(v)||y.has(v)||(y.add(v),b.push({id:_.id,kind:_.kind,origin:_.origin,from_identity:_.from_identity,target:v,model:Vy(_,d),status:_.status,started_at:_.started_at,ended_at:_.ended_at,idle_ms:r-new Date(_.ended_at).getTime(),ran_ms:new Date(_.ended_at).getTime()-new Date(_.started_at).getTime(),error:_.error,parent_invocation_id:_.parent_invocation_id}))}if(e?.tree===!0){let _=new Set([...m.map(E=>E.id),...p.map(E=>E.id),...b.map(E=>E.id)]),v=[..._];for(;v.length>0;){let E=i.listFinishedTrackedInvocationChildren(v,h).filter(x=>!_.has(x.id)&&c(x));if(E.length===0)break;v=[];for(let x of E){_.add(x.id),v.push(x.id);let S=Hd(x);b.push({id:x.id,kind:x.kind,origin:x.origin,from_identity:x.from_identity,target:S,model:Vy(x,d),status:x.status,started_at:x.started_at,ended_at:x.ended_at,idle_ms:r-new Date(x.ended_at).getTime(),ran_ms:new Date(x.ended_at).getTime()-new Date(x.started_at).getTime(),error:x.error,parent_invocation_id:x.parent_invocation_id})}}}return{status:"ok",error:null,running:m,dead:p,idle:b}}catch(i){return{status:"error",error:i instanceof Error?i.message:String(i),code:oG(i),running:[],dead:[],idle:[]}}}var qd,iG,Jy,AC=L(()=>{"use strict";en();rn();zn();tr();xd();kn();$s();qd=24*60*60*1e3,iG=864e13;Jy="default"});var CC={};jn(CC,{DAY_MS:()=>qd,LMCTL_API_VERSION:()=>LV,LMCTL_ERROR_CODES:()=>Po,LMCTL_OPERATIONS:()=>ht,LMCTL_PROFILE_VALUE_NAMES:()=>GL,LMCTL_PROPERTY_KEYS:()=>mp,LMCTL_PROPERTY_TABLES:()=>JL,LMCTL_REMOVED_GLOBALS:()=>pp,LMCTL_RESULT_FIELDS:()=>XL,NativeSessionManager:()=>Ud,agentMessage:()=>kA,batchTurn:()=>lC,closeBatch:()=>cC,closeNativeSession:()=>zs,createLmctlContext:()=>gf,deleteSession:()=>TI,fail:()=>H,finalizeBatchSync:()=>iC,finalizeNativeSessionSync:()=>gC,getSession:()=>EI,inspectBatch:()=>oC,isLmctlContext:()=>Ci,lintTeam:()=>_q,listMembers:()=>hq,listRunning:()=>IC,listSessions:()=>wI,loadProfile:()=>C$,loadProperties:()=>N$,nativeSessionClose:()=>bC,nativeSessionRequest:()=>vC,nativeSessionTurn:()=>io,ok:()=>ge,openNativeSession:()=>so,openTeamBatch:()=>aC,openTerminal:()=>RC,parseRunningSince:()=>Ky,profileValues:()=>A$,promptAgent:()=>gI,promptMember:()=>YA,promptReservedAgent:()=>_I,readPrompts:()=>Eq,readRatelimits:()=>H2,releaseSession:()=>bI,reserveSession:()=>vI,resolveMember:()=>yq,resolveProfilePath:()=>If,seedErrorCollector:()=>cI,seedTeam:()=>vq,sessionAdmission:()=>yI});var NC=L(()=>{"use strict";yt();en();UT();zn();uI();dI();SI();EA();fy();RA();QA();uC();jd();wC();xC();AC();Xy()});var PC={};jn(PC,{createLmctlHostModule:()=>MC,default:()=>bG});import{AsyncLocalStorage as aG}from"node:async_hooks";import{randomUUID as lG}from"node:crypto";import{types as cG}from"node:util";import{createInterface as uG}from"node:readline";import{Writable as dG}from"node:stream";import{readFileSync as mG}from"node:fs";import{resolve as pG}from"node:path";import{homedir as fG}from"node:os";function OC(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(Po.includes(e))return e;if(e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}}return"internal"}function _G(t){if(t.name==="lm_log"||t.name==="lm_error")return{...t,arity:{min:2},params:[zy,...t.params??[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]],readonly:t.name==="lm_error",dryControl:t.name==="lm_error"?"error":"output"};if(t.name==="lm_exit")return{...t,arity:{min:0,max:2},params:[{name:"code",type:"number",optional:!0},zy],readonly:!0};if(Xd.has(t.name)||t.name==="lm_prompt"||t.name==="lm_agent"||t.name==="lm_agent_message"){let e=t.params??[{name:"file",type:"string"}],n=typeof t.arity=="number"?t.arity:t.arity.min;return{...t,arity:{min:n,max:e.length+1},params:[...e,zy],readonly:Xd.has(t.name)}}return t}function MC(t={}){let e={stdout:t.stdout??(r=>process.stdout.write(r)),stderr:t.stderr??(r=>process.stderr.write(r))},n={name:"lmctl",declarations:vG,async activate(r){let s=t.api??await Promise.resolve().then(()=>(NC(),CC)),i,o=new aG,a=()=>o.getStore()??e,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new Map,m=new Map,p=!1,f=()=>{if(i)return i;let w={...r.env};!w.HOME&&!w.LMCTL_HOME&&!w.LMCTL_DB&&(w.HOME=fG());let T=s.createLmctlContext({env:w,cwd:r.cwd,pid:process.pid,onProgress:(k,I)=>a()[I??"stderr"](k),onWarning:k=>a().stderr(k)});if(T.status!=="ok")throw Error(T.error);return i=T,t.onContext?.(i),i},h={},g=()=>{let w=s.loadProperties(f());if(w.status!=="ok")throw Error(w.error);return{path:w.path,properties:w.properties,hint:"Define it in "+w.path+" or run lmctl init"}},y=()=>i&&!i.closed&&i.finalizeSync(r.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r.signal?.addEventListener("abort",y,{once:!0}),r.signal?.aborted&&y();let b=async(w,T,k={},I)=>{let C=k&&typeof k=="object"&&!Array.isArray(k)?{permissionMode:k.permissionMode??"yolo",idleTimeoutMs:k.idleTimeoutMs??void 0}:k,M=I?await s.promptReservedAgent(f(),I,w,T,C):await s.promptAgent(f(),w,T,C);if(w&&typeof w=="object"&&M.sessionid&&M.status!=="busy"&&(w.sessionid=M.sessionid),w?.sessionid&&M.status!=="busy"){let D=JSON.stringify([w.provider,w.sessionid]),j=m.get(D)??{lines:[],options:{}};j.lines.push(`You: ${T}`),M.reply&&j.lines.push(`Agent: ${M.reply}`),M.error&&j.lines.push(`${M.status}: ${M.error}`),j.options={...k},m.set(D,j)}return{status:M.status,reply:M.reply,error:M.error?`lm_agent: ${M.error}`:null,message_id:null,team_chat_log_id:null}},_=(w,T)=>new Error(`${w}: ${T.error??"operation failed"}`),v=(w,T)=>{if(T.status!=="ok")throw _(w,T);return T},E=(w,T="lm_batch_turn",k=!1)=>{if(w!==null&&typeof w=="object"&&cG.isProxy(w))throw Error("Resource batch id cannot be read from a proxy");let I=w!==null&&typeof w=="object"?Object.getOwnPropertyDescriptor(w,"id"):void 0;if(I&&!("value"in I))throw Error("Resource batch id must be an own data property, not an accessor");let C=typeof w=="string"?w:I?.value,M=typeof C=="string"?d.get(C):void 0,D=Lo();if(!M){if(typeof C=="string"&&/^run-[0-9]+-[0-9]+\//.test(C)&&D&&!C.startsWith(D.runtime.token+"/"))throw Error("Resource batch "+C+" belongs to another run: "+T);return}if(!D)throw Error("Resource batch "+C+" requires an authorized script invocation");return D.runtime.authorizeRaw(M,D.scope,T,k),M},x=w=>{let T=Lo();if(!T)throw Error("lm_batch_open requires an authorized script invocation");w.id=T.runtime.token+"/"+lG(),w.kind="lmctl batch",w.closeDeadlineMs=5e3;let k;return w.close=(I={})=>{if(k)return k;let C,M;return k=new Promise((D,j)=>{C=D,M=j}),(async()=>{let D=l.get(w);if(D){v("lm_batch_close",await s.closeNativeSession(f(),D));return}let j=c.get(w);if(j){j.closed=!0;return}let F=I.explicit??[],Z=I.reason==="cancelled"?"cancelled":F[0]??(w.observedError?"error":I.reason??"done");v("lm_batch_close",await s.closeBatch(f(),u.get(w),{status:Z==="done"?"done":Z==="cancelled"?"cancelled":"error",error:F[1]??I.error}))})().then(C,M),k},w.finalizeSync=()=>{let I=f();if(I.closed){let C=I.finalizeSync("SIGTERM");if(C.errors.length)throw Error(C.errors.join(`
|
|
2416
|
+
`),f(O)})})}var kC=L(()=>{"use strict";Us();Zt();Yi();ir();EC();Rn();kn();mn();fd();tr();kd();Ya();TC();Re();Ds()});import{resolve as nG}from"node:path";async function RC(t,e,n){let r=(l,c)=>({status:"error",error:l,errorCode:c,code:null,signal:null}),s,i=!1,o,a;try{let l=fe(t);if(l)return r(l.error,l.code);if(!t.interactive||t.env.LMCTL_NON_INTERACTIVE==="1")return r("terminal opens an interactive TUI; non-interactive mode is enabled","noninteractive");if(!e||typeof e.teamfile!="string"||typeof e.alias!="string"||!n||typeof n.stdin?.pipe!="function"||typeof n.stdout?.write!="function"||typeof n.stderr?.write!="function")return r("Terminal requires teamfile, alias and caller streams","invalid_argument");let c={...e};o={env:{...t.env,LMCTL_DB:t.dbPath},pid:t.pid,signal:t.signal,streams:n,onResource(f){a=f,t.closed&&f.finalizeSync("SIGTERM")}},s=En(t,{async close(){try{await a?.close()}catch(f){throw i=!0,f}},finalizeSync(f){try{a?.finalizeSync(f)}catch(h){throw i=!0,h}}});let u=[],d=mt(t,(f,h)=>{h==="stderr"&&f.startsWith("error:")&&u.push(f.replace(/^error:\s*/,"").trim())}),m=await SC({...d,stdin:n.stdin},nG(t.cwd,c.teamfile),c.alias,un(t),o);return o.cleanupError?.()&&(i=!0),{status:m.code===0&&!m.signal?"ok":"error",error:m.signal?`terminal terminated by ${m.signal}`:m.code===0?null:u.join(`
|
|
2417
|
+
`)||`terminal exited with code ${m.code}`,code:m.code,signal:m.signal}}catch(l){return o?.cleanupError?.()&&(i=!0),r(V(l),"provider")}finally{i||s?.()}}var xC=L(()=>{"use strict";kC();en();rn();yt()});import{isAbsolute as rG,resolve as sG}from"node:path";function Wd(t){return Number.isFinite(t)&&Math.abs(t)<=iG}function oG(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(Po.includes(e))return e;if(e==="SQLITE_BUSY"||e==="SQLITE_LOCKED")return"busy";if(e==="SQLITE_READONLY"||e.startsWith("SQLITE_READONLY")||e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT"||e==="SQLITE_CANTOPEN")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}let n=t.message;if(typeof n=="string"){if(n.includes("readonly database")||n.includes("SQLITE_READONLY"))return"read";if(n.includes("database is locked")||n.includes("SQLITE_BUSY"))return"busy"}}return"internal"}function Ky(t,e=Date.now()){if(t===void 0)return{windowMs:qd};let n=/^(\d+)([smhd])$/.exec(t);if(n!==null){let i=Number(n[1]),o=n[2],l=(o==="s"?i:o==="m"?i*60:o==="h"?i*3600:i*86400)*1e3;return!Number.isFinite(l)||l<0||!Wd(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!Wd(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return Wd(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function Hd(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Vy(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return Jy;let s=e.get(n);if(s===void 0){try{s=qt(n)}catch{s=null}e.set(n,s)}return s===null?Jy:nu(s,r)?.model??Jy}async function IC(t,e={}){let n=fe(t);if(n)return{status:"error",error:n.error,code:n.code,running:[],dead:[],idle:[]};if(e!=null){if(typeof e!="object"||Array.isArray(e))return{status:"error",error:"Options must be a map",code:"invalid_argument",running:[],dead:[],idle:[]};let i=yr("listRunning");if(i.length>0){for(let o of Object.keys(e))if(!i.includes(o))return{status:"error",error:`Unknown option: ${o}`,code:"invalid_argument",running:[],dead:[],idle:[]}}if(e.teamfile!==void 0&&(typeof e.teamfile!="string"||!e.teamfile.trim()))return{status:"error",error:"teamfile must be a nonempty string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.member!==void 0&&typeof e.member!="string")return{status:"error",error:"member must be a string",code:"invalid_argument",running:[],dead:[],idle:[]};if(e.tree!==void 0&&typeof e.tree!="boolean")return{status:"error",error:"tree must be a boolean",code:"invalid_argument",running:[],dead:[],idle:[]}}let r=t.clock(),s=qd;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!Wd(r-e.since))return{status:"error",error:"since must be a non-negative number of milliseconds within representable date range",code:"invalid_argument",running:[],dead:[],idle:[]};s=e.since}else if(typeof e.since=="string"){let i=Ky(e.since,r);if("error"in i)return{status:"error",error:i.error,code:"invalid_argument",running:[],dead:[],idle:[]};s=i.windowMs}else return{status:"error",error:"since must be a duration string or number",code:"invalid_argument",running:[],dead:[],idle:[]};try{let i=un(t),o=e?.teamfile!==void 0?rG(e.teamfile)?e.teamfile:sG(t.cwd,e.teamfile):void 0,a=o!==void 0?Ot(o,i):void 0,l=e?.member!==void 0?e.member.toLowerCase():void 0,c=_=>!(a!==void 0&&_.target_teamfile!==a||l!==void 0&&(_.target_alias??"").toLowerCase()!==l),u=i.listAllRunningTrackedInvocations().filter(c),d=new Map,m=[],p=[];for(let _ of u){let v=Dc(_),E=r-new Date(_.started_at).getTime(),x={id:_.id,kind:_.kind,origin:_.origin,from_identity:_.from_identity,target:Hd(_),model:Vy(_,d),started_at:_.started_at,parent_invocation_id:_.parent_invocation_id};if(v==="dead"){if(Cy(i,_)!==null)continue;p.push({...x,stale_for_ms:E})}else m.push({...x,running_for_ms:E,holder_liveness:v??"unknown"})}let f=new Set(u.map(Hd).filter(_=>_!==null)),h=new Date(r-s).toISOString(),g=i.listRecentlyFinishedTrackedInvocations(h).filter(c),y=new Set,b=[];for(let _ of g){let v=Hd(_);v===null||f.has(v)||y.has(v)||(y.add(v),b.push({id:_.id,kind:_.kind,origin:_.origin,from_identity:_.from_identity,target:v,model:Vy(_,d),status:_.status,started_at:_.started_at,ended_at:_.ended_at,idle_ms:r-new Date(_.ended_at).getTime(),ran_ms:new Date(_.ended_at).getTime()-new Date(_.started_at).getTime(),error:_.error,parent_invocation_id:_.parent_invocation_id}))}if(e?.tree===!0){let _=new Set([...m.map(E=>E.id),...p.map(E=>E.id),...b.map(E=>E.id)]),v=[..._];for(;v.length>0;){let E=i.listFinishedTrackedInvocationChildren(v,h).filter(x=>!_.has(x.id)&&c(x));if(E.length===0)break;v=[];for(let x of E){_.add(x.id),v.push(x.id);let S=Hd(x);b.push({id:x.id,kind:x.kind,origin:x.origin,from_identity:x.from_identity,target:S,model:Vy(x,d),status:x.status,started_at:x.started_at,ended_at:x.ended_at,idle_ms:r-new Date(x.ended_at).getTime(),ran_ms:new Date(x.ended_at).getTime()-new Date(x.started_at).getTime(),error:x.error,parent_invocation_id:x.parent_invocation_id})}}}return{status:"ok",error:null,running:m,dead:p,idle:b}}catch(i){return{status:"error",error:i instanceof Error?i.message:String(i),code:oG(i),running:[],dead:[],idle:[]}}}var qd,iG,Jy,AC=L(()=>{"use strict";en();rn();zn();tr();xd();kn();$s();qd=24*60*60*1e3,iG=864e13;Jy="default"});var CC={};jn(CC,{DAY_MS:()=>qd,LMCTL_API_VERSION:()=>LV,LMCTL_ERROR_CODES:()=>Po,LMCTL_OPERATIONS:()=>ht,LMCTL_PROFILE_VALUE_NAMES:()=>GL,LMCTL_PROPERTY_KEYS:()=>mp,LMCTL_PROPERTY_TABLES:()=>JL,LMCTL_REMOVED_GLOBALS:()=>pp,LMCTL_RESULT_FIELDS:()=>XL,NativeSessionManager:()=>Ud,agentMessage:()=>kA,batchTurn:()=>lC,closeBatch:()=>cC,closeNativeSession:()=>zs,createLmctlContext:()=>gf,deleteSession:()=>TI,fail:()=>H,finalizeBatchSync:()=>iC,finalizeNativeSessionSync:()=>gC,getSession:()=>EI,inspectBatch:()=>oC,isLmctlContext:()=>Ci,lintTeam:()=>_q,listMembers:()=>hq,listRunning:()=>IC,listSessions:()=>wI,loadProfile:()=>C$,loadProperties:()=>N$,nativeSessionClose:()=>bC,nativeSessionRequest:()=>vC,nativeSessionTurn:()=>io,ok:()=>ge,openNativeSession:()=>so,openTeamBatch:()=>aC,openTerminal:()=>RC,parseRunningSince:()=>Ky,profileValues:()=>A$,promptAgent:()=>gI,promptMember:()=>YA,promptReservedAgent:()=>_I,readPrompts:()=>Eq,readRatelimits:()=>H2,releaseSession:()=>bI,reserveSession:()=>vI,resolveMember:()=>yq,resolveProfilePath:()=>If,seedErrorCollector:()=>cI,seedTeam:()=>vq,sessionAdmission:()=>yI});var NC=L(()=>{"use strict";yt();en();UT();zn();uI();dI();SI();EA();fy();RA();QA();uC();jd();wC();xC();AC();Xy()});var PC={};jn(PC,{createLmctlHostModule:()=>MC,default:()=>bG});import{AsyncLocalStorage as aG}from"node:async_hooks";import{randomUUID as lG}from"node:crypto";import{types as cG}from"node:util";import{createInterface as uG}from"node:readline";import{Writable as dG}from"node:stream";import{readFileSync as mG}from"node:fs";import{resolve as pG}from"node:path";import{homedir as fG}from"node:os";function OC(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(Po.includes(e))return e;if(e==="EACCES"||e==="EPERM"||e==="EISDIR")return"read";if(e==="ENOENT")return"missing";if(e==="ETIMEDOUT"||e==="ECANCELED"||e==="ABORT_ERR")return"cancelled"}}return"internal"}function _G(t){if(t.name==="lm_log"||t.name==="lm_error")return{...t,arity:{min:2},params:[zy,...t.params??[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]],readonly:t.name==="lm_error",dryControl:t.name==="lm_error"?"error":"output"};if(t.name==="lm_exit")return{...t,arity:{min:0,max:2},params:[{name:"code",type:"number",optional:!0},zy],readonly:!0};if(Xd.has(t.name)||t.name==="lm_prompt"||t.name==="lm_agent"||t.name==="lm_agent_message"){let e=t.params??[{name:"file",type:"string"}],n=typeof t.arity=="number"?t.arity:t.arity.min;return{...t,arity:{min:n,max:e.length+1},params:[...e,zy],readonly:Xd.has(t.name)}}return t}function MC(t={}){let e={stdout:t.stdout??(r=>process.stdout.write(r)),stderr:t.stderr??(r=>process.stderr.write(r))},n={name:"lmctl",declarations:vG,async activate(r){let s=t.api??await Promise.resolve().then(()=>(NC(),CC)),i,o=new aG,a=()=>o.getStore()??e,l=new WeakMap,c=new WeakMap,u=new WeakMap,d=new Map,m=new Map,p=!1,f=()=>{if(i)return i;let w={...r.env};!w.HOME&&!w.LMCTL_HOME&&!w.LMCTL_DB&&(w.HOME=fG());let T=s.createLmctlContext({env:w,cwd:r.cwd,pid:process.pid,onProgress:(k,I)=>a()[I??"stderr"](k),onWarning:k=>a().stderr(k)});if(T.status!=="ok")throw Error(T.error);return i=T,t.onContext?.(i),i},h={},g=()=>{let w=s.loadProperties(f());if(w.status!=="ok")throw Error(w.error);return{path:w.path,properties:w.properties,hint:"Define it in "+w.path+" or run lmctl init"}},y=()=>i&&!i.closed&&i.finalizeSync(r.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r.signal?.addEventListener("abort",y,{once:!0}),r.signal?.aborted&&y();let b=async(w,T,k={},I)=>{let C=k&&typeof k=="object"&&!Array.isArray(k)?{permissionMode:k.permissionMode??"yolo",idleTimeoutMs:k.idleTimeoutMs??void 0}:k,M=I?await s.promptReservedAgent(f(),I,w,T,C):await s.promptAgent(f(),w,T,C);if(w&&typeof w=="object"&&M.sessionid&&M.status!=="busy"&&(w.sessionid=M.sessionid),w?.sessionid&&M.status!=="busy"){let D=JSON.stringify([w.provider,w.sessionid]),j=m.get(D)??{lines:[],options:{}};j.lines.push(`You: ${T}`),M.reply&&j.lines.push(`Agent: ${M.reply}`),M.error&&j.lines.push(`${M.status}: ${M.error}`),j.options={...k},m.set(D,j)}return{status:M.status,reply:M.reply,error:M.error?`lm_agent: ${M.error}`:null,message_id:null,team_chat_log_id:null}},_=(w,T)=>new Error(`${w}: ${T.error??"operation failed"}`),v=(w,T)=>{if(T.status!=="ok")throw _(w,T);return T},E=(w,T="lm_batch_turn",k=!1)=>{if(w!==null&&typeof w=="object"&&cG.isProxy(w))throw Error("Resource batch id cannot be read from a proxy");let I=w!==null&&typeof w=="object"?Object.getOwnPropertyDescriptor(w,"id"):void 0;if(I&&!("value"in I))throw Error("Resource batch id must be an own data property, not an accessor");let C=typeof w=="string"?w:I?.value,M=typeof C=="string"?d.get(C):void 0,D=Lo();if(!M){if(typeof C=="string"&&/^run-[0-9]+-[0-9]+\//.test(C)&&D&&!C.startsWith(D.runtime.token+"/"))throw Error("Resource batch "+C+" belongs to another run: "+T);return}if(!D)throw Error("Resource batch "+C+" requires an authorized script invocation");return D.runtime.authorizeRaw(M,D.scope,T,k),M},x=w=>{let T=Lo();if(!T)throw Error("lm_batch_open requires an authorized script invocation");w.id=T.runtime.token+"/"+lG(),w.kind="lmctl batch",w.closeDeadlineMs=5e3;let k;return w.close=(I={})=>{if(k)return k;let C,M;return k=new Promise((D,j)=>{C=D,M=j}),(async()=>{let D=l.get(w);if(D){v("lm_batch_close",await s.closeNativeSession(f(),D));return}let j=c.get(w);if(j){j.closed=!0;return}let $=I.explicit??[],Z=I.reason==="cancelled"?"cancelled":$[0]??(w.observedError?"error":I.reason??"done");v("lm_batch_close",await s.closeBatch(f(),u.get(w),{status:Z==="done"?"done":Z==="cancelled"?"cancelled":"error",error:$[1]??I.error}))})().then(C,M),k},w.finalizeSync=()=>{let I=f();if(I.closed){let C=I.finalizeSync("SIGTERM");if(C.errors.length)throw Error(C.errors.join(`
|
|
2417
2418
|
`));return}if(l.has(w))v("lm_batch_close",s.finalizeNativeSessionSync(I,l.get(w)));else if(u.has(w))v("lm_batch_close",s.finalizeBatchSync(I,u.get(w)));else{let C=c.get(w);C&&(C.closed=!0)}},d.set(w.id,w),w},S=w=>w&&typeof w=="object"?u.get(w):void 0,R=w=>{let T=S(w);if(T){let k=v("lm_batch_open",s.inspectBatch(f(),T)),{status:I,error:C,...M}=k;Object.assign(w,{...M,id:w.close?w.id:M.id})}},O={lm_exit:(w=0)=>{let T=Number(w);throw new $t(Number.isFinite(T)&&T>=0&&T<=255?Math.floor(T):1)},lm_log:(w,...T)=>{let k=LC(T);return a().stderr(k.endsWith(`
|
|
2418
2419
|
`)?k:k+`
|
|
2419
2420
|
`),k},lm_error:(w,...T)=>{let k=LC(T);return o.getStore()?.errors?.push(k),r.reportRecordedError(k),a().stderr("error: "+k+`
|
|
2420
2421
|
`),k},lm_read_prompts:async(w,T=!1)=>{let k=await s.readPrompts(f(),w,{single:T});return{status:k.status,error:k.error?`lm_read_prompts: ${k.error}`:null,prompts:"prompts"in k?k.prompts:[]}},lm_read_paragraphs:async w=>{let T=await s.readPrompts(f(),w,{single:!1});return{status:T.status,error:T.error?`lm_read_paragraphs: ${T.error}`:null,prompts:"prompts"in T?T.prompts:[]}},lm_members:async w=>{let T=await s.listMembers(f(),w);return{status:T.status,error:T.error?`lm_members: ${T.error}`:null,members:"members"in T?T.members:[]}},lm_member:async(w,T)=>{try{let k=await s.resolveMember(f(),w,T);if(k.status==="ok")return{status:"ok",error:null,member:k.member,isLead:k.isLead,teamfile:k.teamfile};let I="code"in k?k.code:k.errorCode;return{status:k.status,error:k.error?`lm_member: ${k.error}`:null,...I?{code:I}:{}}}catch(k){return{status:"error",error:`lm_member: ${k instanceof Error?k.message:String(k)}`}}},lm_lint:async w=>{if(typeof w!="string"||!w)throw Error("lm_lint: teamfile must be nonempty");let T=await s.lintTeam(f(),w);return{status:T.status==="ok"?"ok":"error",error:T.error,errors:"errors"in T?T.errors:[{alias:"",message:`lm_lint: ${T.error}`}],warnings:"warnings"in T?T.warnings:[],counts:"counts"in T?T.counts:{errors:1,warnings:0}}},lm_seed:async(w,T={})=>{if(typeof w!="string"||!w)throw Error("lm_seed: teamfile must be nonempty");if(!os(T))throw Error("lm_seed: options must be a map");let k=a(),I=await o.run({...k,stderr:M=>{M.startsWith("error:")||k.stderr(M)}},()=>s.seedTeam(f(),w,os(T)?{preamble:T.preamble}:T)),C="code"in I?I.code:void 0;return C==="provider"&&k.stderr(`error: lm_seed: ${I.error}
|
|
2421
|
-
`),{status:I.status,error:I.error?`lm_seed: ${I.error}`:null,...C?{code:C}:{},seeded:"seeded"in I&&Array.isArray(I.seeded)?I.seeded:[]}},lm_agent:(w,T,k={},I=!1)=>I?Yy():b(w,T,k),lm_agent_message:async(w,T,k={},I=!1)=>{if(I)return{...Yy(),message:null};let C=await b(w,T,k),M=C.status==="ok"&&w?.sessionid?await s.agentMessage(f(),w.provider,w.sessionid,C.reply):null;return{...C,message:M}},lm_prompt:async(w,T,k,I={},C=!1)=>{if(C)return Yy();try{let M=await s.promptMember(f(),{teamfile:w,alias:T,prompt:k,permissionMode:I?.permissionMode??"yolo",idleTimeoutMs:I?.idleTimeoutMs,messageType:I?.messageType});return{status:M.status,reply:M.reply,error:M.error?`lm_prompt: ${M.error}`:null,message_id:M.messageId,team_chat_log_id:M.teamChatLogId}}catch(M){return{status:"error",reply:"",error:`lm_prompt: ${M instanceof Error?M.message:String(M)}`,message_id:null,team_chat_log_id:null}}},lm_session_list:async(w={})=>{if(w!==void 0&&!os(w))throw Error("lm_session_list: options must be a map");let T=await s.listSessions(f(),os(w)?{provider:w.provider,workspace:w.sessiondir,all:w.all}:w),k="code"in T?T.code:void 0;return{status:T.status,error:T.error?`lm_session_list: ${T.error}`:null,...k?{code:k}:{},sessions:"sessions"in T?T.sessions:[]}},lm_session_get:async w=>{try{let T=await s.getSession(f(),w);if(T.status==="ok")return{status:"ok",error:null,messages:T.messages};if(T.status==="not_found")return{status:"not_found",error:null};let k="code"in T&&T.code?T.code:void 0;return{status:T.status,error:T.error?`lm_session_get: ${T.error}`:null,...k?{code:k}:{}}}catch(T){let k=OC(T);return{status:"error",error:`lm_session_get: ${T instanceof Error?T.message:String(T)}`,code:k}}},lm_session_delete:async(w,T={})=>{let k=await s.deleteSession(f(),w,{force:T?.force});return k.status==="deleted"&&(m.delete(JSON.stringify([w.provider,w.sessionid])),w.sessionid=null),{status:k.status,error:k.error?`lm_session_delete: ${k.error}`:null}},lm_session_turn:async(w,T,k={})=>{try{let I=await s.nativeSessionRequest(f(),w,T,k);return{status:I.status,reply:I.reply??"",error:I.error?`lm_session_turn: ${I.error}`:null,message_id:I.messageId??null,team_chat_log_id:I.teamChatLogId??null,..."code"in I&&I.code?{code:I.code}:{},..."outcome"in I?{outcome:I.outcome,service_epoch:I.service_epoch,connection_epoch:I.connection_epoch,connection_state:I.connection_state}:{}}}catch(I){return{status:"error",reply:"",error:`lm_session_turn: ${I instanceof Error?I.message:String(I)}`,code:"internal",message_id:null,team_chat_log_id:null}}},lm_session_close:async w=>{try{let T=await s.nativeSessionClose(f(),w);return{status:T.status,error:T.error?`lm_session_close: ${T.error}`:null,..."code"in T&&T.code?{code:T.code}:{},..."outcome"in T?{outcome:T.outcome,service_epoch:T.service_epoch,connection_epoch:T.connection_epoch,connection_state:T.connection_state}:{}}}catch(T){return{status:"error",error:`lm_session_close: ${T instanceof Error?T.message:String(T)}`,code:"internal"}}},lm_ratelimit_readings:async(w={})=>{let T=await s.readRatelimits(f(),w);return T.status==="ok"?{status:"ok",error:null,readings:T.readings}:{status:"error",error:`lm_ratelimit_readings: ${T.error}`,readings:[]}},lm_terminal:async(w,T)=>{let k=await s.openTerminal(f(),{teamfile:w,alias:T},{stdin:t.stdin??process.stdin,stdout:process.stdout,stderr:process.stderr});return{status:k.status,error:k.error?`lm_terminal: ${k.error}`:null,exit_code:k.code??1,signal:k.signal??null,code:k.errorCode??null}},lm_running:async(w={})=>{if(w!==void 0&&!os(w))throw Error("lm_running: options must be a map");try{let T=await s.listRunning(f(),os(w)?w:{}),k="code"in T&&T.code?T.code:void 0;return{status:T.status,error:T.error?`lm_running: ${T.error}`:null,...k?{code:k}:{},running:"running"in T&&Array.isArray(T.running)?T.running:[],dead:"dead"in T&&Array.isArray(T.dead)?T.dead:[],idle:"idle"in T&&Array.isArray(T.idle)?T.idle:[]}}catch(T){let k=OC(T);return{status:"error",error:`lm_running: ${T instanceof Error?T.message:String(T)}`,code:k,running:[],dead:[],idle:[]}}},lm_fanout:(w,T,k={})=>{if(!Array.isArray(w))throw Error("lm_fanout: participants must be an array");if(w.length===0)return[];if(!os(k))throw Error("lm_fanout: options must be a map");let I=typeof T=="string"?w.map(()=>T):T;if(!Array.isArray(I)||I.length!==w.length||I.some(C=>typeof C!="string"))throw Error("lm_fanout: prompts must match participants");return Promise.all(w.map((C,M)=>b(C,I[M],k)))},lm_batch_open:async(w,T,k,I={})=>{if(!Lo())throw Error("lm_batch_open requires an authorized script invocation");if(typeof w!="string"){if(!w||typeof w!="object"||Array.isArray(w)||typeof w.provider!="string"||!w.provider.trim())throw Error("lm_batch_open: member map requires provider");if(k!==void 0||T!=null&&!os(T))throw Error("lm_batch_open: options must be a map");if(w.sessionid){let
|
|
2422
|
-
`),null;let Z=v("lm_batch_open"
|
|
2423
|
-
`),null}let M={};return u.set(M,C.batch),R(M),x(M)},lm_batch_turn:async(w,T,k,I)=>{w=E(w);let C=w&&l.get(w);if(C){let D=await s.nativeSessionTurn(f(),C,T);return{status:D.status,reply:D.reply,error:D.error,message_id:D.messageId,team_chat_log_id:D.teamChatLogId}}if(k===void 0||I===void 0)throw Error("lm_batch_turn: index and total are required for non-native batches");let M=w&&typeof w=="object"?c.get(w):void 0;if(!M){let D=S(w);if(!D)throw Error("lm_batch_turn: invalid or unmanaged handle");let j=await s.batchTurn(f(),D,T,k,I);return j.status!=="ok"&&j.status!=="busy"&&(w.observedError=j.error??j.status),R(w),{status:j.status,reply:j.reply,error:j.error?`lm_batch_turn: ${j.error}`:null}}if(M.closed||M.failed)return{status:"error",error:"Batch is closed or stopped after a failed turn",reply:""};if(M.busy)return{status:"busy",error:"Batch already has an active turn",reply:""};M.busy=!0;try{let D=M.member.sessionid,j=await b(M.member,T,M.options);return M.member.sessionid&&M.source.provider===M.member.provider&&M.source.sessionid===D&&(M.source.sessionid=M.member.sessionid),j.status!=="ok"&&(M.failed=!0),{status:j.status,reply:j.reply.replace(/\n+$/u,""),error:j.error}}finally{M.busy=!1}},lm_batch_close:async(w,T="done",k)=>{let I=E(w,"lm_batch_close",!0);if(!I)return!1;let C=Lo(),M=C.runtime.authorizeRaw(I,C.scope,"lm_batch_close",!0);if(!await C.runtime.close(M,[T,k]))throw Error("lm_batch_close: resource "+I.id+" close failed");return!0}};return O.prompt_human=async w=>{if(r.env.LMCTL_NON_INTERACTIVE==="1")throw Error("prompt_human is disabled in non-interactive mode");if(p)throw Error("prompt_human: another operator prompt is active");p=!0;let T=w!==null&&typeof w=="object",k=a().stdout,I=t.stdin??process.stdin,C,M,D,j
|
|
2422
|
+
`),{status:I.status,error:I.error?`lm_seed: ${I.error}`:null,...C?{code:C}:{},seeded:"seeded"in I&&Array.isArray(I.seeded)?I.seeded:[]}},lm_agent:(w,T,k={},I=!1)=>I?Yy():b(w,T,k),lm_agent_message:async(w,T,k={},I=!1)=>{if(I)return{...Yy(),message:null};let C=await b(w,T,k),M=C.status==="ok"&&w?.sessionid?await s.agentMessage(f(),w.provider,w.sessionid,C.reply):null;return{...C,message:M}},lm_prompt:async(w,T,k,I={},C=!1)=>{if(C)return Yy();try{let M=await s.promptMember(f(),{teamfile:w,alias:T,prompt:k,permissionMode:I?.permissionMode??"yolo",idleTimeoutMs:I?.idleTimeoutMs,messageType:I?.messageType});return{status:M.status,reply:M.reply,error:M.error?`lm_prompt: ${M.error}`:null,message_id:M.messageId,team_chat_log_id:M.teamChatLogId}}catch(M){return{status:"error",reply:"",error:`lm_prompt: ${M instanceof Error?M.message:String(M)}`,message_id:null,team_chat_log_id:null}}},lm_session_list:async(w={})=>{if(w!==void 0&&!os(w))throw Error("lm_session_list: options must be a map");let T=await s.listSessions(f(),os(w)?{provider:w.provider,workspace:w.sessiondir,all:w.all}:w),k="code"in T?T.code:void 0;return{status:T.status,error:T.error?`lm_session_list: ${T.error}`:null,...k?{code:k}:{},sessions:"sessions"in T?T.sessions:[]}},lm_session_get:async w=>{try{let T=await s.getSession(f(),w);if(T.status==="ok")return{status:"ok",error:null,messages:T.messages};if(T.status==="not_found")return{status:"not_found",error:null};let k="code"in T&&T.code?T.code:void 0;return{status:T.status,error:T.error?`lm_session_get: ${T.error}`:null,...k?{code:k}:{}}}catch(T){let k=OC(T);return{status:"error",error:`lm_session_get: ${T instanceof Error?T.message:String(T)}`,code:k}}},lm_session_delete:async(w,T={})=>{let k=await s.deleteSession(f(),w,{force:T?.force});return k.status==="deleted"&&(m.delete(JSON.stringify([w.provider,w.sessionid])),w.sessionid=null),{status:k.status,error:k.error?`lm_session_delete: ${k.error}`:null}},lm_session_turn:async(w,T,k={})=>{try{let I=await s.nativeSessionRequest(f(),w,T,k);return{status:I.status,reply:I.reply??"",error:I.error?`lm_session_turn: ${I.error}`:null,message_id:I.messageId??null,team_chat_log_id:I.teamChatLogId??null,..."code"in I&&I.code?{code:I.code}:{},..."outcome"in I?{outcome:I.outcome,service_epoch:I.service_epoch,connection_epoch:I.connection_epoch,connection_state:I.connection_state}:{}}}catch(I){return{status:"error",reply:"",error:`lm_session_turn: ${I instanceof Error?I.message:String(I)}`,code:"internal",message_id:null,team_chat_log_id:null}}},lm_session_close:async w=>{try{let T=await s.nativeSessionClose(f(),w);return{status:T.status,error:T.error?`lm_session_close: ${T.error}`:null,..."code"in T&&T.code?{code:T.code}:{},..."outcome"in T?{outcome:T.outcome,service_epoch:T.service_epoch,connection_epoch:T.connection_epoch,connection_state:T.connection_state}:{}}}catch(T){return{status:"error",error:`lm_session_close: ${T instanceof Error?T.message:String(T)}`,code:"internal"}}},lm_ratelimit_readings:async(w={})=>{let T=await s.readRatelimits(f(),w);return T.status==="ok"?{status:"ok",error:null,readings:T.readings}:{status:"error",error:`lm_ratelimit_readings: ${T.error}`,readings:[]}},lm_terminal:async(w,T)=>{let k=await s.openTerminal(f(),{teamfile:w,alias:T},{stdin:t.stdin??process.stdin,stdout:process.stdout,stderr:process.stderr});return{status:k.status,error:k.error?`lm_terminal: ${k.error}`:null,exit_code:k.code??1,signal:k.signal??null,code:k.errorCode??null}},lm_running:async(w={})=>{if(w!==void 0&&!os(w))throw Error("lm_running: options must be a map");try{let T=await s.listRunning(f(),os(w)?w:{}),k="code"in T&&T.code?T.code:void 0;return{status:T.status,error:T.error?`lm_running: ${T.error}`:null,...k?{code:k}:{},running:"running"in T&&Array.isArray(T.running)?T.running:[],dead:"dead"in T&&Array.isArray(T.dead)?T.dead:[],idle:"idle"in T&&Array.isArray(T.idle)?T.idle:[]}}catch(T){let k=OC(T);return{status:"error",error:`lm_running: ${T instanceof Error?T.message:String(T)}`,code:k,running:[],dead:[],idle:[]}}},lm_fanout:(w,T,k={})=>{if(!Array.isArray(w))throw Error("lm_fanout: participants must be an array");if(w.length===0)return[];if(!os(k))throw Error("lm_fanout: options must be a map");let I=typeof T=="string"?w.map(()=>T):T;if(!Array.isArray(I)||I.length!==w.length||I.some(C=>typeof C!="string"))throw Error("lm_fanout: prompts must match participants");return Promise.all(w.map((C,M)=>b(C,I[M],k)))},lm_batch_open:async(w,T,k,I={})=>{if(!Lo())throw Error("lm_batch_open requires an authorized script invocation");if(typeof w!="string"){if(!w||typeof w!="object"||Array.isArray(w)||typeof w.provider!="string"||!w.provider.trim())throw Error("lm_batch_open: member map requires provider");if(k!==void 0||T!=null&&!os(T))throw Error("lm_batch_open: options must be a map");if(w.sessionid){let $=await s.openNativeSession(f(),w,T??{});if($.status==="busy")return a().stderr($.error+`
|
|
2423
|
+
`),null;let Z=v("lm_batch_open",$),q={};return l.set(q,Z.session),x(q)}let D={id:`member-batch-${Date.now()}-${Math.random()}`,kind:"agent"},j={member:{...w},source:w,options:{...T??{}},closed:!1,failed:!1,busy:!1};return c.set(D,j),Object.defineProperties(D,{member:{enumerable:!0,get:()=>j.member},sourceMember:{enumerable:!0,get:()=>j.source},options:{enumerable:!0,get:()=>j.options},closed:{enumerable:!0,get:()=>j.closed},failed:{enumerable:!0,get:()=>j.failed},inFlight:{enumerable:!0,get:()=>j.busy}}),x(D)}if(typeof T!="string"||typeof k!="string")throw Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let C=await s.openTeamBatch(f(),{teamfile:w,alias:T,label:k,promptCount:Number(I?.promptCount??1),legacy:!!I?.legacy});if(C.status!=="ok"){if("code"in C&&(C.code==="provider"||C.code==="cancelled"))throw _("lm_batch_open",C);return a().stderr(`error: lm_batch_open: ${C.error}
|
|
2424
|
+
`),null}let M={};return u.set(M,C.batch),R(M),x(M)},lm_batch_turn:async(w,T,k,I)=>{w=E(w);let C=w&&l.get(w);if(C){let D=await s.nativeSessionTurn(f(),C,T);return{status:D.status,reply:D.reply,error:D.error,message_id:D.messageId,team_chat_log_id:D.teamChatLogId}}if(k===void 0||I===void 0)throw Error("lm_batch_turn: index and total are required for non-native batches");let M=w&&typeof w=="object"?c.get(w):void 0;if(!M){let D=S(w);if(!D)throw Error("lm_batch_turn: invalid or unmanaged handle");let j=await s.batchTurn(f(),D,T,k,I);return j.status!=="ok"&&j.status!=="busy"&&(w.observedError=j.error??j.status),R(w),{status:j.status,reply:j.reply,error:j.error?`lm_batch_turn: ${j.error}`:null}}if(M.closed||M.failed)return{status:"error",error:"Batch is closed or stopped after a failed turn",reply:""};if(M.busy)return{status:"busy",error:"Batch already has an active turn",reply:""};M.busy=!0;try{let D=M.member.sessionid,j=await b(M.member,T,M.options);return M.member.sessionid&&M.source.provider===M.member.provider&&M.source.sessionid===D&&(M.source.sessionid=M.member.sessionid),j.status!=="ok"&&(M.failed=!0),{status:j.status,reply:j.reply.replace(/\n+$/u,""),error:j.error}}finally{M.busy=!1}},lm_batch_close:async(w,T="done",k)=>{let I=E(w,"lm_batch_close",!0);if(!I)return!1;let C=Lo(),M=C.runtime.authorizeRaw(I,C.scope,"lm_batch_close",!0);if(!await C.runtime.close(M,[T,k]))throw Error("lm_batch_close: resource "+I.id+" close failed");return!0}};return O.prompt_human=async w=>{if(r.env.LMCTL_NON_INTERACTIVE==="1")throw Error("prompt_human is disabled in non-interactive mode");if(p)throw Error("prompt_human: another operator prompt is active");p=!0;let T=w!==null&&typeof w=="object",k=a().stdout,I=t.stdin??process.stdin,C,M,D,j,$,Z=!1,q=()=>{Z=!0,D?.close()};try{let Y=new dG({write(B,W,J){k(String(B)),J()}});if(!T)return await Gl(w,I,Y,r.signal);if(M={...w},Array.isArray(w)||typeof M.provider!="string"||!M.provider.trim()||typeof M.sessionid!="string"||!M.sessionid.trim())return{command:"error",args:["prompt_human: session map requires provider and sessionid; call lm_agent first"]};let ne=JSON.stringify([M.provider,M.sessionid]),me=s.sessionAdmission(f(),M);if(me.status==="busy"&&me.busyReason==="turn")return{command:"busy",args:["Agent turn is still running"]};let ee=s.reserveSession(f(),M);if(ee.status!=="ok")return{command:ee.status,args:[ee.error??"Session admission failed"]};if(C=ee.reservation,j={provider:M.provider,sessionid:M.sessionid},$=f().signal,I.destroyed||I.readableEnded)return{command:"eof",args:[]};D=uG({input:I,output:I.isTTY?Y:void 0,terminal:!!I.isTTY,crlfDelay:1/0});let st=D[Symbol.asyncIterator]();D.on("SIGINT",q),$.addEventListener("abort",q,{once:!0}),$.aborted&&q(),k(`Session ${M.alias??M.provider} (${M.sessionid})
|
|
2424
2425
|
`);let Ve=m.get(ne);if(Ve)for(let B of Ve.lines)k(B+`
|
|
2425
2426
|
`);else{let B=await s.getSession(f(),M);if(B.status!=="ok")return{command:"error",args:["Could not load session history"]};for(let W of B.messages)(W.role==="user"||W.role==="assistant")&&k(`${W.role==="user"?"You":"Agent"}: ${W.content}
|
|
2426
2427
|
`)}for(k(`Talk to the agent. Return to the script with /exit [command] [args...].
|
|
2427
|
-
`);;){k("You> ");let B=await st.next();if(Z)return{command:"cancelled",args:[]};if(B.done)return{command:"eof",args:[]};let W=B.value.trim();if(!W)continue;if(/^\/exit(?:\s|$)/u.test(W)){let
|
|
2428
|
-
`),
|
|
2429
|
-
`),{command:
|
|
2430
|
-
`),stderr:
|
|
2431
|
-
`)?
|
|
2432
|
-
`)}),st=ee.exitCode??(ee.success&&(ee.errors?.length??0)===0?0:1),Ve=(ee.diagnostics??[]).filter(
|
|
2433
|
-
`);return{success:st===0,stdout:j,output:ee.output,exit_code:st,code:st,value:ee.value??null,errors:[...ee.errors??[],...Ve.map(
|
|
2428
|
+
`);;){k("You> ");let B=await st.next();if(Z)return{command:"cancelled",args:[]};if(B.done)return{command:"eof",args:[]};let W=B.value.trim();if(!W)continue;if(/^\/exit(?:\s|$)/u.test(W)){let pe=W.split(/\s+/u).slice(1);return{command:pe.shift()??"exit",args:pe}}let J=await b(M,B.value,Ve?.options??{},C);if(J.reply&&k(`Agent: ${J.reply}
|
|
2429
|
+
`),J.status!=="ok")return k(`${J.status}: ${J.error}
|
|
2430
|
+
`),{command:J.status,args:[J.error??"Agent turn failed"]}}}catch(Y){if(!T)throw Y;return{command:"error",args:[Y instanceof Error?Y.message:String(Y)]}}finally{try{D?.close()}finally{$?.removeEventListener("abort",q);try{C&&j&&s.releaseSession(f(),j,C).status!=="ok"&&r.reportRecordedError("prompt_human: reservation release failed")}catch{r.reportRecordedError("prompt_human: reservation release failed")}finally{p=!1}}}},O.run_script=async(w,T=[],k={})=>{let I=pG(r.cwd,String(w)),C=mG(I,"utf8"),M=Array.isArray(T)?T.map(String):[],D=k?.output??"capture";if(D!=="capture"&&D!=="stream")throw Error("run_script output must be capture or stream");let j="",$=a(),Z=o.getStore()?.errors,q=[],Y=wr({source_kind:"file",script_file:I,source_name:I,parent_run_id:(o.getStore()?.executionOrigin??r.executionOrigin).run_id}),ne={executionOrigin:Y,errors:q,stdout:ee=>{j+=ee,D==="stream"&&$.stdout(ee)},stderr:ee=>$.stderr(ee)},me=r.createChildEngine?r.createChildEngine({args:M,excludeBuiltins:["lmctl"]}):new Er({resolveHostModule:r.resolveHostModule??t.resolveHostModule});if(!r.createChildEngine){for(let ee of r.nativeModules??t.nativeModules??[])me.registerNativeModule(ee);for(let ee of r.builtinProviders??t.builtinProviders??[])ee.name!=="lmctl"&&me.registerBuiltinProvider(ee);me.setGlobal("args",M),me.setGlobal("ARGV",[...M])}return me.registerBuiltinProvider({...n,activate:ee=>({functions:O,globals:{},loadProperties:g,getRecordedErrors:()=>[...q],dispose(){}})}),o.run(ne,async()=>{let ee=await me.runAsync(C,{noPreflight:r.noPreflight,file:I,entryLocation:I,executionOrigin:Y,propertyStore:r.propertyStore,reservedFunctionPrefixes:r.reservedFunctionPrefixes??["lm_","lmbee_"],builtinProviderNames:r.builtinProviderNames??["lmctl","lmbee"],resolveHostModule:r.resolveHostModule??t.resolveHostModule,hostContext:{cwd:r.cwd,env:r.env,platform:r.platform},signal:r.signal,stdout:(J,pe)=>ne.stdout(pe?J:J+`
|
|
2431
|
+
`),stderr:J=>ne.stderr(J.endsWith(`
|
|
2432
|
+
`)?J:J+`
|
|
2433
|
+
`)}),st=ee.exitCode??(ee.success&&(ee.errors?.length??0)===0?0:1),Ve=(ee.diagnostics??[]).filter(J=>J.severity==="error"&&!(ee.errors??[]).includes(J.message)),B=[...ee.errors??[],...Ve.map(J=>J.message)],W=[...q];for(let J of B){let pe=W.indexOf(J);pe>=0?W.splice(pe,1):r.reportRecordedError(J)}Z?.push(...B);for(let J of Ve)ne.stderr(`error:${J.file&&J.file!=="<main>"?J.file:I}:${J.line}:${J.column}: ${J.message}
|
|
2434
|
+
`);return{success:st===0,stdout:j,output:ee.output,exit_code:st,code:st,value:ee.value??null,errors:[...ee.errors??[],...Ve.map(J=>J.message)]}})},{functions:O,globals:h,loadProperties:g,async dispose(){r.signal?.removeEventListener("abort",y);for(let w of d.values()){let T=c.get(w);T&&(T.closed=!0)}if(i){let w=await i.close();for(let T of d.values())if(S(T))try{R(T),T.closed=!0}catch(k){w.errors.push(k instanceof Error?k.message:String(k))}if(w.errors.length)throw Error(w.errors.join(`
|
|
2434
2435
|
`))}}}}};return n}var gG,hG,yG,zy,Xd,Yy,vG,os,LC,bG,DC=L(()=>{"use strict";zn();ai();hb();gG=[{name:"lm_exit",arity:{min:0,max:1}},{name:"lm_log",arity:{min:1},params:[{name:"value",type:"any"},{name:"values",type:"any",rest:!0}]},{name:"lm_error",arity:{min:1}},{name:"lm_read_paragraphs",arity:1},{name:"lm_fanout",arity:{min:2,max:3}},{name:"lm_agent_message",arity:{min:2,max:3},params:[{name:"member",type:"map"},{name:"prompt",type:"string"},{name:"options",type:"map",optional:!0}]},{name:"lm_batch_open",arity:{min:1,max:4},returnsResource:ht.find(t=>t.name==="openTeamBatch")?.returnsResource===!0},{name:"lm_batch_turn",arity:{min:2,max:4},params:[{name:"batch",type:"any"},{name:"prompt",type:"string"},{name:"index",type:"number",optional:!0},{name:"total",type:"number",optional:!0}],usesResource:!0},{name:"lm_batch_close",arity:{min:1,max:3},closesResource:!0},{name:"prompt_human",arity:{min:0,max:1},override:!0},{name:"run_script",arity:{min:1,max:3},override:!0}],hG=ht.filter(t=>"scriptBinding"in t).map(t=>{let e=t.scriptBinding;return{name:e.name,arity:{min:e.params.filter(n=>!n.optional).length,max:e.params.length},params:e.params,doc:{name:e.name,description:t.summary,module:"lmctl",category:"lmctl Automation",signature:e.name+"("+e.params.map(n=>n.name).join(", ")+")"}}}),yG={lm_members:"map",lm_member:"map",lm_read_prompts:"map",lm_read_paragraphs:"map",lm_prompt:"map",lm_agent:"map",lm_agent_message:"map",lm_fanout:"array",lm_lint:"map",lm_seed:"map",lm_session_list:"map",lm_session_get:"map",lm_session_delete:"map",lm_ratelimit_readings:"map",lm_terminal:"map",lm_session_turn:"map",lm_session_close:"map",lm_running:"map",lm_batch_open:"ResourceHandle|null",lm_batch_turn:"map",lm_batch_close:"boolean",lm_log:"string",lm_error:"string",lm_exit:"never",prompt_human:"string|map|null",run_script:"map"},zy={name:"dryrun",type:"boolean",optional:!0},Xd=new Set(ht.filter(t=>["readPrompts","listMembers"].includes(t.name)&&t.effects.length>0&&t.effects.every(e=>e==="file-read")).map(t=>t.scriptBinding.name));Xd.has("lm_read_prompts")&&Xd.add("lm_read_paragraphs");Yy=()=>({status:"ok",reply:"",error:null,message_id:null,team_chat_log_id:null,dry:!0}),vG={functions:[...hG,...gG].map(_G).map(t=>({...t,returnType:yG[t.name],doc:(()=>{let e=gb.find(n=>n.name===t.name)??("doc"in t?t.doc:void 0);return e?{...e,module:"lmctl"}:void 0})()})),globals:[],properties:{known:mp,removedGlobals:pp}},os=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),LC=t=>t.map(e=>e!==null&&typeof e=="object"?JSON.stringify(e):String(e)).join(" ");bG=MC()});var Qy,tl,Zy,e_=L(()=>{"use strict";Qy=[{name:"db",type:"string",required:!0},{name:"local_scope",type:"string",required:!0},{name:"conversationid",type:"string",required:!0},{name:"escalationid",type:"string"}],tl=[{name:"lmbee_job_read",description:"Read live parent or child rows, including claimed rows.",keys:[...Qy,{name:"row",type:"string",required:!0,values:["job","escalation"]}]},{name:"lmbee_job_write",description:"Insert or conditionally update one exact parent or child; commit before returning.",keys:[...Qy,{name:"row",type:"string",required:!0,values:["job","escalation"]},{name:"operation",type:"string",required:!0,values:["insert","update"]},{name:"values",type:"map",required:!0},{name:"where",type:"map"}]},{name:"lmbee_job_claim",description:"Reserve one eligible unclaimed child in an immediate transaction; eligibility is script-defined.",keys:[...Qy,{name:"where",type:"map",required:!0},{name:"state",type:"string",required:!0}]}],Zy="Returns {status, code, rows, applied, error}. status: ok, no_rows, not_applied, error, cancelled. Error codes: invalid_argument, selection_failed, database_unavailable, write_rejected. Failures have no partial rows or applied writes. Inspect status: interpreter success alone is not storage success. Cancellation is separate; programmer faults throw."});import{existsSync as FC}from"node:fs";import{createRequire as wG}from"node:module";import{dirname as EG}from"node:path";function TG(){return t_===null&&(t_=wG(import.meta.url)("node:sqlite").DatabaseSync),t_}function RG(t){return kG[t]??SG[t&255]??`SQLITE_UNKNOWN_${t}`}function $n(t){if(t!==null&&typeof t=="object"){let e=t;if(typeof e.errcode=="number")throw e.code=RG(e.errcode),t;if(e.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(e.message)))throw new TypeError(xG);if(e.code==="ERR_INVALID_STATE"&&/database is not open/.test(String(e.message)))throw new TypeError("The database connection is not open")}throw t}function IG(){let t="unable to open database file";return Object.assign(new Error(t),{code:"SQLITE_CANTOPEN",errcode:14,errstr:t})}function $C(t){return t instanceof Uint8Array&&!Buffer.isBuffer(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):t}function AG(t){if(t==null)return t;if(Array.isArray(t))return t.map($C);if(typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=$C(r);return e}return t}function CG(t){if(t===null||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array)return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Gd(t){return t.map((e,n)=>{if(e===void 0)return null;if(n===0&&CG(e)){let r={};for(let[s,i]of Object.entries(e))r[s]=i===void 0?null:i;return r}return e})}function NG(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function OG(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}var t_,SG,kG,xG,n_,r_,s_,i_=L(()=>{"use strict";t_=null;SG={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"},kG={261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB",264:"SQLITE_READONLY_RECOVERY",520:"SQLITE_READONLY_CANTLOCK",776:"SQLITE_READONLY_ROLLBACK",1032:"SQLITE_READONLY_DBMOVED",1288:"SQLITE_READONLY_CANTINIT",1544:"SQLITE_READONLY_DIRECTORY",270:"SQLITE_CANTOPEN_NOTEMPDIR",526:"SQLITE_CANTOPEN_ISDIR",782:"SQLITE_CANTOPEN_FULLPATH",1038:"SQLITE_CANTOPEN_CONVPATH",1294:"SQLITE_CANTOPEN_DIRTYWAL",1550:"SQLITE_CANTOPEN_SYMLINK",275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE"};xG="SQLite3 can only bind numbers, strings, bigints, buffers, and null";n_=class{handle;pluckMode=!1;arrayMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0),this.handle.setAllowUnknownNamedParameters(!0)}get source(){return this.handle.sourceSQL}run(...e){try{let n=this.handle.run(...Gd(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){$n(n)}}get(...e){try{return this.project(this.handle.get(...Gd(e)))}catch(n){$n(n)}}all(...e){try{return this.handle.all(...Gd(e)).map(n=>this.project(n))}catch(n){$n(n)}}*iterate(...e){let n;try{n=this.handle.iterate(...Gd(e))}catch(r){$n(r)}for(;;){let r;try{r=n.next()}catch(s){$n(s)}if(r.done)return;yield this.project(r.value)}}raw(e=!0){return this.arrayMode=e,this.handle.setReturnArrays(e||this.pluckMode),this}pluck(e=!0){return this.pluckMode=e,this.handle.setReturnArrays(e||this.arrayMode),this}project(e){let n=AG(e);return this.pluckMode&&Array.isArray(n)?n[0]:n}},r_=class{name;memory;readonly;handle;savepointId=0;constructor(e,n={}){let r=e===":memory:"||e==="";if(n.readonly===!0&&r)throw new TypeError("In-memory/temporary databases cannot be readonly");if(!r&&!FC(EG(e)))throw new TypeError("Cannot open database because the directory does not exist");if(n.fileMustExist===!0&&!r&&!FC(e))throw IG();this.name=e,this.memory=r,this.readonly=n.readonly===!0;try{this.handle=new(TG())(e,{readOnly:this.readonly,timeout:n.timeout??5e3,enableForeignKeyConstraints:n.foreignKeys??!0})}catch(s){$n(s)}}get open(){return this.handle.isOpen}get inTransaction(){return this.handle.isTransaction}prepare(e){try{return new n_(this.handle.prepare(e))}catch(n){$n(n)}}exec(e){try{return this.handle.exec(e),this}catch(n){$n(n)}}pragma(e,n){let r=this.prepare(`PRAGMA ${e}`);return n?.simple===!0?r.pluck().get():r.all()}transaction(e){let n=s=>(...i)=>this.runTransaction(s,e,i),r=n("BEGIN");return r.default=n("BEGIN"),r.deferred=n("BEGIN DEFERRED"),r.immediate=n("BEGIN IMMEDIATE"),r.exclusive=n("BEGIN EXCLUSIVE"),r}serialize(){try{let e=this.handle.serialize();return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}catch(e){$n(e)}}close(){if(!this.handle.isOpen)return this;try{return this.handle.close(),this}catch(e){$n(e)}}runTransaction(e,n,r){if(!this.inTransaction){this.exec(e);try{let i=n(...r);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!NG(o))throw o}throw i}}let s=`lmbee_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=n(...r);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!OG(o))throw o}throw i}}};s_=r_});import{existsSync as foe,lstatSync as LG,mkdirSync as goe,readFileSync as hoe,realpathSync as jC}from"node:fs";import{basename as MG,dirname as BC,isAbsolute as PG,join as DG,relative as FG,resolve as UC}from"node:path";import{fileURLToPath as $G}from"node:url";function HC(t){let e=process.env.LMBEE_TEST_DB_ROOT;if(!e||t===":memory:")return;let n=[],r=UC(t);for(;LG(r,{throwIfNoEntry:!1})===void 0;){n.unshift(MG(r));let o=BC(r);if(o===r)throw new Error("Cannot resolve test database path");r=o}let s=UC(jC(r),...n),i=FG(jC(e),s);if(i===".."||i.startsWith("../")||i.startsWith("..\\")||PG(i))throw new Error(`Database path is outside the test database root: ${t}`)}function WC(t){let e=s=>t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(s)!==void 0,n=s=>t.prepare(`PRAGMA table_info(${s})`).all(),r;for(let s of["queue_responses","chat_tasks","chat_messages","chat_message_task_reassignments"])if(e(s)){r=`legacy table '${s}'`;break}if(r===void 0&&e("answers")){let s=new Set(n("answers").map(i=>i.name));s.has("request_queue_id")?r="legacy column 'answers.request_queue_id'":s.has("superseded_at")||(r="legacy 'answers' shape: missing column 'superseded_at'")}if(r===void 0&&e("queue")){let s=n("queue"),i=new Set(s.map(o=>o.name));i.has("team")?r="legacy column 'queue.team'":i.has("to_id")?s.some(o=>o.name==="from_id"&&o.notnull!==1)?r="legacy 'queue' shape: from_id is still nullable":i.has("restart_nudge_sent_ts")&&(r="legacy column 'queue.restart_nudge_sent_ts'"):r="legacy 'queue' shape: missing column 'to_id'"}if(r===void 0&&e("cron_jobs")){let s=t.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'cron_jobs'").get();(s===void 0||!s.sql.includes("'miniplayer'"))&&(r="legacy 'cron_jobs' CHECK constraint predates 'miniplayer'")}if(r===void 0&&e("cron_jobs")){let s=t.prepare("SELECT id, action_payload FROM cron_jobs WHERE action_kind = 'enqueue'").all();for(let i of s){let o;try{o=JSON.parse(i.action_payload)}catch{o=void 0}let a=typeof o=="object"&&o!==null?o.prompt:void 0;if(typeof a!="string"||a.trim().length===0){r=`legacy 'cron_jobs' enqueue payload (id ${i.id}) predates the 'prompt' vocabulary`;break}}}if(r===void 0&&e("team_progress")&&new Set(n("team_progress").map(i=>i.name)).has("last_scan_head")&&(r="legacy column 'team_progress.last_scan_head'"),r===void 0&&e("cron_runs")&&(new Set(n("cron_runs").map(i=>i.name)).has("execution_state")||(r="legacy 'cron_runs' shape: missing column 'execution_state'")),r===void 0&&e("rate_limit_policy_log")){let s=t.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'rate_limit_policy_log'").get();(s===void 0||!s.sql.includes("'confirmed_would_fire_policy_disabled'"))&&(r="legacy 'rate_limit_policy_log' CHECK constraint predates 'confirmed_would_fire_policy_disabled'")}if(r===void 0&&e("rate_limit_policy_arm")&&(new Set(n("rate_limit_policy_arm").map(i=>i.name)).has("armed_used_fraction")||(r="legacy 'rate_limit_policy_arm' shape: missing column 'armed_used_fraction'")),r!==void 0)throw new Error(`Refusing to open this lmbee state.db: abandoned pre-v14 lmbee schema shape (${r}). Per the operator's 2026-10-01 shared-database decision, lmbee now shares lmctl's state.db and every pre-existing lmbee-only database is abandoned -- there is no data migration, ever. Do not remove a shared lmctl database. Check LMBEE_DB and the database ownership; point lmbee at the intended compatible database. Preserve this file for operator review.`)}function qC(t){let e=t.pragma("user_version",{simple:!0});if(e<=Jd)return;let n;if(t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_meta'").get()!==void 0){let s=new Set(t.prepare("PRAGMA table_info(schema_meta)").all().map(i=>i.name));if(s.has("key")&&s.has("value")){let i=t.prepare("SELECT value FROM schema_meta WHERE key = 'min_reader_version'").get();typeof i?.value=="string"&&(n=i.value)}}let r;if(n===void 0)r="schema_meta.min_reader_version is absent";else if(!/^[1-9]\d*$/.test(n))r=`schema_meta.min_reader_version=${JSON.stringify(n)} is malformed (not a canonical decimal integer)`;else if(Number(n)>Jd)r=`schema_meta.min_reader_version=${n} declares a breaking floor above ${Jd}`;else return;throw new Error(`Refusing to open the shared state.db: it was migrated by a newer lmctl with breaking changes (user_version=${e} exceeds the newest lmctl schema version this lmbee build understands, ${Jd}, and ${r}). Upgrade lmbee to a build that understands the newer lmctl schema before opening this database again. lmbee never writes user_version or schema_meta, so the file is untouched.`)}var voe,Jd,XC=L(()=>{"use strict";i_();voe=DG(BC($G(import.meta.url)),"schema.sql");Jd=62});import{resolve as jG,isAbsolute as UG}from"node:path";function a_(t){t.exec(`CREATE TABLE IF NOT EXISTS workflow_jobs (
|
|
2435
2436
|
local_scope TEXT NOT NULL, conversationid TEXT NOT NULL, status TEXT NOT NULL,
|
|
2436
2437
|
PRIMARY KEY (local_scope, conversationid)
|
|
@@ -2452,44 +2453,44 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
2452
2453
|
`).slice(-tJ).join(`
|
|
2453
2454
|
`)}function iJ(t){return t.map(e=>`${e.code}${e.param?` '${e.param}'`:""}${e.suggestion?` (did you mean '${e.suggestion}'?)`:""}: ${e.message}`).join("; ")}function IN(t,e={}){let n=f_(t.text),r=t.alias??n.tool;if(!eJ.test(r))throw Error(`namespace ${JSON.stringify(r)} is not an identifier`);let s=e.timeoutMs??0,i=xN(n,r);return{name:"schema:"+r,nativeNamespace:r,declarations:i,async activate(o){let a=f_(t.text),l={};for(let c of a.operations){let u=r+"."+c.name,{positionals:d}=RN(a.tool,c);l[u]=async(...m)=>{let p=m[d.length+1]===!0,f=m[d.length]??{};if(!ol(f))throw Error(`${u}: options must be a map`);if(Object.hasOwn(f,"dryrun"))throw Error(`${u}: dryrun is supplied by the language; omit it`);let h=[],g=Object.create(null);for(let[O,A]of d.entries())m[O]!==void 0&&(g[A.name]=m[O]);for(let[O,A]of Object.entries(f)){if(g_.includes(O)){if(typeof A!="boolean")throw Error(`${u}: option '${O}' must be boolean`);A&&h.push("--"+O);continue}if(Object.hasOwn(g,O))throw Error(`${u}: '${O}' given both positionally and as an option`);g[O]=A}if(p)return{status:"simulated",simulated:u};let y=u_(c,g,{form:"json"});if(!y.ok)return as({code:"validation",message:`${u}: ${iJ(y.issues)}`,issues:[...y.issues]});let b=o.platform??process.platform,_=a.tool,v=bN(c,g),E=()=>{},x,S;try{let O=[_,c.name,"--input-json",v,...h];if(Buffer.byteLength(v)>kN){let A=zG(TN(ZG(),"lmscript-"+a.tool+"-")),w=TN(A,"input.json");E=()=>QG(A,{recursive:!0,force:!0}),YG(w,v,{mode:384}),O=[_,c.name,"--input-file",w,...h]}S=await Xl(O,s,b,o.signal,{cwd:o.cwd,env:{...o.env,LMSCRIPT_RUN_ORIGIN:JSON.stringify(o.executionOrigin)}},{maxOutputBytes:e.maxOutputBytes??0})}catch(O){let A=O;if(A?.code==="ERR_OUTPUT_LIMIT")return as({code:"output_limit",message:`${u}: ${a.tool} ${A.message}`});if(A?.message==="Aborted")throw O;return as({code:"launch",message:`${u}: cannot run ${a.tool}: ${A?.message??String(O)}`})}finally{try{E()}catch(O){x=O}}if(S.timed_out)return as({code:"timeout",message:`${u}: ${a.tool} timed out after ${s} ms`,...S.stderr.trim()?{stderr_tail:SN(S.stderr)}:{}});let R,N=!1;try{R=JSON.parse(S.stdout),N=!0}catch{}if(N&&ol(R)&&R.success===!1&&ol(R.error)){let O=R.error,A=ol(O.data)?O.data:{},w=ol(A.details)?A.details:A,T=Array.isArray(w.issues)?[...w.issues]:[],k=O.code==="VALIDATION_ERROR"?` (the input passed client validation; schema ${a.version??"unversioned"} may be stale)`:"";return as({code:"envelope",message:`${u}: ${String(O.code??"ERROR")}: ${String(O.message??"")}${k}`,tool_code:String(O.code??"ERROR"),...T.length?{issues:T}:{},exit:S.code})}return S.code!==0||S.signal!==null?as({code:"exit",message:`${u}: ${a.tool} exit ${S.code??"none"}${S.signal?` (signal ${S.signal})`:""}`,exit:S.code,signal:S.signal,...S.stderr.trim()?{stderr_tail:SN(S.stderr)}:{}}):N?x!==void 0?as({code:"launch",message:`${u}: cannot remove temporary input: ${x instanceof Error?x.message:String(x)}`}):{status:"ok",result:R}:as({code:"parse",message:`${u}: ${a.tool} ${c.name} printed invalid JSON${S.stdout.trim()?": "+S.stdout.trim().slice(0,200):" (empty stdout)"}`})}}return{functions:l,globals:{},dispose(){}}}}}function oJ(t={}){return e=>IN(e,t)}var g_,eJ,tJ,kN,ls,nJ,rJ,ol,as,CN=L(()=>{"use strict";EN();ai();g_=["readonly","confirm"],eJ=/^[A-Za-z_]\w*$/,tJ=12,kN=100*1024;ls=t=>t.default===void 0&&(t.occurs===void 0||t.occurs==="1"||t.occurs==="+"),nJ=t=>t.type==="array"||t.occurs==="+"||t.occurs==="*";rJ={read:"Read operations",write:"Write operations",dynamic:"Dynamic operations"};ol=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);as=t=>({status:"error",error:t})});function xe(t){return{ok:!0,value:t}}function de(t,e,n={}){return{ok:!1,error:{code:t,message:e,...n},code:t,message:e,...n.file?{file:n.file}:{},...n.issues?{issues:n.issues}:{},...n.details?{details:n.details}:{}}}var zd=L(()=>{});function al(t){if(typeof t!="string"||t.trim()==="")return de("SPEC_SYNTAX","Module spec must be a non-empty string");let e=t.indexOf("#");if(e!==-1){let a=t.slice(0,e),l=t.slice(e+1),c=NN.exec(a);if(!c)return de("SPEC_SYNTAX",`Invalid module spec syntax: "${t}" (expected @owner/repo[#(latest|dev)])`);let u=c[1],d=c[2];if(u==="."||u===".."||d==="."||d==="..")return de("SPEC_SYNTAX",`Invalid owner or repo name: "${t}"`);if(l!=="latest"&&l!=="dev")return de("SPEC_CHANNEL","only the latest and dev channels are supported");let m=l,p=`@${u}/${d}#${m}`;return xe({owner:u,repo:d,channel:m,key:p,requested:t})}let n=NN.exec(t);if(!n)return de("SPEC_SYNTAX",`Invalid module spec syntax: "${t}" (expected @owner/repo[#(latest|dev)])`);let r=n[1],s=n[2];if(r==="."||r===".."||s==="."||s==="..")return de("SPEC_SYNTAX",`Invalid owner or repo name: "${t}"`);let i="latest",o=`@${r}/${s}#${i}`;return xe({owner:r,repo:s,channel:i,key:o,requested:t})}var NN,h_=L(()=>{zd();NN=/^@([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/});import{homedir as aJ}from"node:os";import{isAbsolute as ON,join as LN,relative as MN,resolve as y_}from"node:path";function oo(t=process.env){let e=t.LMCTL_HOME&&t.LMCTL_HOME.trim()!==""?t.LMCTL_HOME:LN(t.HOME??aJ(),".lmctl");return LN(e,"modules")}function __(t,e){let n=y_(t),r=y_(n,"github.com"),s=y_(r,e.owner,e.repo,e.channel),i=MN(n,s),o=MN(r,s);if(i.startsWith("..")||ON(i)||o.startsWith("..")||ON(o))throw new Error(`Path traversal detected: entry directory "${s}" escapes cache root "${n}"`);return s}function Yd(t){return`cli.schema.${t}.json`}var v_=L(()=>{});import{createHash as DN,randomUUID as Qd}from"node:crypto";import{existsSync as Zd,promises as Jt}from"node:fs";import{dirname as bae,isAbsolute as wae,join as yn,relative as Eae,resolve as Tae}from"node:path";async function uJ(t){let e=yn(t,$N);if(!Zd(e))return xe(t);try{let n=(await Jt.readFile(e,"utf8")).trim();if(!lJ.test(n)||n==="."||n==="..")return de("CACHE_CORRUPT",`Invalid ${e}`);let r=yn(t,"generations",n);return Zd(r)?xe(r):de("CACHE_CORRUPT",`Missing cache generation ${n}`)}catch(n){return de("CACHE_CORRUPT",`Failed to read ${e}: ${n?.message??String(n)}`)}}function E_(t){return typeof t=="string"?al(t):xe(t)}async function Zs(t,e){let n=E_(t);if(!n.ok)return de(n.code,n.message);let r=n.value,s=e?.root??oo(),i;try{i=__(s,r)}catch(g){return de("PATH_TRAVERSAL",g?.message??String(g))}let o=Yd(r.channel),a=await uJ(i);if(!a.ok)return a;let l=a.value,c=yn(l,o),u=yn(l,"meta.json");if(!Zd(c)||!Zd(u))return de(l===i?"NOT_INSTALLED":"CACHE_CORRUPT",`Module ${r.key} is missing cache files`);let d,m;try{d=await Jt.readFile(c)}catch(g){return de("CACHE_CORRUPT",`Failed to read ${c}: ${g?.message??String(g)}; run: lmbee module install ${r.key} --force`,{file:c})}try{let g=await Jt.readFile(u,"utf-8");m=JSON.parse(g)}catch(g){return de("CACHE_CORRUPT",`Failed to read or parse ${u}: ${g?.message??String(g)}; run: lmbee module install ${r.key} --force`,{file:u})}let p=DN("sha256").update(d).digest("hex");if(p!==m.sha256)return de("CACHE_CORRUPT",`Cached schema hash mismatch in ${c}: expected ${m.sha256}, got ${p}; run: lmbee module install ${r.key} --force`,{file:c});let f;try{f=JSON.parse(d.toString("utf-8"))}catch(g){return de("BAD_JSON",`Failed to parse ${c} as JSON: ${g?.message??String(g)}`,{file:c})}let h=il(f);return h.ok?xe({spec:r,dir:i,path:c,sha256:p,fetchedAt:m.fetched_at,lastChecked:m.last_checked??m.fetched_at,etag:m.etag,channel:r.channel,tool:h.value.tool,version:h.value.version,document:h.value}):de("INVALID_SCHEMA",`Cached schema in ${c} is invalid: ${h.issues[0]?.message}`,{file:c,issues:h.issues})}async function jN(t,e){let{timeoutMs:n,fetchImpl:r,etag:s}=e,i;try{let o=AbortSignal.timeout(n),a={};if(s&&(a["If-None-Match"]=s),i=await r(t,{signal:o,headers:a,redirect:"manual"}),i.status>=300&&i.status<400&&i.status!==304){let l=i.headers.get("location");if(!l)return de("FETCH_FAILED",`Redirect response from ${t} missing Location header`);let c=new URL(l,t);if(c.protocol!=="https:"||c.hostname!=="raw.githubusercontent.com")return de("FETCH_FAILED",`Cross-host or non-HTTPS redirect to "${l}" refused (must stay on raw.githubusercontent.com)`);i=await r(c.href,{signal:o,headers:a,redirect:"manual"})}}catch(o){return o?.name==="TimeoutError"||o?.name==="AbortError"?de("FETCH_FAILED",`Fetch timed out after ${n}ms for ${t}`):de("FETCH_FAILED",`Network error fetching ${t}: ${o?.message??String(o)}`)}return xe(i)}async function UN(t,e,n,r,s,i){let o;try{if(t.body&&typeof t.body.getReader=="function"){let u=t.body.getReader(),d=[],m=0;for(;;){let{done:p,value:f}=await u.read();if(p)break;if(m+=f.length,m>e)return await u.cancel(),de("OUTPUT_LIMIT",`Schema exceeds maximum size limit of ${e} bytes`);d.push(f)}o=Buffer.concat(d)}else{let u=await t.arrayBuffer();if(u.byteLength>e)return de("OUTPUT_LIMIT",`Schema exceeds maximum size limit of ${e} bytes`);o=Buffer.from(u)}}catch(u){return u?.name==="TimeoutError"||u?.name==="AbortError"?de("FETCH_FAILED",`Fetch stream timed out after ${n}ms`):de("FETCH_FAILED",`Error reading response stream: ${u?.message??String(u)}`)}let a;try{a=JSON.parse(o.toString("utf-8"))}catch(u){return de("BAD_JSON",`Failed to parse ${s} from ${i} as JSON: ${u?.message??String(u)}`)}let l=il(a);if(!l.ok){let u=l.issues[0]?.message??"Schema validation failed";return de("INVALID_SCHEMA",`Invalid schema for ${r}: ${u}`,{issues:l.issues})}let c=DN("sha256").update(o).digest("hex");return xe({buffer:o,sha256:c,schema:l.value})}async function w_(t,e,n,r){let s=`gen-${Date.now()}-${Qd()}`,i=yn(t,"generations",s),o=yn(i,`.tmp.schema.${Qd()}`),a=yn(i,`.tmp.meta.${Qd()}`),l=yn(i,e),c=yn(i,"meta.json"),u=yn(t,`.tmp.current.${Qd()}`);try{await Jt.mkdir(i,{recursive:!0,mode:448}),await Jt.writeFile(o,n,{mode:384}),await Jt.rename(o,l),await PN(l,384),await Jt.writeFile(a,JSON.stringify(r,null,2)+`
|
|
2454
2455
|
`,{mode:384}),await Jt.rename(a,c),await PN(c,384),await Jt.writeFile(u,s+`
|
|
2455
|
-
`,{mode:384}),await Jt.rename(u,yn(t,$N))}catch(d){return await b_(o),await b_(a),await b_(u),de("ATOMIC_WRITE_FAILED",`Failed to write cached module files: ${d?.message??String(d)}`)}return xe(void 0)}async function BN(t,e){let n=E_(t);if(!n.ok)return de(n.code,n.message);let r=n.value,s=e?.root??oo(),i=e?.ttlMs??6*60*60*1e3,o=e?.now??(()=>new Date),a=e?.fetchImpl??globalThis.fetch,l=e?.install??!0,c=e?.update??!0,u=e?.timeoutMs??3e3,d=e?.maxBytes??1048576,m=await Zs(r,{root:s});if(!m.ok){if(m.code==="CACHE_CORRUPT")return m;if(m.code==="NOT_INSTALLED"){if(!l)return de("NOT_INSTALLED",`Module ${r.key} is not installed; run: lmbee module install ${r.key}`);let D=await dJ(r,{root:s,fetchImpl:a,now:o,timeoutMs:u,maxBytes:d});return D.ok?xe({module:D.value.entry,source:"installed"}):de(D.code,D.message,{file:D.file,issues:D.issues,details:D.details})}return m}let p=m.value,f=o().getTime(),h=p.lastChecked?new Date(p.lastChecked).getTime():NaN,g=!isNaN(h)&&h>f,y=isNaN(h),b=f-h;if(!y&&!g&&b>=0&&b<i||!c)return xe({module:p,source:"cache"});let v=Yd(r.channel),E=`${FN}/${r.owner}/${r.repo}/HEAD/${v}`,x=await jN(E,{timeoutMs:u,fetchImpl:a,etag:p.etag});if(!x.ok)return xe({module:p,source:"stale-cache",warning:x.message});let S=x.value;if(S.status===304){let D=o().toISOString(),j=S.headers.get("etag")??S.headers.get("ETag")??p.etag
|
|
2456
|
+
`,{mode:384}),await Jt.rename(u,yn(t,$N))}catch(d){return await b_(o),await b_(a),await b_(u),de("ATOMIC_WRITE_FAILED",`Failed to write cached module files: ${d?.message??String(d)}`)}return xe(void 0)}async function BN(t,e){let n=E_(t);if(!n.ok)return de(n.code,n.message);let r=n.value,s=e?.root??oo(),i=e?.ttlMs??6*60*60*1e3,o=e?.now??(()=>new Date),a=e?.fetchImpl??globalThis.fetch,l=e?.install??!0,c=e?.update??!0,u=e?.timeoutMs??3e3,d=e?.maxBytes??1048576,m=await Zs(r,{root:s});if(!m.ok){if(m.code==="CACHE_CORRUPT")return m;if(m.code==="NOT_INSTALLED"){if(!l)return de("NOT_INSTALLED",`Module ${r.key} is not installed; run: lmbee module install ${r.key}`);let D=await dJ(r,{root:s,fetchImpl:a,now:o,timeoutMs:u,maxBytes:d});return D.ok?xe({module:D.value.entry,source:"installed"}):de(D.code,D.message,{file:D.file,issues:D.issues,details:D.details})}return m}let p=m.value,f=o().getTime(),h=p.lastChecked?new Date(p.lastChecked).getTime():NaN,g=!isNaN(h)&&h>f,y=isNaN(h),b=f-h;if(!y&&!g&&b>=0&&b<i||!c)return xe({module:p,source:"cache"});let v=Yd(r.channel),E=`${FN}/${r.owner}/${r.repo}/HEAD/${v}`,x=await jN(E,{timeoutMs:u,fetchImpl:a,etag:p.etag});if(!x.ok)return xe({module:p,source:"stale-cache",warning:x.message});let S=x.value;if(S.status===304){let D=o().toISOString(),j=S.headers.get("etag")??S.headers.get("ETag")??p.etag,$;try{$=await Jt.readFile(p.path)}catch(ne){return xe({module:p,source:"stale-cache",warning:`Failed to read cached schema: ${ne?.message??String(ne)}`})}let Z={spec:r.key,url:E,sha256:p.sha256,fetched_at:p.fetchedAt,last_checked:D,etag:j,channel:r.channel,tool:p.tool,version:p.version,bytes:$.length},q=await w_(p.dir,v,$,Z);if(!q.ok)return xe({module:p,source:"stale-cache",warning:q.message});let Y=await Zs(r,{root:s});return Y.ok?xe({module:Y.value,source:"network"}):xe({module:p,source:"stale-cache",warning:Y.message})}if(S.status!==200)return xe({module:p,source:"stale-cache",warning:`Failed to refresh ${r.key}: HTTP ${S.status} ${S.statusText}`});let R=await UN(S,d,u,r.key,v,E);if(!R.ok)return xe({module:p,source:"stale-cache",warning:R.message});let{buffer:N,sha256:O,schema:A}=R.value,w=S.headers.get("etag")??S.headers.get("ETag")??void 0,T=o().toISOString(),k=T,I={spec:r.key,url:E,sha256:O,fetched_at:T,last_checked:k,etag:w,channel:r.channel,tool:A.tool,version:A.version??"unknown",bytes:N.length},C=await w_(p.dir,v,N,I);if(!C.ok)return xe({module:p,source:"stale-cache",warning:C.message});let M=await Zs(r,{root:s});return M.ok?xe({module:M.value,source:"network"}):xe({module:p,source:"stale-cache",warning:M.message})}async function dJ(t,e){let n=E_(t);if(!n.ok)return de(n.code,n.message);let r=n.value,s=e?.root??oo(),i=e?.fetchImpl??globalThis.fetch,o=e?.now??(()=>new Date),a=e?.timeoutMs??1e4,l=e?.maxBytes??cJ,c=e?.force??!1,u;try{u=__(s,r)}catch(O){return de("PATH_TRAVERSAL",O?.message??String(O))}let d=Yd(r.channel),m=`${FN}/${r.owner}/${r.repo}/HEAD/${d}`,p=await Zs(r,{root:s});if(!c&&p.ok)return xe({action:"unchanged",entry:p.value});let f=await jN(m,{timeoutMs:a,fetchImpl:i});if(!f.ok)return f;let h=f.value;if(h.status===404)return de("FETCH_FAILED",`Module ${r.key} not found: expected ${d} at the root of the default branch for ${r.owner}/${r.repo}`,{details:{status:404,url:m,file:d}});if(!h.ok)return de("FETCH_FAILED",`Failed to fetch ${m}: HTTP ${h.status} ${h.statusText}`,{details:{status:h.status,url:m}});let g=await UN(h,l,a,r.key,d,m);if(!g.ok)return g;let{buffer:y,sha256:b,schema:_}=g.value;if(!c&&p.ok&&p.value.sha256===b)return xe({action:"unchanged",entry:p.value});let v=h.headers.get("etag")??h.headers.get("ETag")??void 0,E=o().toISOString(),x=E,S={spec:r.key,url:m,sha256:b,fetched_at:E,last_checked:x,etag:v,channel:r.channel,tool:_.tool,version:_.version??"unknown",bytes:y.length},R=await w_(u,d,y,S);if(!R.ok)return R;let N=await Zs(r,{root:s});return N.ok?xe({action:p.ok?"replaced":"installed",entry:N.value}):N}async function PN(t,e){try{await Jt.chmod(t,e)}catch{}}async function b_(t){try{await Jt.unlink(t)}catch{}}var FN,lJ,cJ,$N,HN=L(()=>{p_();v_();h_();zd();FN="https://raw.githubusercontent.com",lJ=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,cJ=2*1024*1024,$N="CURRENT"});var WN=L(()=>{zd();h_();v_();HN()});var JN={};jn(JN,{createModuleResolver:()=>gJ,isModuleSpecifier:()=>fJ,normalizeModuleSpec:()=>XN,parseModuleOverrides:()=>GN});import{readFileSync as mJ}from"node:fs";import{resolve as pJ}from"node:path";function fJ(t){return t.startsWith("@")}function XN(t){let e=al(t);if(!e.ok)throw Error(`${t}: ${e.message}`);return e.value.key}function GN(t,e){let n=new Map;for(let r of t){let s=r.indexOf("=");if(s<1||s===r.length-1)throw Error(`--module expects @owner/repo=<file> (a schema module override), got ${JSON.stringify(r)}; the retired --module NAME host-module loader no longer exists`);n.set(XN(r.slice(0,s)),pJ(e,r.slice(s+1)))}return n}function qN(t,e,n){return{key:t.spec.key,channel:t.channel,origin:e,file:t.path,...t.version!==void 0?{version:t.version}:{},sha256:t.sha256,fetchedAt:t.fetchedAt,lastChecked:t.lastChecked,...n?{warning:n}:{}}}function gJ(t){let e=GN(t.overrides??[],t.cwd??process.cwd()),n=t.root??oo({...t.env}),r=new Map;return{resolve:async i=>{let o=al(i);if(!o.ok)throw Error(`${i}: ${o.message}`);let a=o.value.key,l=e.get(a);if(l!==void 0){let u;try{u=mJ(l,"utf8")}catch(d){throw Error(`--module ${a}=${l}: ${d instanceof Error?d.message:String(d)}`)}return r.set(a,{key:a,channel:o.value.channel,origin:"override",file:l}),{key:a,source:u}}if(t.mode==="cache"){let u=await Zs(o.value,{root:n});if(!u.ok)throw u.code==="NOT_INSTALLED"?Error(`module ${a} is not installed; run the script once to install it, or: lmbee module install @${o.value.owner}/${o.value.repo}${o.value.channel==="latest"?"":"#"+o.value.channel}`):Error(`module ${a}: ${u.message}`);return r.set(a,qN(u.value,"cache")),{key:a,source:JSON.stringify(u.value.document)}}let c=await BN(o.value,{root:n,install:!0,update:!0,...t.fetchImpl?{fetchImpl:t.fetchImpl}:{},...t.now?{now:t.now}:{}});if(!c.ok)throw Error(`module ${a}: ${c.message}`);return r.set(a,qN(c.value.module,c.value.source,c.value.warning)),{key:a,source:JSON.stringify(c.value.module.document)}},provenance:r}}var VN=L(()=>{"use strict";WN()});var Zv={};jn(Zv,{runCli:()=>S_,stableDiagnostic:()=>ll});import{readFileSync as KN,fstatSync as zN,statSync as YN,writeSync as eO,openSync as hJ,closeSync as QN}from"node:fs";import{Socket as yJ}from"node:net";import{resolve as ao,dirname as _J}from"node:path";function ll(t,e="<inline>"){return`${t.severity}:${t.file&&t.file!=="<main>"?t.file:e}:${t.line}:${t.column}: ${t.message}
|
|
2456
2457
|
`}function vJ(t,e){let n;try{n=YN(t)}catch{return}for(let r of e)try{let s=YN(r);if(s.dev===n.dev&&s.ino===n.ino)return r}catch{}}function bJ(t,e){let n=Buffer.from(e+`
|
|
2457
|
-
`),r=0;for(;r<n.length;)try{let s=eO(t,n,r,n.length-r);if(s<=0)throw new Error("trace write made no progress");r+=s}catch(s){if(s.code==="EINTR")continue;throw s}}function wJ(t){let e=Buffer.from(t),n=0,r;for(;n<e.length;)try{let s=eO(2,e,n,e.length-n);if(s===0)return;n+=s}catch(s){let i=s.code;if(i==="EPIPE"||i==="EBADF")return;if(i==="EINTR")continue;if(i==="EAGAIN"||i==="EWOULDBLOCK"){r??=new Int32Array(new SharedArrayBuffer(4)),Atomics.wait(r,0,0,1);continue}throw s}}async function S_(t,e={}){if(t.length===1&&["--version","-v"].includes(t[0]))return(e.stdout??(
|
|
2458
|
-
`),0;let n=[...t],r=e.cwd??process.cwd(),s={...e.env??process.env},i=e.stdout??(
|
|
2459
|
-
`)
|
|
2458
|
+
`),r=0;for(;r<n.length;)try{let s=eO(t,n,r,n.length-r);if(s<=0)throw new Error("trace write made no progress");r+=s}catch(s){if(s.code==="EINTR")continue;throw s}}function wJ(t){let e=Buffer.from(t),n=0,r;for(;n<e.length;)try{let s=eO(2,e,n,e.length-n);if(s===0)return;n+=s}catch(s){let i=s.code;if(i==="EPIPE"||i==="EBADF")return;if(i==="EINTR")continue;if(i==="EAGAIN"||i==="EWOULDBLOCK"){r??=new Int32Array(new SharedArrayBuffer(4)),Atomics.wait(r,0,0,1);continue}throw s}}async function S_(t,e={}){if(t.length===1&&["--version","-v"].includes(t[0]))return(e.stdout??(F=>process.stdout.write(F)))("lmscript "+lp()+`
|
|
2459
|
+
`),0;let n=[...t],r=e.cwd??process.cwd(),s={...e.env??process.env},i=e.stdout??(F=>process.stdout.write(F)),o=e.stderr??wJ,a=new Set,l=[],c=F=>{F.startsWith("error: ")&&l.push(F);let G=F.match(/^error:.*:[0-9]+:[0-9]+: ([^\n]+)/);G&&a.add(G[1]),o(F)},u,d=!1,m=!1,p,f,h,g=!1,y=!1,b,_,v="text",E,x=new Set,S=new Set(["--base-dir","--source-name","--resumepoint","--pref","--dry-loop-limit","--dryrun-timeout","--plan-format","--module","--trace"]),R=[],N=new Set(["--check","--dry-run","--lint","--check-files","--no-preflight",...S]);for(;n.length&&N.has(n[0]);){let F=n.shift();if(x.has(F)&&F!=="--module")return c("error: "+F+` may be specified only once
|
|
2460
|
+
`),F==="--resumepoint"?2:1;x.add(F);let G;if(S.has(F)){if(G=n[0],G===void 0||F==="--pref"&&G===""||G.startsWith("-"))return c("error: "+F+(F==="--resumepoint"||F==="--pref"?` requires a path
|
|
2460
2461
|
`:` requires a value
|
|
2461
|
-
`)),1;n.shift()}if(
|
|
2462
|
-
`),1;u=
|
|
2463
|
-
`),1;v=
|
|
2464
|
-
`),1
|
|
2462
|
+
`)),1;n.shift()}if(F==="--resumepoint"){if(!/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(G))return c("error: Invalid --resumepoint path: "+G+`; expected NAME(.NAME)*
|
|
2463
|
+
`),1;u=G}else if(F==="--base-dir")p=ao(r,G);else if(F==="--pref")E=ao(r,G);else if(F==="--source-name")f=G;else if(F==="--trace")h=ao(r,G);else if(F==="--module")R.push(G);else if(F==="--dry-run")g=!0;else if(F==="--no-preflight")y=!0;else if(F==="--check-files")m=!0;else if(F==="--plan-format"){if(G!=="text"&&G!=="json")return c(`error: --plan-format must be text or json
|
|
2464
|
+
`),1;v=G}else if(F==="--dry-loop-limit"||F==="--dryrun-timeout"){if(!/^[0-9]+$/.test(G)||!Number.isSafeInteger(Number(G))||Number(G)<=0)return c("error: "+F+` requires a positive safe integer
|
|
2465
|
+
`),1;F==="--dry-loop-limit"?b=Number(G):_=Number(G)}else d=!0}if(h&&(g||d||y))return c(`error: --trace records a real run and cannot be combined with --check, --lint, --check-files, --dry-run or --no-preflight
|
|
2465
2466
|
`),1;if(g&&d||g&&y||x.has("--plan-format")&&!g)return c(`error: incompatible execution modes/options
|
|
2466
|
-
`),1;d=d||m&&!g;let O=["--dry-loop-limit","--dryrun-timeout"].find(
|
|
2467
|
+
`),1;d=d||m&&!g;let O=["--dry-loop-limit","--dryrun-timeout"].find(F=>x.has(F));if(O&&!g&&(d||y)){let F=["--check","--lint","--check-files","--no-preflight"].filter(G=>x.has(G));return c("error: "+O+" bounds only the dry pass and has no effect with "+F.join(" and ")+`
|
|
2467
2468
|
`),1}let A=n.shift(),w=A==="help"||A==="--help"||A==="-h";if(E!==void 0&&w)return c(`error: --pref cannot be used with help
|
|
2468
2469
|
`),1;if(!A||A.startsWith("-")&&!["-e","-","--help","-h"].includes(A))return c((A?.startsWith("-")?"error: Unknown option "+A+`
|
|
2469
2470
|
`:"")+T_+`
|
|
2470
2471
|
`),1;let T,k;try{if(w)T=n[0]!==void 0&&Oo(n[0])?"import "+JSON.stringify(ao(r,n[0]))+`;
|
|
2471
2472
|
`:n[0]!==void 0&&vs(n[0])?"import "+JSON.stringify(n[0])+`;
|
|
2472
|
-
`:"";else if(A==="-e"){let
|
|
2473
|
-
`),1;T
|
|
2474
|
-
`),1}let I;if(E!==void 0)try{I=rb(E)}catch(
|
|
2475
|
-
`),Ie}let C=f??k??(A==="-"?"<stdin>":"<inline>"),M=new Er;M.setGlobal("args",[...n]),M.setGlobal("ARGV",[...n]);let D=new AbortController,j=new Set
|
|
2476
|
-
`),1}for(let[
|
|
2477
|
-
`);for(let
|
|
2478
|
-
`),stderr
|
|
2479
|
-
`)
|
|
2480
|
-
`),...I?{propertyOverlay:I}:{}},me,ee=await M.scanAndCheckAsync(T,ne);if(ne.preparedCheck=ee,w&&!ee.diagnostics.some(
|
|
2473
|
+
`:"";else if(A==="-e"){let F=n.shift();if(F===void 0)return c(T_+`
|
|
2474
|
+
`),1;T=F}else if(A==="-")if(e.stdin){T="";for await(let F of e.stdin)T+=String(F)}else T=KN(0,"utf8");else k=ao(r,A),T=KN(k,"utf8")}catch(F){return c(`error:${k??A}:1:1: ${F instanceof Error?F.message:String(F)}
|
|
2475
|
+
`),1}let I;if(E!==void 0)try{I=rb(E)}catch(F){let G=F,Ie=d?2:1;return c(`error:${G.path}:${G.line}:${G.column}: ${G.message}
|
|
2476
|
+
`),Ie}let C=f??k??(A==="-"?"<stdin>":"<inline>"),M=new Er;M.setGlobal("args",[...n]),M.setGlobal("ARGV",[...n]);let D=new AbortController,j=new Set,$=new Map,Z=new Map,q={name:"native:git",nativeNamespace:"git",declarations:x_,activate:async F=>{let{createGit:G}=await Promise.resolve().then(()=>(cb(),lb));return G(F)}};M.registerNativeModule(q),$.set("native:git",q);try{let{createLmctlHostModule:F}=await Promise.resolve().then(()=>(DC(),PC)),G=F({stdout:i,stderr:c,stdin:e.stdin,onContext:Ie=>j.add(Ie),nativeModules:[q]});M.registerBuiltinProvider(G),$.set("lmctl",G)}catch(F){if(!["ERR_MODULE_NOT_FOUND","ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(F?.code??""))throw F;Z.set("lmctl",F)}try{let{createLmbeeHostModule:F}=await Promise.resolve().then(()=>(ZC(),QC)),G=F();M.registerBuiltinProvider(G),$.set("lmbee",G)}catch(F){if(!["ERR_MODULE_NOT_FOUND","ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(F?.code??""))throw F;Z.set("lmbee",F)}try{let{createSchemaModuleFactory:F}=await Promise.resolve().then(()=>(CN(),AN));M.registerSchemaModuleFactory(F())}catch(F){if(!["ERR_MODULE_NOT_FOUND","ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(F?.code??""))throw F;Z.set("schema-modules",F)}let Y;try{let{createModuleResolver:F}=await Promise.resolve().then(()=>(VN(),JN));Y=F({mode:w||d||g?"cache":"run",env:s,cwd:r,overrides:R,...e.moduleRoot!==void 0?{root:e.moduleRoot}:{},...e.moduleFetch?{fetchImpl:e.moduleFetch}:{},...e.moduleNow?{now:e.moduleNow}:{}}),M.registerModuleSpecResolver(Y.resolve)}catch(F){let G=F?.code??"";if(["ERR_MODULE_NOT_FOUND","ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(G))Z.set("module-store",F);else return c("error: "+(F instanceof Error?F.message:String(F))+`
|
|
2477
|
+
`),1}for(let[F,G]of Z)c(`warning: ${F} host module unavailable: ${G.code}: ${G instanceof Error?G.message:String(G)}
|
|
2478
|
+
`);for(let F of e.builtinProviders??[])M.registerBuiltinProvider(F);let ne={executionOrigin:wr({source_kind:k?"file":A==="-"?"stdin":A==="-e"?"inline":"unknown",script_file:k??null,source_name:C}),noPreflight:y,dryLoopLimit:b,dryrunTimeoutMs:_,resumepoint:u,file:f??k,entryLocation:k,baseDir:p??(k?_J(k):r),builtinProviderNames:["lmctl","lmbee",...(e.builtinProviders??[]).map(F=>F.name)],reservedFunctionPrefixes:["lm_","lmbee_"],checkFiles:m,checkPaths:m||!d,hostContext:{cwd:r,env:s,platform:e.platform??process.platform},stdout:(F,G)=>i(G?F:F+`
|
|
2479
|
+
`),stderr:F=>c(F.endsWith(`
|
|
2480
|
+
`)?F:F+`
|
|
2481
|
+
`),...I?{propertyOverlay:I}:{}},me,ee=await M.scanAndCheckAsync(T,ne);if(ne.preparedCheck=ee,w&&!ee.diagnostics.some(F=>F.severity==="error")){let F=n[0]!==void 0&&(Oo(n[0])||vs(n[0]))?ee.hostModules?.find(Ie=>Ie.name.startsWith("schema:")):void 0;if(F){let Ie=vs(n[0])?[...Y?.provenance.values()??[]][0]:void 0;return i(tb(F,Ie?Ie.key:ao(r,n[0]),Ie)),0}let G=eb(M,[...new Map([...$.values(),...ee.hostModules??[]].map(Ie=>[Ie.name,Ie])).values()],n[0]);return G===void 0?(c("error: unknown help target "+n[0]+`
|
|
2481
2482
|
`),1):(i(T_+`
|
|
2482
|
-
`+
|
|
2483
|
-
`))},W,
|
|
2484
|
-
`)}catch(Ie){
|
|
2485
|
-
`)}M.terminateResourceRuns()},ei=(
|
|
2483
|
+
`+G),0)}for(let F of ee.diagnostics)c(ll(F,C));if(ee.diagnostics.some(F=>F.severity==="error"))return 2;if(d)return 0;let st={currentPath:null};ne.recoveryProbe=st;let Ve=!1,B=()=>{let F=st.firstFailure?.path;Ve||F==null||(Ve=!0,pe("resumepoint: "+F+" (rerun with --resumepoint "+F+`)
|
|
2484
|
+
`))},W,J,pe=F=>{try{c(F)}catch{}},kt=F=>{for(let G of j)try{let Ie=G.finalizeSync(F);for(let ul of Ie.errors)pe("error: resource critical finalization: "+ul+`
|
|
2485
|
+
`)}catch(Ie){pe("error: resource critical finalization: "+String(Ie)+`
|
|
2486
|
+
`)}M.terminateResourceRuns()},ei=(F,G=F==="SIGINT"?130:143)=>{W===void 0&&(W=G,st.firstFailure??={path:st.currentPath},kt(F),D.abort(F),J=setTimeout(()=>{B(),process.exit(W)},250))},ti=()=>ei("SIGINT"),ni=()=>ei("SIGTERM"),cl=()=>ei("SIGTERM",129);if(e.installSignals!==!1&&!e.stdout&&!ZN&&(ZN=!0,process.stdout.on("error",F=>{if(F.code!=="EPIPE")throw F;kt("SIGTERM"),process.exit(0)})),e.installSignals!==!1){process.on("SIGINT",ti),process.on("SIGTERM",ni),process.on("SIGHUP",cl);let F=Number(s.LMSCRIPT_LIFELINE_FD);if(delete s.LMSCRIPT_LIFELINE_FD,e.env||delete process.env.LMSCRIPT_LIFELINE_FD,Number.isInteger(F)&&F>2)try{if(zN(F).isFIFO()||zN(F).isSocket()){let G=new yJ({fd:F,readable:!0,writable:!1});G.on("error",()=>{}),G.on("end",ni),G.on("close",ni),G.resume(),G.unref()}}catch{}}ne.signal=D.signal;try{if(h){let Ae=vJ(h,[...k?[k]:[],...ee.compiledSource?.loadedFiles.slice(1)??[],...Array.from(Y?.provenance.values()??[],Ke=>Ke.file)]);if(Ae)return c("error: --trace output aliases source file "+Ae+`
|
|
2486
2487
|
`),1;try{me=hJ(h,"w")}catch(Ke){return c("error: cannot open trace file "+h+": "+(Ke instanceof Error?Ke.message:String(Ke))+`
|
|
2487
|
-
`),1}ne.trace={write:Ke=>bJ(me,Ke),engine:"lmscript "+lp()}}let
|
|
2488
|
-
`),W??Ae.exitCode)}ne.onPreflight=
|
|
2488
|
+
`),1}ne.trace={write:Ke=>bJ(me,Ke),engine:"lmscript "+lp()}}let F=new Set(ee.diagnostics.map(Ae=>JSON.stringify(Ae))),G=Ae=>{if(!(W!==void 0||!g))for(let Ke of Ae.diagnostics)F.has(JSON.stringify(Ke))||(c(ll(Ke,C)),F.add(JSON.stringify(Ke)))};if(g){let Ae=await M.dryRunAsync(T,ne);return W!==void 0?(c(ll({severity:"error",message:"Execution aborted",line:1,column:1},C)),W):(G(Ae),i(Vv(Ae,v)+`
|
|
2489
|
+
`),W??Ae.exitCode)}ne.onPreflight=G;let Ie;try{Ie=await M.runAsync(T,ne)}finally{if(me!==void 0){let Ae=me;me=void 0,QN(Ae)}}for(let Ae of Ie.diagnostics)F.has(JSON.stringify(Ae))||c(ll(Ae,C));let ul=Ae=>{let Ke=l.findIndex(R_=>R_==="error: "+Ae||R_==="error: "+Ae+`
|
|
2489
2490
|
`);return Ke<0?Number.MAX_SAFE_INTEGER:Ke},dl=[...new Set(Ie.errors??[])].filter(Ae=>!a.has(Ae)).sort((Ae,Ke)=>ul(Ae)-ul(Ke));if(dl.length){c(`
|
|
2490
2491
|
=== LMScript Error Summary (${dl.length} error${dl.length===1?"":"s"}) ===
|
|
2491
2492
|
`);for(let[Ae,Ke]of dl.entries())c(` ${Ae+1}. ${Ke}
|
|
2492
2493
|
`);c(`==========================================
|
|
2493
|
-
`)}let k_=W??(Ie.exitCode!==void 0?Ie.exitCode:Ie.success&&!Ie.errors?.length?0:1);return k_!==0&&B(),k_}catch(
|
|
2494
|
-
`),B(),W??1)}finally{if(me!==void 0){let
|
|
2495
|
-
`)}}W===void 0&&(clearTimeout(
|
|
2494
|
+
`)}let k_=W??(Ie.exitCode!==void 0?Ie.exitCode:Ie.success&&!Ie.errors?.length?0:1);return k_!==0&&B(),k_}catch(F){return F?.code==="EPIPE"?W??0:(c(`error:${C}:1:1: ${F instanceof Error?F.message:String(F)}
|
|
2495
|
+
`),B(),W??1)}finally{if(me!==void 0){let F=me;me=void 0;try{QN(F)}catch(G){pe("error: closing trace: "+String(G)+`
|
|
2496
|
+
`)}}W===void 0&&(clearTimeout(J),process.removeListener("SIGINT",ti),process.removeListener("SIGTERM",ni),process.removeListener("SIGHUP",cl));for(let F of j)await F.close()}}var ZN,T_,cp=L(()=>{"use strict";I_();nb();sb();ai();ZN=!1,T_="Usage: lmscript [--check|--dry-run|--lint] [--no-preflight] [--trace FILE] [--dry-loop-limit N] [--dryrun-timeout MS] [--plan-format text|json] [--resumepoint PATH] [--pref FILE] [--module SPEC=FILE]... [--check-files] [--base-dir dir] [--source-name label] <file>|-| -e <code> [args...]"});cp();async function Jae(){process.exitCode=await S_(process.argv.slice(2))}export{Jae as main};
|