@lmctl-ai/lmctl 0.2.243 → 0.2.244
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/index.js +128 -128
- package/dist/cli/lmscript.js +77 -77
- package/dist/cli/native-holder-worker.js +33 -33
- package/package.json +1 -1
package/dist/cli/lmscript.js
CHANGED
|
@@ -5,7 +5,7 @@ var NC=Object.create;var id=Object.defineProperty;var OC=Object.getOwnPropertyDe
|
|
|
5
5
|
`),i=String(t.line),o=t.line-1,a=s[o]??"",l=" | ",c=` ${i.padStart(4," ")} | `,u=" ".repeat(Math.max(0,t.column-1));return`[${t.severity.toUpperCase()} at ${n}] ${t.message}
|
|
6
6
|
`+l+`
|
|
7
7
|
${c}${a}
|
|
8
|
-
${l}${u}^`}function Hy(t,e){if(t.length<2)return t;let n=r=>[...e?.get(r.file??"")??[],r.line,r.column];return t.map((r,s)=>({diagnostic:r,index:s,key:n(r)})).sort((r,s)=>{for(let i=0;i<Math.min(r.key.length,s.key.length);i++)if(r.key[i]!==s.key[i])return r.key[i]-s.key[i];return r.key.length-s.key.length||r.index-s.index}).map(r=>r.diagnostic)}function vy(t,e,n=[],r){let s=t instanceof D?t:new D(t instanceof Error?t.message:String(t),1,1,"CHECKER",e);return t instanceof Vi&&(n=t.diagnostics,r=t.diagnosticPaths),Hy([...n,{severity:"error",message:s.message,line:s.line,column:s.column,file:s.file??e}],r)}function By(t){if(typeof t!="string"||t.length!==1||/["\r\n]/.test(t))throw new Error("CSV delimiter must be one character other than a quote or newline")}function ht(t,e){return t&&typeof t=="object"&&Ds.has(t)?Ds.get(t)(String(e)):t!=null&&Object.hasOwn(t,e)?t[e]:void 0}function
|
|
8
|
+
${l}${u}^`}function Hy(t,e){if(t.length<2)return t;let n=r=>[...e?.get(r.file??"")??[],r.line,r.column];return t.map((r,s)=>({diagnostic:r,index:s,key:n(r)})).sort((r,s)=>{for(let i=0;i<Math.min(r.key.length,s.key.length);i++)if(r.key[i]!==s.key[i])return r.key[i]-s.key[i];return r.key.length-s.key.length||r.index-s.index}).map(r=>r.diagnostic)}function vy(t,e,n=[],r){let s=t instanceof D?t:new D(t instanceof Error?t.message:String(t),1,1,"CHECKER",e);return t instanceof Vi&&(n=t.diagnostics,r=t.diagnosticPaths),Hy([...n,{severity:"error",message:s.message,line:s.line,column:s.column,file:s.file??e}],r)}function By(t){if(typeof t!="string"||t.length!==1||/["\r\n]/.test(t))throw new Error("CSV delimiter must be one character other than a quote or newline")}function ht(t,e){return t&&typeof t=="object"&&Ds.has(t)?Ds.get(t)(String(e)):t!=null&&Object.hasOwn(t,e)?t[e]:void 0}function et(t,e,n){String(e)==="__proto__"?Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0}):t[e]=n}function Dd(t,e,n){if(t==null||t===""||t===!1||Array.isArray(t)&&t.length===0)throw n?.(String(e)),Object.assign(new At(1),{resourceFailure:String(e)});return t}function Ui(t,e){if(t==null)return;let n=Array.isArray(e)?e:String(e).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),r=t;for(let s of n){if(r==null||typeof r!="object")return;r=ht(r,s)}return r}function Wy(t){if(typeof t!="string"||!t.trim())throw new Error("http_get() requires a non-empty URL string");let e;try{e=new URL(t)}catch{throw new Error("http_get() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("http_get() only permits HTTP(S) URLs without embedded credentials");let n=`
|
|
9
9
|
const target = process.argv[1];
|
|
10
10
|
const maxBytes = ${_d};
|
|
11
11
|
const controller = new AbortController();
|
|
@@ -52,11 +52,11 @@ try {
|
|
|
52
52
|
`;e.onWaiting?e.onWaiting(g):typeof process<"u"&&process.stderr&&process.stderr.write(g)}await new Promise(g=>setTimeout(g,u))}let f="";if(j.existsSync(a))try{f=j.readFileSync(a,"utf-8")}catch{}if(!f.trim()&&j.existsSync(l))try{f=j.readFileSync(l,"utf-8")}catch{}try{j.existsSync(l)&&j.unlinkSync(l)}catch{}try{j.existsSync(a)&&j.unlinkSync(a)}catch{}try{j.existsSync(o)&&j.unlinkSync(o)}catch{}try{j.existsSync(i)&&j.unlinkSync(i)}catch{}return f.replace(/\r?\n$/u,"")}function Ey(t,e=!0,n=","){By(n);let r=[],s=[],i="",o=!1,a=!1,l=!1;for(let d=0;d<t.length;d++){let m=t[d],p=t[d+1];if(l=!0,o)m==='"'?p==='"'?(i+='"',d++):(o=!1,a=!0):i+=m;else{if(a&&m!==n&&m!=="\r"&&m!==`
|
|
53
53
|
`)throw new Error("Invalid CSV: unexpected character after closing quote");if(m==='"'){if(i.length>0)throw new Error("Invalid CSV: quote inside unquoted field");o=!0}else m===n?(a=!1,s.push(i),i=""):m==="\r"?(p===`
|
|
54
54
|
`&&d++,s.push(i),r.push(s),s=[],i="",a=!1,l=!1):m===`
|
|
55
|
-
`?(s.push(i),r.push(s),s=[],i="",a=!1,l=!1):i+=m}}if(o)throw new Error("Invalid CSV: unterminated quoted field");if(l&&(s.push(i),r.push(s)),!e)return r.map(d=>d.map(Ty));if(r.length===0)return[];let c=r[0].map(d=>d.trim()),u=[];for(let d=1;d<r.length;d++){let m=r[d],p={};for(let f=0;f<c.length;f++)
|
|
55
|
+
`?(s.push(i),r.push(s),s=[],i="",a=!1,l=!1):i+=m}}if(o)throw new Error("Invalid CSV: unterminated quoted field");if(l&&(s.push(i),r.push(s)),!e)return r.map(d=>d.map(Ty));if(r.length===0)return[];let c=r[0].map(d=>d.trim()),u=[];for(let d=1;d<r.length;d++){let m=r[d],p={};for(let f=0;f<c.length;f++)et(p,c[f],f<m.length?Ty(m[f]):null);u.push(p)}return u}function Ty(t){let e=t.trim();if(e==="")return"";if(/^-?\d+$/.test(e)){let n=Number(e);if(!Number.isNaN(n))return n}if(/^-?\d+\.\d+$/.test(e)){let n=Number(e);if(!Number.isNaN(n))return n}return e.toLowerCase()==="true"?!0:e.toLowerCase()==="false"?!1:e.toLowerCase()==="null"?null:t}function Sy(t,e=","){if(By(e),!Array.isArray(t)||t.length===0)return"";let n=t[0];if(Array.isArray(n))return t.map(r=>r.map(s=>Ma(s,e)).join(e)).join(`
|
|
56
56
|
`);if(typeof n=="object"&&n!==null){let r=Object.keys(n),s=r.map(o=>Ma(o,e)).join(e),i=t.map(o=>r.map(a=>Ma(ht(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
57
57
|
`)}return t.map(r=>Ma(r,e)).join(`
|
|
58
58
|
`)}function Ma(t,e){let n=t==null?"":String(t);return n===""||n.includes(e)||n.includes('"')||n.includes(`
|
|
59
|
-
`)||n.includes("\r")?`"${n.replaceAll('"','""')}"`:n}function mN(t){return/^[A-Za-z_]\w*$/.test(t)&&!Object.hasOwn(zi,t)}function Iy(t,e){let n=(i,o=t)=>{throw new D("command: "+i,o.line,o.column,"RUNTIME",o.file)},r=(i,o)=>{if(typeof i!="string"&&typeof i!="number")return n("arguments must be strings or numbers (or a whole-word list of them)",o);let a=String(i);return a.includes("\0")?n("NUL is not allowed in argv",o):a},s=[];return t.words.forEach((i,o)=>{if(i.pieces.length===1&&typeof i.pieces[0]!="string"&&Array.isArray(e[o][0])){let l=e[o][0];o===0&&l.length===0&&n("a program is required; first-word list is empty",i);for(let c of l)s.push(r(c,i))}else s.push(e[o].map((l,c)=>r(l,typeof i.pieces[c]=="string"?i:i.pieces[c])).join(""))}),(!s.length||!s[0])&&n("a non-empty program is required"),s}function qi(t,e,n="native"){if(typeof e!="string")throw new Error("Regex flags must be a string");let r=new Set;for(let s of e){if(!"dgimsuvy".includes(s))throw new Error(`Unsupported regex flag '${s}'`);if(r.has(s))throw new Error(`Duplicate regex flag '${s}'`);r.add(s)}if(r.has("u")&&r.has("v"))throw new Error("Regex flags cannot combine 'u' and 'v' Unicode modes");if(n!=="native"&&r.has("y"))throw new Error("Sticky regex flag 'y' is incompatible with capture helpers that search anywhere");try{return new RegExp(t,n==="all"&&!r.has("g")?e+"g":e)}catch(s){throw new Error(`Invalid regex pattern: ${s instanceof Error?s.message:String(s)}`)}}function Yy(t){return Array.from(t,e=>e===void 0?null:e)}function pN(t,e,n=""){let r=qi(e,n,"first").exec(String(t));return r===null?null:Yy(r)}function fN(t,e,n=""){let r=qi(e,n,"all"),s=String(t),i=n.includes("u")||n.includes("v"),o=[],a;for(;(a=r.exec(s))!==null;)if(o.push(Yy(a)),a[0]===""){let l=r.lastIndex;if(l>=s.length)break;let c=s.charCodeAt(l),u=s.charCodeAt(l+1),d=i&&c>=55296&&c<=56319&&u>=56320&&u<=57343?2:1;r.lastIndex=l+d}return o}function xy(t,e,n){try{if(n){if(n.at(e),t!==null&&typeof t=="object"&&Ee.isProxy(t))throw Error("Dry iterable cannot be a proxy");let s=[];if(Array.isArray(t)){if(![Array.prototype,null].includes(Object.getPrototypeOf(t)))throw Error("Dry iterable must be a plain array");let i=Math.min(t.length,n.loopLimit);for(let o=0;o<i;o++){n.check();let a=Object.getOwnPropertyDescriptor(t,String(o));if(a&&!("value"in a))throw Error("Dry iterable cannot contain accessors");s.push(a?.value)}return s}if(typeof t=="string"){for(let i of t)if(n.check(),s.push(i),s.length===n.loopLimit)break;return s}if(t!==null&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t))){if(Hd(t))throw Error("Dry iterable must be plain data");for(let i in t)if(n.check(),!!Object.hasOwn(t,i)&&(s.push(i),s.length===n.loopLimit))break;return s}}if(Array.isArray(t))return Array.from({length:t.length},(s,i)=>t[i]);if(typeof t=="string")return Array.from(t);if(t!==null&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.keys(t);let r=t===null?"null":t instanceof Date?"Date":typeof t;throw new D(`Cannot iterate value of type ${r}; expected list, map or string`,e.line,e.column,"RUNTIME",e.file)}catch(r){throw r instanceof D||n&&r?.isControlFlow?r:new D(`Cannot snapshot iterable: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,"RUNTIME",e.file)}}function bd(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let n of Object.keys(t)){let r=t[n];if(Array.isArray(r))for(let s of r)bd(s,e);else r&&typeof r=="object"&&bd(r,e)}}}function Xi(t,e="Call to undefined function"){let n=`${e} '${t}'`;if(!Object.hasOwn(Wa,t))return n;let r=n+`; did you mean '${Wa[t]}'?`;return t==="json"?r+" Use json_stringify for serialization.":t==="count"?r+" Use count_matches for substring occurrences.":t==="parseInt"||t==="parseFloat"?r+" num uses whole-value Number conversion; it does not provide prefix parsing or integer truncation.":r}function hN(){if(!md){let e=new Ba(gN,"<std>").tokenize(),r=new qa(e,"<std>").parse();for(let s of r.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);md=r}return{kind:"Program",statements:[...md.statements],line:1,column:1,file:"<std>"}}function Yr(t){return t&&typeof t=="object"&&Yi.has(t)?Yi.get(t)():t}function wd(t){if(typeof t!="string"||!/^[_a-zA-Z]\w*(?:\.[_a-zA-Z]\w*)*$/.test(t))throw Error(`Invalid property key '${String(t)}'; use dotted identifier segments`);return t}function Xa(t,e){return e.find(n=>{let r=n.lastIndexOf(".");return n===t||r>=0&&t===n.slice(0,r+1)+n.slice(r+1).toLowerCase()})??t}function Dn(t,e,n=new Set){if(t instanceof Date)return t.toISOString();if(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(t&&typeof t=="object"){if(!Array.isArray(t)&&![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw Error(`Property '${e}' has an unsupported object value`);if(n.has(t))throw Error(`Property '${e}' contains a cycle`);n.add(t);try{if(Array.isArray(t))return t.map((s,i)=>Dn(s,e+"."+i,n));let r={};for(let[s,i]of Object.entries(t))Ze(r,s,Dn(i,e?e+"."+s:s,n));return r}finally{n.delete(t)}}throw Error(`Property '${e}' has an unsupported value type: ${typeof t}`)}function Fs(t){let e=Dn(t.properties,"");if(!e||typeof e!="object"||Array.isArray(e))throw Error("Property document must be a table in "+t.path);for(let n of["Directory","NonInteractive"])if(Object.hasOwn(e,n))throw Error("Property '"+n+"' is read-only in "+t.path);return{...t,properties:e}}function Ps(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date)}function Ed(t,e,n,r=""){let s={};for(let[i,o]of Object.entries(t)){let a=r?r+"."+i:i,l=/^[_a-zA-Z]\w*$/.test(i)?Xa(a,e):a,c=l===a?i:l.slice(l.lastIndexOf(".")+1);if(Object.hasOwn(s,c))throw Error("Ambiguous property '"+l+"' in "+n);Ze(s,c,Ps(o)?Ed(o,e,n,l):structuredClone(o))}return s}function Qy(t,e,n,r,s=""){let i=structuredClone(t);for(let[o,a]of Object.entries(e)){let l=s?s+"."+o:o;if(Object.hasOwn(t,o)&&Ps(t[o])!==Ps(a))throw Error("Property '"+l+"' cannot merge a table and a value between "+n+" and "+r);Ze(i,o,Object.hasOwn(t,o)&&Ps(t[o])&&Ps(a)?Qy(t[o],a,n,r,l):structuredClone(a))}return i}function Ja(t){if(t.kind==="IdentifierExpr"&&t.name==="PROPS")return"";if(t.kind==="IndexExpr"&&t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"){let e=Ja(t.target);if(e!==void 0)return e?e+"."+t.index.value:t.index.value}}function Hi(t,e){return Mn.run(void 0,()=>t.fn(...e))}function yN(t,e,n,r,s){return function(...i){let o=this,a={run:t,module:e,readonly:n,async:r,active:!0};return Mn.run(a,()=>{try{let l=s.apply(o,i);return Qe(l)?Promise.resolve(l).finally(()=>{a.active=!1}):(a.active=!1,l)}catch(l){throw a.active=!1,l}})}}function _N(t){if(Ee.isProxy(t))throw Error("Grant declarations cannot be a proxy");let e=Object.getOwnPropertyDescriptor(t,"readonlyPrograms");if(!e)return[];if(!("value"in e))throw Error("readonlyPrograms must be data");let n=en(e.value),r=s=>Array.from({length:s.length},(i,o)=>Object.hasOwn(s,o)).every(Boolean);if(!Array.isArray(n)||!r(n)||n.some(s=>!Array.isArray(s)||!r(s)||!s.length||!s[0]||s.some(i=>typeof i!="string"||i.includes("\0"))))throw Error("Invalid readonlyPrograms prefixes");return Object.freeze(n.map(s=>Object.freeze(s)))}function Bi(t,e={currentPath:null}){return zr(e),{finished:!1,probe:e,errors:[],pending:t?t.split("."):[],entered:new Set,stack:[],envs:new Map,active:!1,rootTaskId:-1}}function zr(t){t&&(t.currentPath=null,delete t.firstFailure)}function Ud(t){t.finished||(t.probe.firstFailure??={path:t.probe.currentPath})}function vN(t){let e=t;return!!(t instanceof At||e?.name==="LMScriptExit"||e?.isControlFlow)&&(typeof e?.exitCode=="number"?e.exitCode:0)===0}function Cy(t,e){let n=()=>Ud(t);return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&n(),()=>e?.removeEventListener("abort",n)}function xt(t,e){e instanceof ar||e instanceof qt||e instanceof Xt||vN(e)||Ud(t)}function Fa(t,e){t.finished||(Ud(t),t.errors.push(e))}function wN(t,e){let n=e.resumepoint;if(n===void 0||!t.ast)return[];let r={severity:"error",line:1,column:1,file:e.file};if(typeof n!="string"||!bN.test(n))return[{...r,message:`Invalid resumepoint path: ${String(n)}; expected NAME(.NAME)*`}];if(!t.hasRecover)return[{...r,message:"Script has no recover block"}];let s=n.split(".")[0];return t.recoverLabels?.includes(s)?[]:[{...r,message:`Unknown resumepoint '${s}': no recover block declares this point`}]}function Kr(t,e){let n=t.diagnostics.filter(s=>!t.resumepointDiagnostics?.includes(s)),r=wN(t,e);return{...t,diagnostics:Hy([...n,...r],t.diagnosticPaths),resumepointDiagnostics:r}}function Qi(t){return!t.startsWith("native:")&&!t.startsWith("@")&&(/\.cli\.schema\.v1\.json$/.test(t)||/(?:^|[\\/])cli\.schema\.(?:latest|dev)\.json$/.test(t))}function es(t){return t.startsWith("@")}function Zy(t){return t.trim().length>0&&!/[\0\r\n]/.test(t)&&!/[\/\\]/.test(t)&&!t.startsWith(".")&&!t.endsWith(".lms")}function EN(t){let e=t instanceof Error&&t.name!=="Error"?`${t.name}: `:"",n=t instanceof Error?t.message:String(t),r=[];for(let i of n.split(/\r?\n/)){if(/^\s*Require stack:\s*$/.test(i))break;/^\s*(?:at\s|-\s)/.test(i)||r.push(i)}let s=r.join(" ").replace(/__lmscript_modules__\.cjs/g,"").replace(/(?:file:\/\/)?(?:[A-Za-z]:)?[\\/][^\s'"<>]+/g,"<module file>").replace(/\s+/g," ").trim();return(e+(s||"module loading failed")).trim()}function Ke(t){if(t?.aborted)throw new Error("Execution aborted")}function Qe(t){return t!==null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function $a(t,e,n){if(/^https?:/i.test(t)||/^https?:/i.test(e??"")){let s=/^https?:/i.test(t)?new URL(t):new URL(t,e);if(!["http:","https:"].includes(s.protocol))throw Error("Only http/https module URLs are supported");return s.hash="",s.href}let r=re.resolve(e&&e!=="<main>"&&!e.startsWith("<")?re.dirname(e):n,t);try{return j.realpathSync(r)}catch{return r}}function e_(t){if(t.kind==="IdentifierExpr")return t.name;if(t.kind==="IndexExpr"&&t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"){let e=e_(t.target);if(e)return e+"."+t.index.value}}function Td(t){let e=new Set,n=r=>{if(!(!r||typeof r!="object")){r.kind==="AssignExpr"&&e.add(r.target),r.kind==="TupleAssignExpr"&&r.targets.forEach(s=>e.add(s));for(let s of Object.values(r))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};for(let r of t.statements)(r.kind==="FunctionDeclStmt"||r.kind==="VarDeclStmt")&&e.add(r.name),r.kind==="TupleVarDeclStmt"&&r.names.forEach(s=>e.add(s)),r.kind==="ExprStmt"&&n(r.expr);return e}function TN(t,e){let n=Td(t),r=(o,a)=>n.has(o)&&!a.locals.has(o)?e+"."+o:o,s=(o,a)=>{if(!o||typeof o!="object")return o;let l={...o};if(o.kind==="IdentifierExpr")return l.name=r(o.name,a),l;if(o.kind==="AssignExpr"||o.kind==="TupleAssignExpr"){l.value=s(o.value,a);let u=(o.kind==="AssignExpr"?[o.target]:o.targets).map(d=>a.fn?(a.locals.add(d),d):r(d,a));return o.kind==="AssignExpr"?l.target=u[0]:l.targets=u,l}o.kind==="CallExpr"&&(l.callee=n.has(o.callee)&&!a.locals.has(o.callee)?e+"."+o.callee:o.callee);for(let[c,u]of Object.entries(o))c!=="callee"&&(Array.isArray(u)?l[c]=u.map(d=>d&&typeof d=="object"?s(d,a):d):u&&typeof u=="object"&&(l[c]=s(u,a)));return l},i=(o,a)=>{let l={...o};if(o.kind==="FunctionDeclStmt")return l.name=e+"."+o.name,l.body=i(o.body,{locals:new Set(o.params),root:!1,fn:!0}),l;if(o.kind==="BlockStmt"){let c={...a,locals:new Set(a.locals),root:!1};return l.statements=o.statements.map(u=>i(u,c)),l}if(o.kind==="RecoverStmt"){let c={...a,locals:new Set(a.locals),root:!1};return l.points=o.points.map(u=>({...u,statements:u.statements.map(d=>i(d,c))})),l}if(o.kind==="VarDeclStmt"||o.kind==="TupleVarDeclStmt"){o.initializer&&(l.initializer=s(o.initializer,a));let u=(o.kind==="VarDeclStmt"?[o.name]:o.names).map(d=>a.root?r(d,a):(a.locals.add(d),d));return o.kind==="VarDeclStmt"?l.name=u[0]:l.names=u,l}if(o.kind==="ForInStmt"){l.iterable=s(o.iterable,a);let c={...a,root:!1,locals:new Set(a.locals)};return c.locals.add(o.name),l.body=i(o.body,c),l}if(o.kind==="ForStmt"){let c={...a,root:!1,locals:new Set(a.locals)};return o.init&&(l.init=i(o.init,c)),o.condition&&(l.condition=s(o.condition,c)),o.update&&(l.update=s(o.update,c)),l.body=i(o.body,c),l}o.kind==="SyncAssignStmt"&&(l.target=r(o.target,a));for(let[c,u]of Object.entries(o))c==="target"&&o.kind==="SyncAssignStmt"||u&&typeof u=="object"&&(l[c]=u.kind?.endsWith("Stmt")?i(u,a):s(u,a));return l};return{...t,statements:t.statements.map(o=>i(o,{locals:new Set,root:!0,fn:!1}))}}function*t_(t,e){let n=e.file??"<main>",r=e.baseDir??(e.file&&!/^https?:/i.test(e.file)?re.dirname(re.resolve(e.file)):process.cwd()),s=[],i=new Map,o=new Map,a=[],l=[],c=new Map,u=new Map,d=new Map([[n,[]]]);try{for(let _ of e.modules??[]){if(!Zy(_))throw new D("modules option requires a host module name",1,1,"CHECKER",n);if(e.builtinProviderNames?.includes(_))throw new D(_+" functions are built in; remove this line",1,1,"CHECKER",n);l.push({name:_,line:1,column:1,file:n})}let m=(_,v)=>{let E=new Ba(_,v),I;try{I=E.tokenize()}finally{s.push(...E.diagnostics)}return new qa(I,v).parse()},p=(_,v,E,I)=>{let T;try{T=e.schemaModule({text:E,location:v,..._.alias!==void 0?{alias:_.alias}:{}})}catch(C){throw I("Invalid schema module "+_.path+": "+(C instanceof Error?C.message:String(C)))}let k=T.nativeNamespace;if(!k||T.name!=="schema:"+k||!mN(k))throw I(`Invalid schema module ${_.path}: namespace ${JSON.stringify(k)} is not a usable identifier; import it with as <identifier>`);for(let[C,O]of e.nativeModules??[])if(O.namespace===k)throw I("Namespace collision: "+k+" is the native module "+C+"; import the schema with as <name>");let N=o.get(k);if(N)throw I("Namespace collision: "+k+" is already imported from "+N.location+"; import the schema with as <name>");return u.set(v,k),c.set(T.name,T),a.push(v),o.set(k,{location:v,members:T.declarations.functions.map(C=>C.name)}),l.push({name:T.name,line:_.line,column:_.column,file:_.file}),{kind:"PackageStmt",name:k,nativeModule:T.name,line:_.line,column:_.column,file:_.file}};function*f(_,v){let E=_.statements.find(T=>T.kind==="PackageStmt");if(E&&_.statements[0]!==E)throw new D("package must be the first statement in its file",E.line,E.column,"CHECKER",v);if(_.statements.filter(T=>T.kind==="PackageStmt").length>1)throw new D("Only one package declaration is allowed",E.line,E.column,"CHECKER",v);if(E?.kind==="PackageStmt"){if(Td(_).has(E.name))throw new D("Package name collision: "+E.name+" is also a module variable/function",E.line,E.column,"CHECKER",v);let T=o.get(E.name);if(T&&T.location!==v)throw new D("Duplicate package "+E.name+": "+T.location+" and "+v,E.line,E.column,"CHECKER",v);o.set(E.name,{location:v,members:[...Td(_)].map(k=>E.name+"."+k)}),_=TN(_,E.name)}let I=[];for(let T of _.statements){if(T.kind!=="ImportStmt"){I.push(T);continue}if(T.path.startsWith("native:")){let C=e.nativeModules?.get(T.path);if(!C)throw new D("Unknown native module "+T.path+"; it must be compiled into this build",T.line,T.column,"CHECKER",T.file);let O=o.get(C.namespace);if(O&&O.location!==T.path)throw new D("Duplicate package "+C.namespace+": "+O.location+" and "+T.path,T.line,T.column,"CHECKER",T.file);if(i.get(T.path)==="loaded")continue;i.set(T.path,"loaded"),o.set(C.namespace,{location:T.path,members:[...C.members]}),l.push({name:T.path,line:T.line,column:T.column,file:T.file}),I.push({kind:"PackageStmt",name:C.namespace,nativeModule:T.path,line:T.line,column:T.column,file:T.file});continue}if(Qi(T.path)||es(T.path)){let C=x=>new D(x,T.line,T.column,"CHECKER",T.file??v);if(!e.schemaModule)throw C("Schema module imports are not available in this host");let O;if(es(T.path)){if(!e.resolveModuleSpec)throw C("GitHub module imports (@owner/repo) are not available in this host");let x=yield{location:"module:"+T.path,specifier:T.path,from:v,node:T,module:!0};O=x.location;let A=u.get(O);if(A!==void 0){if(T.alias===void 0||T.alias===A)continue;throw C("Schema module "+O.slice(7)+" is already imported as "+A)}let M=p(T,O,x.source,C);M&&I.push(M);continue}if(/^https?:/i.test(T.path)||/^https?:/i.test(v))throw C("Schema modules are local files; "+T.path+" cannot be imported from a URL");try{O=$a(T.path,v===g?e.baseDir?re.join(r,"__entry__.lms"):g:v,r)}catch(x){throw C("Cannot resolve import "+T.path+": "+String(x))}let w=u.get(O);if(w!==void 0){if(T.alias===void 0||T.alias===w)continue;throw C("Schema module "+T.path+" is already imported as "+w)}let S=yield{location:O,specifier:T.path,from:v,node:T},R=p(T,O,S.source,C);R&&I.push(R);continue}let k;try{k=$a(T.path,v===g?e.baseDir?re.join(r,"__entry__.lms"):g:v,r)}catch(C){throw new D("Cannot resolve import "+T.path+": "+String(C),T.line,T.column,"CHECKER",v)}if(i.get(k)==="loading")throw new D("Import cycle: "+v+" -> "+k,T.line,T.column,"CHECKER",v);if(i.get(k)==="loaded")continue;let N=yield{location:k,specifier:T.path,from:v,node:T};if(k=N.location,i.get(k)==="loading")throw new D("Import cycle: "+v+" -> "+k,T.line,T.column,"CHECKER",v);i.get(k)!=="loaded"&&(d.set(k,[...d.get(v)??[],T.line,T.column]),i.set(k,"loading"),a.push(k),I.push(...yield*f(m(N.source,k),k)),i.set(k,"loaded"))}return I}let g=e.entryLocation??n;try{g!=="<main>"&&!g.startsWith("<")&&(g=$a(g,void 0,r))}catch{}d.set(g,[]),i.set(g,"loading"),a.push(g);let h=yield*f(m(t,n),g);i.set(g,"loaded");let y=_=>{if(!_||typeof _!="object")return _;let v={..._};if(_.kind==="IndexExpr"&&_.target.kind==="IdentifierExpr"&&o.has(_.target.name)&&_.index.kind==="LiteralExpr"&&typeof _.index.value=="string")return{kind:"IdentifierExpr",name:_.target.name+"."+_.index.value,line:_.line,column:_.column,file:_.file};if(_.kind==="IndexAssignExpr"&&_.target.kind==="IdentifierExpr"&&o.has(_.target.name)&&_.index.kind==="LiteralExpr"&&typeof _.index.value=="string")return{kind:"AssignExpr",target:_.target.name+"."+_.index.value,value:y(_.value),line:_.line,column:_.column,file:_.file};for(let[E,I]of Object.entries(_))Array.isArray(I)?v[E]=I.map(y):I&&typeof I=="object"&&(v[E]=y(I));return v};return{program:{kind:"Program",statements:[...e.noStdlib?[]:hN().statements,...h.map(y)],line:1,column:1,file:n},loadedFiles:a,diagnostics:s,hostImports:l,packages:o,diagnosticPaths:d,schemaModules:c}}catch(m){throw m instanceof Vi?m:new Vi(m,s,d,n)}}function n_(t,e){if(t.module)throw new D("GitHub module imports (@owner/repo) need the async runtime (runAsync / scanAndCheckAsync)",t.node.line,t.node.column,"CHECKER",t.node.file);try{if(e.moduleResolver){let n=e.moduleResolver(t.specifier,t.from);return{location:$a(n.path,void 0,e.baseDir??process.cwd()),source:n.source}}if(/^https?:/i.test(t.location))throw Error("URL imports require runAsync or scanAndCheckAsync");return{location:t.location,source:j.readFileSync(t.location,"utf8")}}catch(n){throw new D("Cannot load module "+t.location+": "+String(n instanceof Error?n.message:n),t.node.line,t.node.column,"CHECKER",t.node.file)}}function SN(t,e={}){let n=t_(t,e),r=n.next();for(;!r.done;){let s;try{s=n_(r.value,e)}catch(i){r=n.throw(i);continue}r=n.next(s)}return r.value}async function kN(t,e={}){let n=e.importCache??new Map,r=t_(t,e),s=r.next();for(;!s.done;){let i=s.value,o=n.get(i.location);o||(o=(async()=>{if(i.module)try{let l=await e.resolveModuleSpec(i.specifier);return{location:"module:"+l.key,source:l.source}}catch(l){throw new D(l instanceof Error?l.message:String(l),i.node.line,i.node.column,"CHECKER",i.node.file)}if(!/^https?:/i.test(i.location)||e.moduleResolver)return n_(i,e);try{let l=await fetch(i.location,{signal:AbortSignal.timeout(e.importTimeoutMs??5e3)});if(!l.ok)throw Error("HTTP "+l.status);return{location:i.location,source:await l.text()}}catch(l){throw new D("Cannot load module URL "+i.location+": "+String(l instanceof Error?l.message:l),i.node.line,i.node.column,"CHECKER",i.node.file)}})(),n.set(i.location,o));let a;try{a=await o}catch(l){s=r.throw(l);continue}s=r.next(a)}return s.value}function kd(t,e){t&&typeof t=="object"&&Yi.has(t)&&(t=Yi.get(t)());let n,r=o=>{throw n=e?new D("Cannot interpolate value: "+o,e.line,e.column,"RUNTIME",e.file):new Error("Cannot convert value to text: "+o),n},s=new Set,i=o=>{if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="boolean")return String(o);if(typeof o=="number")return Number.isFinite(o)?String(o):r("nonfinite number");if(typeof o!="object")return r(o===void 0?"undefined":"unsupported "+typeof o);let a=Array.isArray(o),l=Object.getPrototypeOf(o);if(!a&&l!==Object.prototype&&l!==null)return r("unsupported host object");if(s.has(o))return r("cyclic collection");s.add(o);try{if(Reflect.ownKeys(o).some(m=>typeof m=="symbol"))return r("symbol-keyed collection");let c=a?Array.from({length:o.length},(m,p)=>String(p)):Object.keys(o);if(a&&c.some(m=>!Object.hasOwn(o,m)))return r("sparse array");let u=Object.getOwnPropertyNames(o).filter(m=>!a||m!=="length");if(u.length!==c.length||u.some(m=>!c.includes(m)))return r("extra or non-enumerable collection property");let d=[];for(let m of c){let p=Object.getOwnPropertyDescriptor(o,m);if(!p)return r("sparse array");if(!Object.hasOwn(p,"value"))return r("accessor property");let f=i(p.value);d.push(a?f:JSON.stringify(m)+":"+f)}return a?"["+d.join(",")+"]":"{"+d.join(",")+"}"}finally{s.delete(o)}};try{return typeof t=="string"?t:i(t)}catch(o){if(o===n)throw o;return r("serialization failed: "+(o instanceof Error?o.message:String(o)))}}function pd(t){if(t!==null&&typeof t=="object"){let e=Object.getPrototypeOf(t);if(Array.isArray(t)||e===Object.prototype||e===null)return kd(t)}return t===null?"null":String(t)}function Ny(t){switch(t){case"boolean":return!0;case"number":return 0;case"string":return"";case"array":return[];case"map":return{};case"SystemResult":return{...xN};case"null":case void 0:default:return null}}function r_(t){if(!t)return null;let e=t.trim(),n=e.toLowerCase();return{bool:"boolean",boolean:"boolean",list:"array",array:"array",map:"map",object:"map"}[n]??e}function Cd(t){return typeof t=="object"&&t?Object.freeze({min:t.min,...t.max===void 0?{}:{max:t.max}}):t}function fd(t){if(t)return Object.freeze({...t,parameters:t.parameters?Object.freeze(t.parameters.map(e=>Object.freeze({...e}))):void 0,returns:t.returns?Object.freeze({...t.returns}):void 0})}function Nd(t){return Object.freeze({...t,values:t.values?Object.freeze([...t.values]):void 0,keys:t.keys?Object.freeze(t.keys.map(e=>Object.freeze({...e,values:e.values?Object.freeze([...e.values]):void 0}))):void 0})}function Zt(t,e,n,r,s){if(r!==void 0&&typeof r!="string")throw Error(`Function '${t}' returnType must be a string`);let i=(n??[]).map(Nd),o=i.map((f,g)=>f.name==="dryrun"?g:-1).filter(f=>f>=0);if(o.length>1)throw new Error(`Function '${t}' declares dryrun more than once`);let a=o[0];if(a!==void 0){let f=i[a];if(f.type?.toLowerCase()!=="boolean"&&f.type?.toLowerCase()!=="bool")throw new Error(`Function '${t}' dryrun parameter must be boolean`);if(!f.optional)throw new Error(`Function '${t}' dryrun parameter must be optional`);if(f.rest)throw new Error(`Function '${t}' dryrun parameter cannot be rest`);if(i.some(g=>g.rest)&&a!==0)throw new Error(`Function '${t}' dryrun with rest must place dryrun at slot zero`);if(typeof e=="number")throw new Error(`Function '${t}' must use a range arity when declaring optional dryrun`)}for(let f=0;f<i.length;f++){let g=i[f];if(g.default!==void 0&&f!==a)throw Error("Host parameter default is only supported on the reserved dryrun slot");if(g.default!==void 0&&typeof g.default!="boolean")throw new Error(`Function '${t}' dryrun default must be boolean`);if(g.optional!==void 0&&typeof g.optional!="boolean")throw Error(`Function '${t}' optional must be boolean`);if(g.rest!==void 0&&typeof g.rest!="boolean")throw Error(`Function '${t}' rest must be boolean`);if(g.rest&&(g.optional||g.default!==void 0))throw Error(`Function '${t}' rest cannot have an optional/default slot`);if(g.rest&&f!==i.length-1)throw new Error(`Function '${t}' rest parameter must be last`);if(g.optional&&f<i.length-1&&f!==a&&i.slice(f+1).some(y=>!y.optional&&!y.rest&&y.name!=="dryrun"))throw new Error(`Function '${t}' has a required parameter after an optional parameter`)}let l=i.filter((f,g)=>g!==a),c=i.reduce((f,g,h)=>!g.optional&&!g.rest?h+1:f,0),u=a!==void 0||i.some(f=>f.rest||f.default!==void 0),d=e??(u?{min:c,max:i.some(f=>f.rest)?void 0:i.length}:void 0);if(n?.length&&d&&(a!==void 0||i.some(f=>f.rest)||i.some(f=>f.default!==void 0))){let f=i.reduce((b,_,v)=>!_.optional&&!_.rest?v+1:b,0),g=i.some(b=>b.rest)?void 0:i.length,h=typeof d=="number"?d:d.min,y=typeof d=="number"?d:d.max;if(h!==f||y!==g)throw new Error(`Function '${t}' arity does not match its declared parameters`)}let m=a===void 0?d:(()=>{if(typeof d=="number")return Math.max(0,d-1);if(!d)return;let f=l.filter(h=>!h.optional&&!h.rest).length,g=d.max===void 0?void 0:Math.max(0,d.max-1);return g!==void 0&&f===g?f:{min:f,...g===void 0?{}:{max:g}}})(),p=r_(r??s?.returns?.type);return Object.freeze({name:t,nativeParams:Object.freeze(i),publicParams:Object.freeze(l),nativeArity:Cd(d),publicArity:Cd(m),dryrunIndex:a,returnType:p})}function Oy(t,e,n){if(e!==void 0&&typeof e!="boolean")throw Error(`Function '${t}' readonly must be boolean`);if(e===!0&&n.dryrunIndex===void 0)throw Error(`Function '${t}' readonly host must declare optional boolean dryrun`)}function Pa(t,e,n){if(e!==void 0){if(e!=="output"&&e!=="error")throw Error("Function "+t+" dryControl must be output or error");if(n.dryrunIndex===void 0||n.returnType!=="string")throw Error("Function "+t+" dryControl requires optional boolean dryrun and a string return type");return e}}function Wi(t,e,n=!1){let r=t.signature??Zt("<host>",t.arity,t.params,t.returnType,t.doc),s=r.publicArity,i=typeof s=="number"?s:s?.max,o=typeof s=="number"?s:s?.min;if(o!==void 0&&e.length<o||i!==void 0&&e.length>i)throw new Error(`Function '${r.name}' expects ${o??0}..${i??"unlimited"} public argument(s), but received ${e.length}`);if(r.dryrunIndex===void 0)return[...e];let a=[...e];for(;a.length<r.dryrunIndex;)a.push(void 0);return n?a.splice(r.dryrunIndex,0,!0):a.splice(r.dryrunIndex,0,r.nativeParams[r.dryrunIndex].default??!1),a}function gd(t){let n=t.stop?t.stop.file.length+t.stop.reason.length:0;for(let a of t.diagnostics)if(n+=a.message.length+(a.file?.length??0),n>1048576)break;if(n<=1048576&&Buffer.byteLength(JSON.stringify(t))<=1048576)return t;let r=(a,l)=>a.length<=l?a:a.slice(0,l)+" [truncated]",s=t.stop?{...t.stop,file:r(t.stop.file,96),reason:r(t.stop.reason,160)}:{file:"<main>",line:1,column:1,reason:"dry run truncated: plan size exceeded"},i=t.diagnostics.find(a=>a.severity==="error")??t.diagnostics[0],o=i?[{...i,message:r(i.message,160),...i.file?{file:r(i.file,96)}:{}}]:[];return o.push({severity:"warning",file:s.file,line:s.line,column:s.column,message:"dry run truncated: diagnostic metadata exceeded plan size limit ("+t.diagnostics.length+" findings)"}),{...t,status:t.status==="complete"||t.status==="loop-limited"?"truncated":t.status,stop:s,diagnostics:o}}function s_(t,e="text"){let{version:n,status:r,entries:s,stop:i,diagnostics:o}=t;if(e==="json")return JSON.stringify({version:n,status:r,entries:s,stop:i,diagnostics:o});let a=l=>/[\x00-\x1f\x7f\u2028\u2029]/.test(l)?JSON.stringify(l).replace(/[\u007f\u2028\u2029]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0")):l;return["PLAN "+r,...s.map(l=>String(l.seq)+". "+a(l.file)+":"+l.line+":"+l.column+" "+(l.kind==="loop"?l.message:l.kind+" "+a(l.function)+" "+JSON.stringify(l.arguments)))].join(`
|
|
59
|
+
`)||n.includes("\r")?`"${n.replaceAll('"','""')}"`:n}function mN(t){return/^[A-Za-z_]\w*$/.test(t)&&!Object.hasOwn(zi,t)}function Iy(t,e){let n=(i,o=t)=>{throw new D("command: "+i,o.line,o.column,"RUNTIME",o.file)},r=(i,o)=>{if(typeof i!="string"&&typeof i!="number")return n("arguments must be strings or numbers (or a whole-word list of them)",o);let a=String(i);return a.includes("\0")?n("NUL is not allowed in argv",o):a},s=[];return t.words.forEach((i,o)=>{if(i.pieces.length===1&&typeof i.pieces[0]!="string"&&Array.isArray(e[o][0])){let l=e[o][0];o===0&&l.length===0&&n("a program is required; first-word list is empty",i);for(let c of l)s.push(r(c,i))}else s.push(e[o].map((l,c)=>r(l,typeof i.pieces[c]=="string"?i:i.pieces[c])).join(""))}),(!s.length||!s[0])&&n("a non-empty program is required"),s}function qi(t,e,n="native"){if(typeof e!="string")throw new Error("Regex flags must be a string");let r=new Set;for(let s of e){if(!"dgimsuvy".includes(s))throw new Error(`Unsupported regex flag '${s}'`);if(r.has(s))throw new Error(`Duplicate regex flag '${s}'`);r.add(s)}if(r.has("u")&&r.has("v"))throw new Error("Regex flags cannot combine 'u' and 'v' Unicode modes");if(n!=="native"&&r.has("y"))throw new Error("Sticky regex flag 'y' is incompatible with capture helpers that search anywhere");try{return new RegExp(t,n==="all"&&!r.has("g")?e+"g":e)}catch(s){throw new Error(`Invalid regex pattern: ${s instanceof Error?s.message:String(s)}`)}}function Yy(t){return Array.from(t,e=>e===void 0?null:e)}function pN(t,e,n=""){let r=qi(e,n,"first").exec(String(t));return r===null?null:Yy(r)}function fN(t,e,n=""){let r=qi(e,n,"all"),s=String(t),i=n.includes("u")||n.includes("v"),o=[],a;for(;(a=r.exec(s))!==null;)if(o.push(Yy(a)),a[0]===""){let l=r.lastIndex;if(l>=s.length)break;let c=s.charCodeAt(l),u=s.charCodeAt(l+1),d=i&&c>=55296&&c<=56319&&u>=56320&&u<=57343?2:1;r.lastIndex=l+d}return o}function xy(t,e,n){try{if(n){if(n.at(e),t!==null&&typeof t=="object"&&Ee.isProxy(t))throw Error("Dry iterable cannot be a proxy");let s=[];if(Array.isArray(t)){if(![Array.prototype,null].includes(Object.getPrototypeOf(t)))throw Error("Dry iterable must be a plain array");let i=Math.min(t.length,n.loopLimit);for(let o=0;o<i;o++){n.check();let a=Object.getOwnPropertyDescriptor(t,String(o));if(a&&!("value"in a))throw Error("Dry iterable cannot contain accessors");s.push(a?.value)}return s}if(typeof t=="string"){for(let i of t)if(n.check(),s.push(i),s.length===n.loopLimit)break;return s}if(t!==null&&typeof t=="object"&&[Object.prototype,null].includes(Object.getPrototypeOf(t))){if(Hd(t))throw Error("Dry iterable must be plain data");for(let i in t)if(n.check(),!!Object.hasOwn(t,i)&&(s.push(i),s.length===n.loopLimit))break;return s}}if(Array.isArray(t))return Array.from({length:t.length},(s,i)=>t[i]);if(typeof t=="string")return Array.from(t);if(t!==null&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.keys(t);let r=t===null?"null":t instanceof Date?"Date":typeof t;throw new D(`Cannot iterate value of type ${r}; expected list, map or string`,e.line,e.column,"RUNTIME",e.file)}catch(r){throw r instanceof D||n&&r?.isControlFlow?r:new D(`Cannot snapshot iterable: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,"RUNTIME",e.file)}}function bd(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let n of Object.keys(t)){let r=t[n];if(Array.isArray(r))for(let s of r)bd(s,e);else r&&typeof r=="object"&&bd(r,e)}}}function Xi(t,e="Call to undefined function"){let n=`${e} '${t}'`;if(!Object.hasOwn(Wa,t))return n;let r=n+`; did you mean '${Wa[t]}'?`;return t==="json"?r+" Use json_stringify for serialization.":t==="count"?r+" Use count_matches for substring occurrences.":t==="parseInt"||t==="parseFloat"?r+" num uses whole-value Number conversion; it does not provide prefix parsing or integer truncation.":r}function hN(){if(!md){let e=new Ba(gN,"<std>").tokenize(),r=new qa(e,"<std>").parse();for(let s of r.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);md=r}return{kind:"Program",statements:[...md.statements],line:1,column:1,file:"<std>"}}function Yr(t){return t&&typeof t=="object"&&Yi.has(t)?Yi.get(t)():t}function wd(t){if(typeof t!="string"||!/^[_a-zA-Z]\w*(?:\.[_a-zA-Z]\w*)*$/.test(t))throw Error(`Invalid property key '${String(t)}'; use dotted identifier segments`);return t}function Xa(t,e){return e.find(n=>{let r=n.lastIndexOf(".");return n===t||r>=0&&t===n.slice(0,r+1)+n.slice(r+1).toLowerCase()})??t}function Dn(t,e,n=new Set){if(t instanceof Date)return t.toISOString();if(t===null||typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t))return t;if(t&&typeof t=="object"){if(!Array.isArray(t)&&![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw Error(`Property '${e}' has an unsupported object value`);if(n.has(t))throw Error(`Property '${e}' contains a cycle`);n.add(t);try{if(Array.isArray(t))return t.map((s,i)=>Dn(s,e+"."+i,n));let r={};for(let[s,i]of Object.entries(t))et(r,s,Dn(i,e?e+"."+s:s,n));return r}finally{n.delete(t)}}throw Error(`Property '${e}' has an unsupported value type: ${typeof t}`)}function Fs(t){let e=Dn(t.properties,"");if(!e||typeof e!="object"||Array.isArray(e))throw Error("Property document must be a table in "+t.path);for(let n of["Directory","NonInteractive"])if(Object.hasOwn(e,n))throw Error("Property '"+n+"' is read-only in "+t.path);return{...t,properties:e}}function Ps(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date)}function Ed(t,e,n,r=""){let s={};for(let[i,o]of Object.entries(t)){let a=r?r+"."+i:i,l=/^[_a-zA-Z]\w*$/.test(i)?Xa(a,e):a,c=l===a?i:l.slice(l.lastIndexOf(".")+1);if(Object.hasOwn(s,c))throw Error("Ambiguous property '"+l+"' in "+n);et(s,c,Ps(o)?Ed(o,e,n,l):structuredClone(o))}return s}function Qy(t,e,n,r,s=""){let i=structuredClone(t);for(let[o,a]of Object.entries(e)){let l=s?s+"."+o:o;if(Object.hasOwn(t,o)&&Ps(t[o])!==Ps(a))throw Error("Property '"+l+"' cannot merge a table and a value between "+n+" and "+r);et(i,o,Object.hasOwn(t,o)&&Ps(t[o])&&Ps(a)?Qy(t[o],a,n,r,l):structuredClone(a))}return i}function Ja(t){if(t.kind==="IdentifierExpr"&&t.name==="PROPS")return"";if(t.kind==="IndexExpr"&&t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"){let e=Ja(t.target);if(e!==void 0)return e?e+"."+t.index.value:t.index.value}}function Hi(t,e){return Mn.run(void 0,()=>t.fn(...e))}function yN(t,e,n,r,s){return function(...i){let o=this,a={run:t,module:e,readonly:n,async:r,active:!0};return Mn.run(a,()=>{try{let l=s.apply(o,i);return Ze(l)?Promise.resolve(l).finally(()=>{a.active=!1}):(a.active=!1,l)}catch(l){throw a.active=!1,l}})}}function _N(t){if(Ee.isProxy(t))throw Error("Grant declarations cannot be a proxy");let e=Object.getOwnPropertyDescriptor(t,"readonlyPrograms");if(!e)return[];if(!("value"in e))throw Error("readonlyPrograms must be data");let n=en(e.value),r=s=>Array.from({length:s.length},(i,o)=>Object.hasOwn(s,o)).every(Boolean);if(!Array.isArray(n)||!r(n)||n.some(s=>!Array.isArray(s)||!r(s)||!s.length||!s[0]||s.some(i=>typeof i!="string"||i.includes("\0"))))throw Error("Invalid readonlyPrograms prefixes");return Object.freeze(n.map(s=>Object.freeze(s)))}function Bi(t,e={currentPath:null}){return zr(e),{finished:!1,probe:e,errors:[],pending:t?t.split("."):[],entered:new Set,stack:[],envs:new Map,active:!1,rootTaskId:-1}}function zr(t){t&&(t.currentPath=null,delete t.firstFailure)}function Ud(t){t.finished||(t.probe.firstFailure??={path:t.probe.currentPath})}function vN(t){let e=t;return!!(t instanceof At||e?.name==="LMScriptExit"||e?.isControlFlow)&&(typeof e?.exitCode=="number"?e.exitCode:0)===0}function Cy(t,e){let n=()=>Ud(t);return e?.addEventListener("abort",n,{once:!0}),e?.aborted&&n(),()=>e?.removeEventListener("abort",n)}function xt(t,e){e instanceof ar||e instanceof qt||e instanceof Xt||vN(e)||Ud(t)}function Fa(t,e){t.finished||(Ud(t),t.errors.push(e))}function wN(t,e){let n=e.resumepoint;if(n===void 0||!t.ast)return[];let r={severity:"error",line:1,column:1,file:e.file};if(typeof n!="string"||!bN.test(n))return[{...r,message:`Invalid resumepoint path: ${String(n)}; expected NAME(.NAME)*`}];if(!t.hasRecover)return[{...r,message:"Script has no recover block"}];let s=n.split(".")[0];return t.recoverLabels?.includes(s)?[]:[{...r,message:`Unknown resumepoint '${s}': no recover block declares this point`}]}function Kr(t,e){let n=t.diagnostics.filter(s=>!t.resumepointDiagnostics?.includes(s)),r=wN(t,e);return{...t,diagnostics:Hy([...n,...r],t.diagnosticPaths),resumepointDiagnostics:r}}function Qi(t){return!t.startsWith("native:")&&!t.startsWith("@")&&(/\.cli\.schema\.v1\.json$/.test(t)||/(?:^|[\\/])cli\.schema\.(?:latest|dev)\.json$/.test(t))}function es(t){return t.startsWith("@")}function Zy(t){return t.trim().length>0&&!/[\0\r\n]/.test(t)&&!/[\/\\]/.test(t)&&!t.startsWith(".")&&!t.endsWith(".lms")}function EN(t){let e=t instanceof Error&&t.name!=="Error"?`${t.name}: `:"",n=t instanceof Error?t.message:String(t),r=[];for(let i of n.split(/\r?\n/)){if(/^\s*Require stack:\s*$/.test(i))break;/^\s*(?:at\s|-\s)/.test(i)||r.push(i)}let s=r.join(" ").replace(/__lmscript_modules__\.cjs/g,"").replace(/(?:file:\/\/)?(?:[A-Za-z]:)?[\\/][^\s'"<>]+/g,"<module file>").replace(/\s+/g," ").trim();return(e+(s||"module loading failed")).trim()}function Ke(t){if(t?.aborted)throw new Error("Execution aborted")}function Ze(t){return t!==null&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function $a(t,e,n){if(/^https?:/i.test(t)||/^https?:/i.test(e??"")){let s=/^https?:/i.test(t)?new URL(t):new URL(t,e);if(!["http:","https:"].includes(s.protocol))throw Error("Only http/https module URLs are supported");return s.hash="",s.href}let r=re.resolve(e&&e!=="<main>"&&!e.startsWith("<")?re.dirname(e):n,t);try{return j.realpathSync(r)}catch{return r}}function e_(t){if(t.kind==="IdentifierExpr")return t.name;if(t.kind==="IndexExpr"&&t.index.kind==="LiteralExpr"&&typeof t.index.value=="string"){let e=e_(t.target);if(e)return e+"."+t.index.value}}function Td(t){let e=new Set,n=r=>{if(!(!r||typeof r!="object")){r.kind==="AssignExpr"&&e.add(r.target),r.kind==="TupleAssignExpr"&&r.targets.forEach(s=>e.add(s));for(let s of Object.values(r))Array.isArray(s)?s.forEach(n):s&&typeof s=="object"&&n(s)}};for(let r of t.statements)(r.kind==="FunctionDeclStmt"||r.kind==="VarDeclStmt")&&e.add(r.name),r.kind==="TupleVarDeclStmt"&&r.names.forEach(s=>e.add(s)),r.kind==="ExprStmt"&&n(r.expr);return e}function TN(t,e){let n=Td(t),r=(o,a)=>n.has(o)&&!a.locals.has(o)?e+"."+o:o,s=(o,a)=>{if(!o||typeof o!="object")return o;let l={...o};if(o.kind==="IdentifierExpr")return l.name=r(o.name,a),l;if(o.kind==="AssignExpr"||o.kind==="TupleAssignExpr"){l.value=s(o.value,a);let u=(o.kind==="AssignExpr"?[o.target]:o.targets).map(d=>a.fn?(a.locals.add(d),d):r(d,a));return o.kind==="AssignExpr"?l.target=u[0]:l.targets=u,l}o.kind==="CallExpr"&&(l.callee=n.has(o.callee)&&!a.locals.has(o.callee)?e+"."+o.callee:o.callee);for(let[c,u]of Object.entries(o))c!=="callee"&&(Array.isArray(u)?l[c]=u.map(d=>d&&typeof d=="object"?s(d,a):d):u&&typeof u=="object"&&(l[c]=s(u,a)));return l},i=(o,a)=>{let l={...o};if(o.kind==="FunctionDeclStmt")return l.name=e+"."+o.name,l.body=i(o.body,{locals:new Set(o.params),root:!1,fn:!0}),l;if(o.kind==="BlockStmt"){let c={...a,locals:new Set(a.locals),root:!1};return l.statements=o.statements.map(u=>i(u,c)),l}if(o.kind==="RecoverStmt"){let c={...a,locals:new Set(a.locals),root:!1};return l.points=o.points.map(u=>({...u,statements:u.statements.map(d=>i(d,c))})),l}if(o.kind==="VarDeclStmt"||o.kind==="TupleVarDeclStmt"){o.initializer&&(l.initializer=s(o.initializer,a));let u=(o.kind==="VarDeclStmt"?[o.name]:o.names).map(d=>a.root?r(d,a):(a.locals.add(d),d));return o.kind==="VarDeclStmt"?l.name=u[0]:l.names=u,l}if(o.kind==="ForInStmt"){l.iterable=s(o.iterable,a);let c={...a,root:!1,locals:new Set(a.locals)};return c.locals.add(o.name),l.body=i(o.body,c),l}if(o.kind==="ForStmt"){let c={...a,root:!1,locals:new Set(a.locals)};return o.init&&(l.init=i(o.init,c)),o.condition&&(l.condition=s(o.condition,c)),o.update&&(l.update=s(o.update,c)),l.body=i(o.body,c),l}o.kind==="SyncAssignStmt"&&(l.target=r(o.target,a));for(let[c,u]of Object.entries(o))c==="target"&&o.kind==="SyncAssignStmt"||u&&typeof u=="object"&&(l[c]=u.kind?.endsWith("Stmt")?i(u,a):s(u,a));return l};return{...t,statements:t.statements.map(o=>i(o,{locals:new Set,root:!0,fn:!1}))}}function*t_(t,e){let n=e.file??"<main>",r=e.baseDir??(e.file&&!/^https?:/i.test(e.file)?re.dirname(re.resolve(e.file)):process.cwd()),s=[],i=new Map,o=new Map,a=[],l=[],c=new Map,u=new Map,d=new Map([[n,[]]]);try{for(let _ of e.modules??[]){if(!Zy(_))throw new D("modules option requires a host module name",1,1,"CHECKER",n);if(e.builtinProviderNames?.includes(_))throw new D(_+" functions are built in; remove this line",1,1,"CHECKER",n);l.push({name:_,line:1,column:1,file:n})}let m=(_,v)=>{let E=new Ba(_,v),I;try{I=E.tokenize()}finally{s.push(...E.diagnostics)}return new qa(I,v).parse()},p=(_,v,E,I)=>{let T;try{T=e.schemaModule({text:E,location:v,..._.alias!==void 0?{alias:_.alias}:{}})}catch(C){throw I("Invalid schema module "+_.path+": "+(C instanceof Error?C.message:String(C)))}let k=T.nativeNamespace;if(!k||T.name!=="schema:"+k||!mN(k))throw I(`Invalid schema module ${_.path}: namespace ${JSON.stringify(k)} is not a usable identifier; import it with as <identifier>`);for(let[C,O]of e.nativeModules??[])if(O.namespace===k)throw I("Namespace collision: "+k+" is the native module "+C+"; import the schema with as <name>");let N=o.get(k);if(N)throw I("Namespace collision: "+k+" is already imported from "+N.location+"; import the schema with as <name>");return u.set(v,k),c.set(T.name,T),a.push(v),o.set(k,{location:v,members:T.declarations.functions.map(C=>C.name)}),l.push({name:T.name,line:_.line,column:_.column,file:_.file}),{kind:"PackageStmt",name:k,nativeModule:T.name,line:_.line,column:_.column,file:_.file}};function*f(_,v){let E=_.statements.find(T=>T.kind==="PackageStmt");if(E&&_.statements[0]!==E)throw new D("package must be the first statement in its file",E.line,E.column,"CHECKER",v);if(_.statements.filter(T=>T.kind==="PackageStmt").length>1)throw new D("Only one package declaration is allowed",E.line,E.column,"CHECKER",v);if(E?.kind==="PackageStmt"){if(Td(_).has(E.name))throw new D("Package name collision: "+E.name+" is also a module variable/function",E.line,E.column,"CHECKER",v);let T=o.get(E.name);if(T&&T.location!==v)throw new D("Duplicate package "+E.name+": "+T.location+" and "+v,E.line,E.column,"CHECKER",v);o.set(E.name,{location:v,members:[...Td(_)].map(k=>E.name+"."+k)}),_=TN(_,E.name)}let I=[];for(let T of _.statements){if(T.kind!=="ImportStmt"){I.push(T);continue}if(T.path.startsWith("native:")){let C=e.nativeModules?.get(T.path);if(!C)throw new D("Unknown native module "+T.path+"; it must be compiled into this build",T.line,T.column,"CHECKER",T.file);let O=o.get(C.namespace);if(O&&O.location!==T.path)throw new D("Duplicate package "+C.namespace+": "+O.location+" and "+T.path,T.line,T.column,"CHECKER",T.file);if(i.get(T.path)==="loaded")continue;i.set(T.path,"loaded"),o.set(C.namespace,{location:T.path,members:[...C.members]}),l.push({name:T.path,line:T.line,column:T.column,file:T.file}),I.push({kind:"PackageStmt",name:C.namespace,nativeModule:T.path,line:T.line,column:T.column,file:T.file});continue}if(Qi(T.path)||es(T.path)){let C=x=>new D(x,T.line,T.column,"CHECKER",T.file??v);if(!e.schemaModule)throw C("Schema module imports are not available in this host");let O;if(es(T.path)){if(!e.resolveModuleSpec)throw C("GitHub module imports (@owner/repo) are not available in this host");let x=yield{location:"module:"+T.path,specifier:T.path,from:v,node:T,module:!0};O=x.location;let A=u.get(O);if(A!==void 0){if(T.alias===void 0||T.alias===A)continue;throw C("Schema module "+O.slice(7)+" is already imported as "+A)}let M=p(T,O,x.source,C);M&&I.push(M);continue}if(/^https?:/i.test(T.path)||/^https?:/i.test(v))throw C("Schema modules are local files; "+T.path+" cannot be imported from a URL");try{O=$a(T.path,v===g?e.baseDir?re.join(r,"__entry__.lms"):g:v,r)}catch(x){throw C("Cannot resolve import "+T.path+": "+String(x))}let w=u.get(O);if(w!==void 0){if(T.alias===void 0||T.alias===w)continue;throw C("Schema module "+T.path+" is already imported as "+w)}let S=yield{location:O,specifier:T.path,from:v,node:T},R=p(T,O,S.source,C);R&&I.push(R);continue}let k;try{k=$a(T.path,v===g?e.baseDir?re.join(r,"__entry__.lms"):g:v,r)}catch(C){throw new D("Cannot resolve import "+T.path+": "+String(C),T.line,T.column,"CHECKER",v)}if(i.get(k)==="loading")throw new D("Import cycle: "+v+" -> "+k,T.line,T.column,"CHECKER",v);if(i.get(k)==="loaded")continue;let N=yield{location:k,specifier:T.path,from:v,node:T};if(k=N.location,i.get(k)==="loading")throw new D("Import cycle: "+v+" -> "+k,T.line,T.column,"CHECKER",v);i.get(k)!=="loaded"&&(d.set(k,[...d.get(v)??[],T.line,T.column]),i.set(k,"loading"),a.push(k),I.push(...yield*f(m(N.source,k),k)),i.set(k,"loaded"))}return I}let g=e.entryLocation??n;try{g!=="<main>"&&!g.startsWith("<")&&(g=$a(g,void 0,r))}catch{}d.set(g,[]),i.set(g,"loading"),a.push(g);let h=yield*f(m(t,n),g);i.set(g,"loaded");let y=_=>{if(!_||typeof _!="object")return _;let v={..._};if(_.kind==="IndexExpr"&&_.target.kind==="IdentifierExpr"&&o.has(_.target.name)&&_.index.kind==="LiteralExpr"&&typeof _.index.value=="string")return{kind:"IdentifierExpr",name:_.target.name+"."+_.index.value,line:_.line,column:_.column,file:_.file};if(_.kind==="IndexAssignExpr"&&_.target.kind==="IdentifierExpr"&&o.has(_.target.name)&&_.index.kind==="LiteralExpr"&&typeof _.index.value=="string")return{kind:"AssignExpr",target:_.target.name+"."+_.index.value,value:y(_.value),line:_.line,column:_.column,file:_.file};for(let[E,I]of Object.entries(_))Array.isArray(I)?v[E]=I.map(y):I&&typeof I=="object"&&(v[E]=y(I));return v};return{program:{kind:"Program",statements:[...e.noStdlib?[]:hN().statements,...h.map(y)],line:1,column:1,file:n},loadedFiles:a,diagnostics:s,hostImports:l,packages:o,diagnosticPaths:d,schemaModules:c}}catch(m){throw m instanceof Vi?m:new Vi(m,s,d,n)}}function n_(t,e){if(t.module)throw new D("GitHub module imports (@owner/repo) need the async runtime (runAsync / scanAndCheckAsync)",t.node.line,t.node.column,"CHECKER",t.node.file);try{if(e.moduleResolver){let n=e.moduleResolver(t.specifier,t.from);return{location:$a(n.path,void 0,e.baseDir??process.cwd()),source:n.source}}if(/^https?:/i.test(t.location))throw Error("URL imports require runAsync or scanAndCheckAsync");return{location:t.location,source:j.readFileSync(t.location,"utf8")}}catch(n){throw new D("Cannot load module "+t.location+": "+String(n instanceof Error?n.message:n),t.node.line,t.node.column,"CHECKER",t.node.file)}}function SN(t,e={}){let n=t_(t,e),r=n.next();for(;!r.done;){let s;try{s=n_(r.value,e)}catch(i){r=n.throw(i);continue}r=n.next(s)}return r.value}async function kN(t,e={}){let n=e.importCache??new Map,r=t_(t,e),s=r.next();for(;!s.done;){let i=s.value,o=n.get(i.location);o||(o=(async()=>{if(i.module)try{let l=await e.resolveModuleSpec(i.specifier);return{location:"module:"+l.key,source:l.source}}catch(l){throw new D(l instanceof Error?l.message:String(l),i.node.line,i.node.column,"CHECKER",i.node.file)}if(!/^https?:/i.test(i.location)||e.moduleResolver)return n_(i,e);try{let l=await fetch(i.location,{signal:AbortSignal.timeout(e.importTimeoutMs??5e3)});if(!l.ok)throw Error("HTTP "+l.status);return{location:i.location,source:await l.text()}}catch(l){throw new D("Cannot load module URL "+i.location+": "+String(l instanceof Error?l.message:l),i.node.line,i.node.column,"CHECKER",i.node.file)}})(),n.set(i.location,o));let a;try{a=await o}catch(l){s=r.throw(l);continue}s=r.next(a)}return s.value}function kd(t,e){t&&typeof t=="object"&&Yi.has(t)&&(t=Yi.get(t)());let n,r=o=>{throw n=e?new D("Cannot interpolate value: "+o,e.line,e.column,"RUNTIME",e.file):new Error("Cannot convert value to text: "+o),n},s=new Set,i=o=>{if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="boolean")return String(o);if(typeof o=="number")return Number.isFinite(o)?String(o):r("nonfinite number");if(typeof o!="object")return r(o===void 0?"undefined":"unsupported "+typeof o);let a=Array.isArray(o),l=Object.getPrototypeOf(o);if(!a&&l!==Object.prototype&&l!==null)return r("unsupported host object");if(s.has(o))return r("cyclic collection");s.add(o);try{if(Reflect.ownKeys(o).some(m=>typeof m=="symbol"))return r("symbol-keyed collection");let c=a?Array.from({length:o.length},(m,p)=>String(p)):Object.keys(o);if(a&&c.some(m=>!Object.hasOwn(o,m)))return r("sparse array");let u=Object.getOwnPropertyNames(o).filter(m=>!a||m!=="length");if(u.length!==c.length||u.some(m=>!c.includes(m)))return r("extra or non-enumerable collection property");let d=[];for(let m of c){let p=Object.getOwnPropertyDescriptor(o,m);if(!p)return r("sparse array");if(!Object.hasOwn(p,"value"))return r("accessor property");let f=i(p.value);d.push(a?f:JSON.stringify(m)+":"+f)}return a?"["+d.join(",")+"]":"{"+d.join(",")+"}"}finally{s.delete(o)}};try{return typeof t=="string"?t:i(t)}catch(o){if(o===n)throw o;return r("serialization failed: "+(o instanceof Error?o.message:String(o)))}}function pd(t){if(t!==null&&typeof t=="object"){let e=Object.getPrototypeOf(t);if(Array.isArray(t)||e===Object.prototype||e===null)return kd(t)}return t===null?"null":String(t)}function Ny(t){switch(t){case"boolean":return!0;case"number":return 0;case"string":return"";case"array":return[];case"map":return{};case"SystemResult":return{...xN};case"null":case void 0:default:return null}}function r_(t){if(!t)return null;let e=t.trim(),n=e.toLowerCase();return{bool:"boolean",boolean:"boolean",list:"array",array:"array",map:"map",object:"map"}[n]??e}function Cd(t){return typeof t=="object"&&t?Object.freeze({min:t.min,...t.max===void 0?{}:{max:t.max}}):t}function fd(t){if(t)return Object.freeze({...t,parameters:t.parameters?Object.freeze(t.parameters.map(e=>Object.freeze({...e}))):void 0,returns:t.returns?Object.freeze({...t.returns}):void 0})}function Nd(t){return Object.freeze({...t,values:t.values?Object.freeze([...t.values]):void 0,keys:t.keys?Object.freeze(t.keys.map(e=>Object.freeze({...e,values:e.values?Object.freeze([...e.values]):void 0}))):void 0})}function Zt(t,e,n,r,s){if(r!==void 0&&typeof r!="string")throw Error(`Function '${t}' returnType must be a string`);let i=(n??[]).map(Nd),o=i.map((f,g)=>f.name==="dryrun"?g:-1).filter(f=>f>=0);if(o.length>1)throw new Error(`Function '${t}' declares dryrun more than once`);let a=o[0];if(a!==void 0){let f=i[a];if(f.type?.toLowerCase()!=="boolean"&&f.type?.toLowerCase()!=="bool")throw new Error(`Function '${t}' dryrun parameter must be boolean`);if(!f.optional)throw new Error(`Function '${t}' dryrun parameter must be optional`);if(f.rest)throw new Error(`Function '${t}' dryrun parameter cannot be rest`);if(i.some(g=>g.rest)&&a!==0)throw new Error(`Function '${t}' dryrun with rest must place dryrun at slot zero`);if(typeof e=="number")throw new Error(`Function '${t}' must use a range arity when declaring optional dryrun`)}for(let f=0;f<i.length;f++){let g=i[f];if(g.default!==void 0&&f!==a)throw Error("Host parameter default is only supported on the reserved dryrun slot");if(g.default!==void 0&&typeof g.default!="boolean")throw new Error(`Function '${t}' dryrun default must be boolean`);if(g.optional!==void 0&&typeof g.optional!="boolean")throw Error(`Function '${t}' optional must be boolean`);if(g.rest!==void 0&&typeof g.rest!="boolean")throw Error(`Function '${t}' rest must be boolean`);if(g.rest&&(g.optional||g.default!==void 0))throw Error(`Function '${t}' rest cannot have an optional/default slot`);if(g.rest&&f!==i.length-1)throw new Error(`Function '${t}' rest parameter must be last`);if(g.optional&&f<i.length-1&&f!==a&&i.slice(f+1).some(y=>!y.optional&&!y.rest&&y.name!=="dryrun"))throw new Error(`Function '${t}' has a required parameter after an optional parameter`)}let l=i.filter((f,g)=>g!==a),c=i.reduce((f,g,h)=>!g.optional&&!g.rest?h+1:f,0),u=a!==void 0||i.some(f=>f.rest||f.default!==void 0),d=e??(u?{min:c,max:i.some(f=>f.rest)?void 0:i.length}:void 0);if(n?.length&&d&&(a!==void 0||i.some(f=>f.rest)||i.some(f=>f.default!==void 0))){let f=i.reduce((b,_,v)=>!_.optional&&!_.rest?v+1:b,0),g=i.some(b=>b.rest)?void 0:i.length,h=typeof d=="number"?d:d.min,y=typeof d=="number"?d:d.max;if(h!==f||y!==g)throw new Error(`Function '${t}' arity does not match its declared parameters`)}let m=a===void 0?d:(()=>{if(typeof d=="number")return Math.max(0,d-1);if(!d)return;let f=l.filter(h=>!h.optional&&!h.rest).length,g=d.max===void 0?void 0:Math.max(0,d.max-1);return g!==void 0&&f===g?f:{min:f,...g===void 0?{}:{max:g}}})(),p=r_(r??s?.returns?.type);return Object.freeze({name:t,nativeParams:Object.freeze(i),publicParams:Object.freeze(l),nativeArity:Cd(d),publicArity:Cd(m),dryrunIndex:a,returnType:p})}function Oy(t,e,n){if(e!==void 0&&typeof e!="boolean")throw Error(`Function '${t}' readonly must be boolean`);if(e===!0&&n.dryrunIndex===void 0)throw Error(`Function '${t}' readonly host must declare optional boolean dryrun`)}function Pa(t,e,n){if(e!==void 0){if(e!=="output"&&e!=="error")throw Error("Function "+t+" dryControl must be output or error");if(n.dryrunIndex===void 0||n.returnType!=="string")throw Error("Function "+t+" dryControl requires optional boolean dryrun and a string return type");return e}}function Wi(t,e,n=!1){let r=t.signature??Zt("<host>",t.arity,t.params,t.returnType,t.doc),s=r.publicArity,i=typeof s=="number"?s:s?.max,o=typeof s=="number"?s:s?.min;if(o!==void 0&&e.length<o||i!==void 0&&e.length>i)throw new Error(`Function '${r.name}' expects ${o??0}..${i??"unlimited"} public argument(s), but received ${e.length}`);if(r.dryrunIndex===void 0)return[...e];let a=[...e];for(;a.length<r.dryrunIndex;)a.push(void 0);return n?a.splice(r.dryrunIndex,0,!0):a.splice(r.dryrunIndex,0,r.nativeParams[r.dryrunIndex].default??!1),a}function gd(t){let n=t.stop?t.stop.file.length+t.stop.reason.length:0;for(let a of t.diagnostics)if(n+=a.message.length+(a.file?.length??0),n>1048576)break;if(n<=1048576&&Buffer.byteLength(JSON.stringify(t))<=1048576)return t;let r=(a,l)=>a.length<=l?a:a.slice(0,l)+" [truncated]",s=t.stop?{...t.stop,file:r(t.stop.file,96),reason:r(t.stop.reason,160)}:{file:"<main>",line:1,column:1,reason:"dry run truncated: plan size exceeded"},i=t.diagnostics.find(a=>a.severity==="error")??t.diagnostics[0],o=i?[{...i,message:r(i.message,160),...i.file?{file:r(i.file,96)}:{}}]:[];return o.push({severity:"warning",file:s.file,line:s.line,column:s.column,message:"dry run truncated: diagnostic metadata exceeded plan size limit ("+t.diagnostics.length+" findings)"}),{...t,status:t.status==="complete"||t.status==="loop-limited"?"truncated":t.status,stop:s,diagnostics:o}}function s_(t,e="text"){let{version:n,status:r,entries:s,stop:i,diagnostics:o}=t;if(e==="json")return JSON.stringify({version:n,status:r,entries:s,stop:i,diagnostics:o});let a=l=>/[\x00-\x1f\x7f\u2028\u2029]/.test(l)?JSON.stringify(l).replace(/[\u007f\u2028\u2029]/g,c=>"\\u"+c.charCodeAt(0).toString(16).padStart(4,"0")):l;return["PLAN "+r,...s.map(l=>String(l.seq)+". "+a(l.file)+":"+l.line+":"+l.column+" "+(l.kind==="loop"?l.message:l.kind+" "+a(l.function)+" "+JSON.stringify(l.arguments)))].join(`
|
|
60
60
|
`)}function AN(t){if(!(t instanceof Gt)&&(t instanceof At||t?.name==="LMScriptExit"||t?.isControlFlow)&&t.resourceFailure===void 0)return typeof t.exitCode=="number"?t.exitCode:0}function se(t){return t[Id]}function Ly(t,e,n,r){if(!r||!Ds.has(t))return ht(t,e);r.at(n);try{return ht(t,e)}catch(s){throw new D(s instanceof Error?s.message:String(s),n.line,n.column,"RUNTIME",n.file)}}function en(t,e=new Map){if(typeof t=="function")throw Error("Dry input cannot contain native functions");if(t===null||typeof t!="object"||Oe(t))return t;if(Ds.has(t))return en(Yr(t),e);if(Ee.isProxy(t))throw Error("Dry input cannot be a proxy");if(e.has(t))return e.get(t);if(!Array.isArray(t)&&Object.getPrototypeOf(t)!==lr.prototype&&![Object.prototype,null].includes(Object.getPrototypeOf(t)))throw Error("Dry input must be plain data");let n=Array.isArray(t)?new Array(t.length):Object.create(Object.getPrototypeOf(t));e.set(t,n);for(let r of Reflect.ownKeys(t)){if(Array.isArray(t)&&r==="length")continue;let s=Object.getOwnPropertyDescriptor(t,r);if(!("value"in s))throw Error("Dry input cannot contain accessors");Object.defineProperty(n,r,{value:en(s.value,e),writable:!0,enumerable:s.enumerable,configurable:!0})}return n}function NN(t,e){if(!CN.has(t)||typeof e[0]!="string")return!1;try{let n=j.statSync(e[0]);return!n.isFile()&&!n.isDirectory()}catch{return!1}}function My(t,e,n,r,s,i){if(s.failure)throw new Gt(s.failure.message);s.at(r);let o=Wi(t,e,!0),a=t[Be],l=a?.readonly&&!a.control||t.readonly&&t.signature?.dryrunIndex!==void 0&&!t.dryControl?[]:s.snapshot(e),c=a?.process?Ya(e[0],Jy(e[1]).timeoutMs,i):void 0;if(a?.frozen&&Zr(en(e))&&s.fail("Dry host arguments contain a live or unsupported capability",r),a?.frozen==="now")return{skip:!0,value:s.wallClock};if(a?.frozen==="timestamp")return{skip:!0,value:Math.floor(s.wallClock/1e3)};if(a?.frozen==="date")return{skip:!0,value:new Date(e[0]??s.wallClock).toISOString()};if(a?.frozen==="env")return{skip:!0,value:s.environment[e[0]]??e[1]??null};let u=t.dryControl??a?.control,d=u?en(e):e;if(u==="output"){let p=d.map(f=>typeof f=="object"?JSON.stringify(f):String(f)).join(" ");return s.record(n,l,r,"handled",void 0,!1),{skip:!0,value:p}}if(u==="error"){let p=d.map(f=>typeof f=="object"?JSON.stringify(f):String(f)).join(" ");return s.recordError(p,r),{skip:!0,value:p}}if(u==="exit"){let p=Number(d[0]??0),f=Number.isFinite(p)&&p>=0&&p<=255?Math.floor(p):1;throw s.finishExit(f,r),new Gt("script exit with code "+f)}if(u==="require"){let p=e[0];return Dd(p,e[1],f=>s.fail(f,r)),{skip:!0,value:p}}if(a?.readonly&&NN(n,e))return s.record(n,s.snapshot(e),r,"dummy"),{skip:!0,value:Ny(a.dummyType??t.signature?.returnType??t.returnType)};let m=t.signature?.dryrunIndex!==void 0;return a?.readonly||m?(Zr(en(e))&&s.fail("Dry host arguments contain a live or unsupported capability",r),{skip:!1,args:o,handled:!a?.readonly&&!t.readonly,publicArgs:l,taints:a?.taints!==!1}):(s.record(n,l,r,"dummy",c),{skip:!0,value:Ny(t.returnsResource?"null":a?.dummyType??t.signature?.returnType??t.returnType)})}function Qr(t){return{returnsResource:t.returnsResource===!0||void 0,usesResource:t.usesResource===!0||void 0,closesResource:t.closesResource===!0||void 0}}function Py(){return i_>0}function Oe(t){return o_.has(t)}function Da(t){let e=[];for(let n=t;n;n=n.parent)e.push(n.key);return e.reverse().map(n=>typeof n=="symbol"?`[${String(n)}]`:/^(0|[1-9]\d*)$/.test(n)?`[${String(n)}]`:/^[A-Za-z_$][\w$]*$/.test(n)?`.${String(n)}`:`[${JSON.stringify(n)}]`).join("")}function Hd(t){if(typeof t=="function")return"a function";if(Ee.isMap(t)||Ee.isSet(t)||Ee.isWeakMap(t)||Ee.isWeakSet(t))return"a native collection";if(Ee.isPromise(t)||Ee.isDate(t)||Ee.isRegExp(t)||Ee.isBoxedPrimitive(t)||Ee.isNativeError(t))return"a native object";if(Ee.isArrayBufferView(t)||Ee.isAnyArrayBuffer(t))return"binary data";if(Ee.isMapIterator(t)||Ee.isSetIterator(t)||Ee.isGeneratorObject(t)||Ee.isModuleNamespaceObject(t)||Ee.isExternal(t))return"a native object";if(Object.getPrototypeOf(t)===null)try{return WeakRef.prototype.deref.call(t),"a native object"}catch{}}function Zr(t,e=a_){if(Oe(t))return t;if(t===null||typeof t!="object"&&typeof t!="function")return;let n=new Set([t]),r=[t],s=[void 0],i=0;for(;r.length>0;){let o=r.pop(),a=s.pop();if(Ee.isProxy(o))return{refused:"uninspectable",path:Da(a),reason:"a proxy"};let l=Hd(o);if(l)return{refused:"uninspectable",path:Da(a),reason:l};let c=Object.getPrototypeOf(o),u=c===Array.prototype&&Array.isArray(o);if(!u&&c!==Object.prototype&&c!==null&&c!==lr.prototype)return{refused:"uninspectable",path:Da(a),reason:"not plain data"};if(i+=u?o.length+1:1,i>e)return{refused:"too large"};let d=Reflect.ownKeys(o);if(i+=u?Math.max(0,d.length-o.length):d.length,i>e)return{refused:"too large"};for(let m=0;m<d.length;m++){let p=d[m],f=Reflect.getOwnPropertyDescriptor(o,p);if(!("value"in f))return{refused:"uninspectable",path:Da({parent:a,key:p}),reason:"an accessor property"};let g=f.value;if(Oe(g))return g;g!==null&&(typeof g=="object"||typeof g=="function")&&!n.has(g)&&(n.add(g),r.push(g),s.push({parent:a,key:p}))}}}function hd(t,e){return t.refused==="too large"?`The ${e} result is too large to inspect for resources (over ${a_} units) and is refused`:`The ${e} result is an uninspectable value at result${t.path} (${t.reason}); results must be plain data`}function MN(t){for(let e=0;e<t.length;e++)if(Oe(t[e]))return!0;return!1}function Zi(){return l_.getStore()}function or(t){if(t instanceof At)return t.resourceFailure;if(!(t instanceof ar||t instanceof qt||t instanceof Xt))return t}function $N(t,e){if(typeof t!="number"||!Number.isFinite(t)||typeof e!="string")throw new Error("strftime: expected epoch milliseconds first and format string second");let n=new Date(t);if(!Number.isFinite(n.getTime()))throw new Error("strftime: invalid epoch milliseconds");let r=i=>String(i).padStart(2,"0"),s={"%Y":String(n.getFullYear()),"%m":r(n.getMonth()+1),"%d":r(n.getDate()),"%H":r(n.getHours()),"%M":r(n.getMinutes()),"%S":r(n.getSeconds()),"%%":"%"};return e.replace(/%[YmdHMS%]/g,i=>s[i])}function ja(t,e,n="sprintf"){let r=0;return String(t).replace(/%(-?0?)(\d+)?(?:\.(\d+))?([sdf%])|%/g,(s,i,o,a,l)=>{if(s==="%%")return"%";if(!l||l==="%")throw new Error(`${n}: unsupported or malformed directive`);if(r>=e.length)throw new Error(`${n}: missing value for ${s}`);let c=o===void 0?0:Number(o),u=a===void 0?void 0:Number(a);if(c>1e4||u!==void 0&&u>(l==="f"?100:1e4))throw new Error(`${n}: width or precision exceeds supported limit`);let d=e[r++],m;if(l==="s")m=d!==null&&typeof d=="object"?JSON.stringify(d):String(d),u!==void 0&&(m=m.slice(0,u));else{let p=Number(d);if(!Number.isFinite(p))throw new Error(`${n}: numeric directive needs a finite number`);if(l==="f")m=u===void 0?String(p):p.toFixed(u);else{let f=Math.trunc(p);m=BigInt(Math.abs(f)).toString().padStart(u??0,"0"),f<0&&(m="-"+m)}}return i.includes("-")?m.padEnd(c," "):l!=="s"&&i.includes("0")&&!(l==="d"&&u!==void 0)?m.startsWith("-")?"-"+m.slice(1).padStart(Math.max(0,c-1),"0"):m.padStart(c,"0"):m.padStart(c," ")})}async function jN(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
61
61
|
`);let t=new cr,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let r=t.run(`
|
|
62
62
|
fn factorial(n) {
|
|
@@ -398,12 +398,12 @@ fn clamp(val, low, high) {
|
|
|
398
398
|
}
|
|
399
399
|
return val;
|
|
400
400
|
}
|
|
401
|
-
`,md=null;Ds=new WeakMap,Yi=new WeakMap,Ay=["get_property","has_property","get_properties","set_property"];Ga=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(WC(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=Fs(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))Ze(e.tree,n,structuredClone(r));return this.overlay&&(e.overlay=Fs(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(),!Ps(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=Ed(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);Ze(n,a,structuredClone(l))}}if(this.overlay){let s=Ed(this.overlay.properties,this.known,this.overlay.path);n=Qy(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))Ze(this.tree,s,i);this.loaded=!0}find(e,n=!0){let r=Xa(wd(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?Dn(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>"),Dn(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 Dn(n.value,n.key)}set(e,n){let r=Xa(wd(e),this.known);if(["Directory","NonInteractive"].includes(r.split(".")[0]))throw Error(`Property '${r}' is read-only`);let s=Dn(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)||Ze(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?Dn(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 Ze(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=Dn(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 Ds.set(s,n),Yi.set(s,()=>this.copy(e)),s}};Mn=new Fy;bN=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;Pn=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}},Sd=class{diagnostics=[];hostFunctions=new Map;knownHostReferences=new Map;options;functions=new Map;currentScope=new Pn;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 Pn,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 Pn(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 Pn(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 Pn(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 Pn(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 Pn(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!=="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(!j.statSync(n.value).isFile())throw new Error("path is not a regular file");j.accessSync(n.value,j.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(h=>h.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(h=>h.trim().replace(/^array$/,"list").replace(/^object$/,"map")),g=["string","number","boolean","null","list","map"];f.every(h=>g.includes(h))&&!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=wd(e)}catch(l){this.addError(l.message,n.line,n.column,n.file);return}let s=this.options.propertyDeclarations;if(!s||(r=Xa(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"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"||Ay.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(Wa,e.name)?Xi(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=Ja(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(Wa,e.callee)&&!this.options.sourcePackages?.has(e.callee.split(".")[0])?this.addError(Xi(e.callee),e.line,e.column,e.file):this.checkPackageMember(e.callee,e)),Ay.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=ji(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(Xi(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}}}};ar=class{value;constructor(e){this.value=e}},qt=class{},Xt=class{},lr=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},ot=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)}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)}},Va=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()}}},Rd=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let n=this.bindingLocks.get(e);return n||(n=new Va,this.bindingLocks.set(e,n)),n}getObjectLock(e){let n=this.objectLocks.get(e);return n||(n=new Va,this.objectLocks.set(e,n)),n}},be=Object.freeze({readonly:!0}),RN=t=>{for(let e of Object.values(t))Object.freeze(e);return Object.freeze(t)},IN=RN({warning:{readonly:!0,control:"warning",dummyType:"string"},which:be,get_property:be,has_property:be,get_properties:be,expand:be,set_property:{dummyType:"null"},read:be,read_file:be,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:be,pop:be,shift:be,unshift:be,insert:be,remove_at:be,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:be,last:be,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:be,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:be,getstr:{readonly:!0,dummyType:"string"},getnum:{readonly:!0,dummyType:"number"},getbool:{readonly:!0,dummyType:"boolean"},getlist:{readonly:!0,dummyType:"array"},set:be,delete_key:be,merge:{readonly:!0,dummyType:"map"},clone:be,pluck:{readonly:!0,dummyType:"array"},filter_by:{readonly:!0,dummyType:"array"},find_by:be,json_parse:be,json_parse_safe:be,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:be,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:be,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:be,if_null:be,if_else:be,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"},http_get:{dummyType:"string"},random:{dummyType:"number"},sleep_ms:{dummyType:"null"},prompt_human:{dummyType:"null"},prompt_human_config:{dummyType:"map"}}),xN={stdout:"",stderr:"",code:0,signal:null,timed_out:!1,duration_ms:0,pid:null,dry:!0};Be=Symbol("core dry policy"),Id=Symbol("dry invocation"),xd=Symbol("implicit preflight work limit"),Ad=Symbol("implicit preflight stdout");Gt=class extends Error{isControlFlow=!0;exitCode=0};Ka=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(),Qe(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[Ad],this.workLimit=e[xd]??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 Gt(this.truncation);if(this.sealed)throw new Gt("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 Gt(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(Qe)?Promise.all(n):void 0}fail(e,n=this.lastSite){throw this.check(),this.failure??={site:{...n},message:e,untrusted:this.tainted},new Gt(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=AN(e);if(r!==void 0){this.finishExit(r,n);return}if(e?.isControlFlow&&e?.resourceFailure===void 0)return;let s=e instanceof D?{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:Fd(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 h=String(a);return i(h.length),{$type:"bigint",value:h}}if(typeof a=="symbol"){r.has(a)||r.set(a,r.size+1);let h=String(a);return i(Buffer.byteLength(h)),{$type:"symbol",id:r.get(a),value:h}}if(typeof a>"u"||typeof a=="function")return{$type:typeof a};if(Oe(a))return{$type:"resource"};if(Ds.has(a)&&(a=Yr(a)),Ee.isProxy(a))return{$type:"proxy"};let u=Hd(a);if(u)return{$type:Ee.isMap(a)?"Map":Ee.isSet(a)?"Set":Ee.isDate(a)?"Date":Ee.isRegExp(a)?"RegExp":Ee.isNativeError(a)?"Error":Ee.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(h=>typeof h=="symbol"||h==="$ref"||h==="$type"||p&&h!=="length"&&!(/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)<a.length)),g=[];for(let h 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 h=="symbol"?"symbol:"+g.length:h;i(Buffer.byteLength(y));let b=Object.getOwnPropertyDescriptor(a,h),_="value"in b?o(b.value,f?l+"/properties/"+g.length+"/1":l+"/"+y.replaceAll("~","~0").replaceAll("/","~1"),c+1):{$type:"accessor"};f?g.push([typeof h=="symbol"?o(h,l+"/properties/"+g.length+"/0",c+1):h,_]):Object.defineProperty(d,y,{value:_,enumerable:!0,writable:!0,configurable:!0})}return f?{$type:p?"array":"object",...p?{length:a.length}:{},properties:g}: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 gd({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 gd({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 gd({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})}};CN=new Set(["read","read_file","read_lines","read_json","read_csv"]);Od=new WeakMap,Gi=class{constructor(e){Od.set(this,e)}},ON=5e3;LN=1,Ld=class{id;constructor(e){i_++,o_.add(this),Object.defineProperty(this,"id",{value:e,enumerable:!0}),Object.freeze(this)}},i_=0;o_=new WeakSet;Dy=new WeakMap,a_=1e7;Ji=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}},l_=new Fy;Md=class{token=`run-${process.pid}-${LN++}`;root=new Ji("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:ON}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 Ji(r,n);return this.scopes.set(e,s),s}temporaryScope(e,n,r){return new Ji(n,e,r)}register(e,n,r,s){let i=String(e.id),o={handle:new Ld(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 Dy.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}`:`${Dy.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(Qe(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(g=>{c=setTimeout(()=>g(!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}))}},za=class{nativeImports;processContext;warningDiagnostics=[];dry;platform;abortSignal;resources;resourcesEnabled;temporaryScopes=new Map;globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new Rd;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=Bi(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 ot,this.hostFunctions=new Map(e),this.promptHumanConfig=o??{mode:"interactive"},this.resourcesEnabled=[...this.hostFunctions.values()].some(k=>k.returnsResource===!0),this.resources=new Md(k=>{Fa(this.recovery,k);try{this.stderr?.(`error: ${k}`)}catch{}});let m=e.get("print");(!m||m.isDefault)&&this.hostFunctions.set("print",{...m,fn:(...k)=>{let N=m?.signature?.dryrunIndex===0?k.shift()===!0:!1,C=k.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return N||this.stdout(C),C},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:(...k)=>{let N=p?.signature?.dryrunIndex===0?k.shift()===!0:!1,C=k.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return N||this.stdout(C),C},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:(...k)=>{let N=f?.signature?.dryrunIndex===0?k.shift()===!0:!1,[C,...O]=k,w=ja(C,O,"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 g=e.get("require");(!g||g.isDefault)&&this.hostFunctions.set("require",{...g,fn:(k,N)=>Dd(k,N,C=>{Fa(this.recovery,C),this.stderr?.(`error: ${C}`)}),arity:2,isDefault:!0});let h=e.get("error");(!h||h.isDefault)&&this.hostFunctions.set("error",{...h,fn:(...k)=>{let N=k.map(C=>typeof C=="object"?JSON.stringify(C):String(C)).join(" ");return Fa(this.recovery,N),this.stderr?this.stderr(`error: ${N}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${N}
|
|
401
|
+
`,md=null;Ds=new WeakMap,Yi=new WeakMap,Ay=["get_property","has_property","get_properties","set_property"];Ga=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(WC(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=Fs(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))et(e.tree,n,structuredClone(r));return this.overlay&&(e.overlay=Fs(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(),!Ps(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=Ed(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);et(n,a,structuredClone(l))}}if(this.overlay){let s=Ed(this.overlay.properties,this.known,this.overlay.path);n=Qy(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))et(this.tree,s,i);this.loaded=!0}find(e,n=!0){let r=Xa(wd(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?Dn(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>"),Dn(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 Dn(n.value,n.key)}set(e,n){let r=Xa(wd(e),this.known);if(["Directory","NonInteractive"].includes(r.split(".")[0]))throw Error(`Property '${r}' is read-only`);let s=Dn(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)||et(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?Dn(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 et(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=Dn(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 Ds.set(s,n),Yi.set(s,()=>this.copy(e)),s}};Mn=new Fy;bN=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;Pn=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}},Sd=class{diagnostics=[];hostFunctions=new Map;knownHostReferences=new Map;options;functions=new Map;currentScope=new Pn;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 Pn,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 Pn(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 Pn(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 Pn(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 Pn(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 Pn(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!=="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(!j.statSync(n.value).isFile())throw new Error("path is not a regular file");j.accessSync(n.value,j.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(h=>h.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(h=>h.trim().replace(/^array$/,"list").replace(/^object$/,"map")),g=["string","number","boolean","null","list","map"];f.every(h=>g.includes(h))&&!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=wd(e)}catch(l){this.addError(l.message,n.line,n.column,n.file);return}let s=this.options.propertyDeclarations;if(!s||(r=Xa(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"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"||Ay.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(Wa,e.name)?Xi(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=Ja(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(Wa,e.callee)&&!this.options.sourcePackages?.has(e.callee.split(".")[0])?this.addError(Xi(e.callee),e.line,e.column,e.file):this.checkPackageMember(e.callee,e)),Ay.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=ji(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(Xi(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}}}};ar=class{value;constructor(e){this.value=e}},qt=class{},Xt=class{},lr=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},ot=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)}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)}},Va=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()}}},Rd=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let n=this.bindingLocks.get(e);return n||(n=new Va,this.bindingLocks.set(e,n)),n}getObjectLock(e){let n=this.objectLocks.get(e);return n||(n=new Va,this.objectLocks.set(e,n)),n}},be=Object.freeze({readonly:!0}),RN=t=>{for(let e of Object.values(t))Object.freeze(e);return Object.freeze(t)},IN=RN({warning:{readonly:!0,control:"warning",dummyType:"string"},which:be,get_property:be,has_property:be,get_properties:be,expand:be,set_property:{dummyType:"null"},read:be,read_file:be,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:be,pop:be,shift:be,unshift:be,insert:be,remove_at:be,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:be,last:be,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:be,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:be,getstr:{readonly:!0,dummyType:"string"},getnum:{readonly:!0,dummyType:"number"},getbool:{readonly:!0,dummyType:"boolean"},getlist:{readonly:!0,dummyType:"array"},set:be,delete_key:be,merge:{readonly:!0,dummyType:"map"},clone:be,pluck:{readonly:!0,dummyType:"array"},filter_by:{readonly:!0,dummyType:"array"},find_by:be,json_parse:be,json_parse_safe:be,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:be,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:be,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:be,if_null:be,if_else:be,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"},http_get:{dummyType:"string"},random:{dummyType:"number"},sleep_ms:{dummyType:"null"},prompt_human:{dummyType:"null"},prompt_human_config:{dummyType:"map"}}),xN={stdout:"",stderr:"",code:0,signal:null,timed_out:!1,duration_ms:0,pid:null,dry:!0};Be=Symbol("core dry policy"),Id=Symbol("dry invocation"),xd=Symbol("implicit preflight work limit"),Ad=Symbol("implicit preflight stdout");Gt=class extends Error{isControlFlow=!0;exitCode=0};Ka=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(),Ze(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[Ad],this.workLimit=e[xd]??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 Gt(this.truncation);if(this.sealed)throw new Gt("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 Gt(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(Ze)?Promise.all(n):void 0}fail(e,n=this.lastSite){throw this.check(),this.failure??={site:{...n},message:e,untrusted:this.tainted},new Gt(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=AN(e);if(r!==void 0){this.finishExit(r,n);return}if(e?.isControlFlow&&e?.resourceFailure===void 0)return;let s=e instanceof D?{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:Fd(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 h=String(a);return i(h.length),{$type:"bigint",value:h}}if(typeof a=="symbol"){r.has(a)||r.set(a,r.size+1);let h=String(a);return i(Buffer.byteLength(h)),{$type:"symbol",id:r.get(a),value:h}}if(typeof a>"u"||typeof a=="function")return{$type:typeof a};if(Oe(a))return{$type:"resource"};if(Ds.has(a)&&(a=Yr(a)),Ee.isProxy(a))return{$type:"proxy"};let u=Hd(a);if(u)return{$type:Ee.isMap(a)?"Map":Ee.isSet(a)?"Set":Ee.isDate(a)?"Date":Ee.isRegExp(a)?"RegExp":Ee.isNativeError(a)?"Error":Ee.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(h=>typeof h=="symbol"||h==="$ref"||h==="$type"||p&&h!=="length"&&!(/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)<a.length)),g=[];for(let h 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 h=="symbol"?"symbol:"+g.length:h;i(Buffer.byteLength(y));let b=Object.getOwnPropertyDescriptor(a,h),_="value"in b?o(b.value,f?l+"/properties/"+g.length+"/1":l+"/"+y.replaceAll("~","~0").replaceAll("/","~1"),c+1):{$type:"accessor"};f?g.push([typeof h=="symbol"?o(h,l+"/properties/"+g.length+"/0",c+1):h,_]):Object.defineProperty(d,y,{value:_,enumerable:!0,writable:!0,configurable:!0})}return f?{$type:p?"array":"object",...p?{length:a.length}:{},properties:g}: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 gd({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 gd({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 gd({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})}};CN=new Set(["read","read_file","read_lines","read_json","read_csv"]);Od=new WeakMap,Gi=class{constructor(e){Od.set(this,e)}},ON=5e3;LN=1,Ld=class{id;constructor(e){i_++,o_.add(this),Object.defineProperty(this,"id",{value:e,enumerable:!0}),Object.freeze(this)}},i_=0;o_=new WeakSet;Dy=new WeakMap,a_=1e7;Ji=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}},l_=new Fy;Md=class{token=`run-${process.pid}-${LN++}`;root=new Ji("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:ON}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 Ji(r,n);return this.scopes.set(e,s),s}temporaryScope(e,n,r){return new Ji(n,e,r)}register(e,n,r,s){let i=String(e.id),o={handle:new Ld(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 Dy.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}`:`${Dy.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(Ze(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(g=>{c=setTimeout(()=>g(!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}))}},za=class{nativeImports;processContext;warningDiagnostics=[];dry;platform;abortSignal;resources;resourcesEnabled;temporaryScopes=new Map;globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new Rd;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=Bi(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 ot,this.hostFunctions=new Map(e),this.promptHumanConfig=o??{mode:"interactive"},this.resourcesEnabled=[...this.hostFunctions.values()].some(k=>k.returnsResource===!0),this.resources=new Md(k=>{Fa(this.recovery,k);try{this.stderr?.(`error: ${k}`)}catch{}});let m=e.get("print");(!m||m.isDefault)&&this.hostFunctions.set("print",{...m,fn:(...k)=>{let N=m?.signature?.dryrunIndex===0?k.shift()===!0:!1,C=k.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return N||this.stdout(C),C},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:(...k)=>{let N=p?.signature?.dryrunIndex===0?k.shift()===!0:!1,C=k.map(O=>typeof O=="object"?JSON.stringify(O):String(O)).join(" ");return N||this.stdout(C),C},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:(...k)=>{let N=f?.signature?.dryrunIndex===0?k.shift()===!0:!1,[C,...O]=k,w=ja(C,O,"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 g=e.get("require");(!g||g.isDefault)&&this.hostFunctions.set("require",{...g,fn:(k,N)=>Dd(k,N,C=>{Fa(this.recovery,C),this.stderr?.(`error: ${C}`)}),arity:2,isDefault:!0});let h=e.get("error");(!h||h.isDefault)&&this.hostFunctions.set("error",{...h,fn:(...k)=>{let N=k.map(C=>typeof C=="object"?JSON.stringify(C):String(C)).join(" ");return Fa(this.recovery,N),this.stderr?this.stderr(`error: ${N}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${N}
|
|
402
402
|
`):console.error(`error: ${N}`),N},arity:{min:1},description:h?.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:(k,N)=>Vy(k,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:(k,N)=>{if(k===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 k=="string")k==="interactive"?this.promptHumanConfig.mode="interactive":k==="file"?(this.promptHumanConfig.mode="file",N&&(this.promptHumanConfig.dir=String(N))):(this.promptHumanConfig.mode="file",this.promptHumanConfig.dir=k);else if(k&&typeof k=="object"){let C=k.mode?String(k.mode):k.dir?"file":this.promptHumanConfig.mode??"interactive",O=k.dir!==void 0?String(k.dir):this.promptHumanConfig.dir,w=k.timeout_ms!==void 0?Number(k.timeout_ms):k.timeoutMs!==void 0?Number(k.timeoutMs):this.promptHumanConfig.timeoutMs,S=k.poll_ms!==void 0?Number(k.poll_ms):k.pollIntervalMs!==void 0?Number(k.pollIntervalMs):this.promptHumanConfig.pollIntervalMs;this.promptHumanConfig.mode=C==="file"?"file":"interactive",this.promptHumanConfig.dir=O,this.promptHumanConfig.timeoutMs=typeof w=="number"&&Number.isFinite(w)?w:void 0,this.promptHumanConfig.pollIntervalMs=typeof S=="number"&&Number.isFinite(S)&&S>0?S: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:(k,N)=>{if((N?.mode??(N?.dir?"file":this.promptHumanConfig.mode??"interactive"))==="file"){let O=N?.dir??this.promptHumanConfig.dir;if(!O)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 zy(k,{dir:O,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?Za(k,void 0,void 0,this.abortSignal):Ky(k)},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:(k,N)=>Fd(k,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:(k,N=[])=>{let C=this.processContext,O=re.resolve(C?.cwd??process.cwd(),String(k));if(!j.existsSync(O))throw new Error(`run_script: file not found: '${O}'`);let w=j.readFileSync(O,"utf-8"),S=Array.isArray(N)?N.map(String):[],R=this.childEngineFactory?this.childEngineFactory({args:S}):new cr;if(!this.childEngineFactory){for(let[x,A]of this.hostFunctions)R.hasFunction(x)?A.isDefault||R.registerFunction(x,A.fn,A.signature?.nativeArity??A.arity,{description:A.description,params:A.signature?.nativeParams??A.params,returnType:A.returnType,readonly:A.readonly,dryControl:A.dryControl,[Be]:A[Be],doc:A.doc,allowOverwrite:!0,isContainerMutation:A.isContainerMutation,...Qr(A)},!1,A.isContainerMutation):R.registerFunction(x,A.fn,A.signature?.nativeArity??A.arity,{description:A.description,params:A.signature?.nativeParams??A.params,returnType:A.returnType,readonly:A.readonly,dryControl:A.dryControl,[Be]:A[Be],doc:A.doc,isDefault:A.isDefault,isContainerMutation:A.isContainerMutation,...Qr(A)});R.setGlobal("args",[...S]),R.setGlobal("ARGV",[...S])}if(this.isAsync)return(async()=>{let x=await R.runAsync(w,{file:O,signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight,hostContext:C,propertyStore:this.compileOptions?.propertyStore}),A=Zr(x.value);if(A)throw new Error(`run_script: ${Oe(A)?`the child result contains resource ${A.id}, which cannot leave the child run`:hd(A,"child run")}`);let M=x.output.join(`
|
|
403
403
|
`)+(x.output.length>0?`
|
|
404
404
|
`:""),P=x.exitCode!==void 0?x.exitCode:x.success&&!x.errors?.length?0:1,U={success:x.success&&P===0,stdout:M,output:[...x.output],value:x.value,exit_code:P,code:P,errors:x.errors??[]};for(let F of[...x.errors??[],...x.diagnostics.filter(ee=>ee.severity==="error").map(ee=>ee.message)])this.recordedErrors.push(F);return U})();{let x=R.run(w,{file:O,signal:this.abortSignal,platform:this.platform,noPreflight:this.noPreflight,hostContext:C,propertyStore:this.compileOptions?.propertyStore}),A=x.output.join(`
|
|
405
405
|
`)+(x.output.length>0?`
|
|
406
|
-
`:""),M=x.exitCode!==void 0?x.exitCode:x.success&&!x.errors?.length?0:1,P={success:x.success&&M===0,stdout:A,output:[...x.output],value:x.value,exit_code:M,code:M,errors:x.errors??[]};for(let U of[...x.errors??[],...x.diagnostics.filter(F=>F.severity==="error").map(F=>F.message)])this.recordedErrors.push(U);return P}},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 I=e.get("http_get");(!I||I.isDefault)&&this.hostFunctions.set("http_get",{...I,fn:k=>this.isAsync?VC(k):Wy(k),arity:I?.arity??1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let T=e.get("sleep_ms");if((!T||T.isDefault)&&this.hostFunctions.set("sleep_ms",{...T,fn:k=>{if(typeof k!="number"||!Number.isFinite(k)||k<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(k>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(C=>setTimeout(C,k));let N=Date.now()+k;for(;Date.now()<N;);return null},arity:T?.arity??1,description:"Sleeps for the specified milliseconds",isDefault:!0}),this.dry)for(let[k,N]of e)N.signature?.dryrunIndex!==void 0&&this.hostFunctions.set(k,N)}evaluateProgram(e){if(this.globalEnv=new ot,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 D("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 D("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 D(`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(Ke(this.abortSignal),this.recovery.pending.length>0)throw new D(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(Ke(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new D(`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 D(`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){switch(this.dry?.at(e),Ke(this.abortSignal),e.kind){case"PackageStmt":{if(e.nativeModule&&!this.dry){let r=this.nativeImports?.get(e.nativeModule)?.();if(Qe(r))throw new D("Native import requires runAsync",e.line,e.column,"RUNTIME",e.file)}return}case"ImportStmt":return;case"BlockStmt":{let r=new ot(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 D(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.execStmt(e.thenBranch,n):e.elseBranch?this.execStmt(e.elseBranch,n):void 0}case"WhileStmt":{let r=0;for(;!this.dry?.loop(r,e)&&this.isTruthy(this.evalExpr(e.condition,n));){if(++r>1e6&&!this.dry)throw new D("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(s){if(s instanceof qt)break;if(s instanceof Xt)continue;throw s}}return}case"ForInStmt":{let r=xy(this.evalExpr(e.iterable,n),e,this.dry),s=0;for(let i=0;(i<r.length||this.dry&&s===this.dry.loopLimit)&&!this.dry?.loop(s,e);i++){let o=r[i];if(++s>1e6&&!this.dry)throw new D("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new ot(n);a.define(e.name,o);try{if(e.body.kind==="BlockStmt")for(let l of e.body.statements)this.execStmt(l,a);else this.execStmt(e.body,a)}catch(l){if(l instanceof qt)break;if(l instanceof Xt)continue;throw l}}return}case"ForStmt":{let r=new ot(n);e.init&&this.execStmt(e.init,r);let s=0;for(;!this.dry?.loop(s,e);){if(e.condition){let i=this.evalExpr(e.condition,r);if(!this.isTruthy(i))break}if(++s>1e6&&!this.dry)throw new D("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(i){if(i instanceof qt)break;if(!(i instanceof Xt))throw i}if(this.dry?.loop(s,e))break;e.update&&this.evalExpr(e.update,r)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new ar(r)}case"BreakStmt":throw new qt;case"ContinueStmt":throw new Xt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new D("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,n);case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new ot(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 xt(this.recovery,o),o}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(Ke(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=Iy(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:kd(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new D("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let r=this.evalExpr(e.value,n),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 D(`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),Ze(r,s,i),i;throw new D("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)Ze(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Ja(e);if(r)try{this.dry&&this.dry.at(e);let o=this.dry?.prepareProperties(r);if(Qe(o))throw o.catch(()=>{}),Error("Async properties require dryRunAsync");return ht(this.dry?this.dry.propertyView:this.resolveIdentifier("PROPS",n,e),r)}catch(o){throw this.dry?new D(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 D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:Ly(s,i,e,this.dry)}case"UnaryExpr":{let r=this.evalExpr(e.operand,n),s=e.operator;if(s==="!")return!this.isTruthy(r);if(s==="-")return-r;throw new D(`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 D("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 D(`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"&&Od.has(s)){this.dry&&this.dry.at(r);try{let i=Od.get(s)();return Qe(i)?i.catch(o=>{throw new D(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new D(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new lr(e);throw new D(`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 lr?r.name:e}invokeNamed(e,n,r,s,i,o){if(this.dry?.at({line:s,column:i,file:o}),Ke(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>La)throw this.callDepth--,new D(`Execution fuel exhausted: maximum function call depth exceeded (${La})`,s,i,"RUNTIME",o);let l=new ot(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 ar)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{if(a[Be]?.control==="warning"){Wi(a,n);let u=String(this.dry?en(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:u,line:s,column:i,file:o}),u}if(this.dry){let u=My(a,n,e,{line:s,column:i,file:o},this.dry,this.platform);if(u.skip)return u.value;let d=Hi(a,u.args);if(this.dry.check(),Qe(d)&&(Promise.resolve(d).catch(()=>{}),this.dry.fail("Async host requires dryRunAsync",{line:s,column:i,file:o})),this.dry.failure)throw new Gt(this.dry.failure.message);return Zr(d)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:o}),a[Be]?.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=Wi(a,n);if(a.returnsResource)throw new D(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);Ke(this.abortSignal);let c=Hi(a,l);if(a.returnsResource&&Qe(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 At||l?.name==="LMScriptExit"||l?.isControlFlow?l:new D(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new D(`'${e}' is not a function`,s,i,"RUNTIME",o):new D(Xi(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){if(!this.resourcesEnabled||e.kind==="BlockStmt"){await this.execStmtAsync(e,n,r);return}let s=this.resources.temporaryScope(this.ownerFor(n,r),"iteration",this.resources.scopeFor(n));this.pushTemporaryScope(r,s);try{await this.execStmtAsync(e,n,r)}catch(i){throw xt(this.recovery,i),s.failure=or(i),i}finally{this.popTemporaryScope(r),s.records.length>0&&await this.resources.drain(s)}}resourceError(e,n,r){return new D(`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 D(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 ot,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 xt(this.recovery,s),this.resources.root.failure=or(s),s}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),Oe(r))r=null;else if(Py()){let s=Zr(r);if(s)throw new D(Oe(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:hd(s,"run"),1,1,"RUNTIME")}return r}async execStmtAsync(e,n,r){switch(this.dry?.at(e),Ke(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 ot(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 xt(this.recovery,o),i.failure=or(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 D(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,n,r):e.elseBranch?await this.execStmtAsync(e.elseBranch,n,r):void 0}case"WhileStmt":{let s=0;for(;!this.dry?.loop(s,e)&&this.isTruthy(await this.evalExprAsync(e.condition,n,r));){if(++s>1e6&&!this.dry)throw new D("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,n,r):await this.execStmtAsync(e.body,n,r)}catch(i){if(i instanceof qt)break;if(i instanceof Xt)continue;throw i}}return}case"ForInStmt":{let s=xy(await this.evalExprAsync(e.iterable,n,r),e,this.dry),i=0;for(let o=0;(o<s.length||this.dry&&i===this.dry.loopLimit)&&!this.dry?.loop(i,e);o++){let a=s[o];if(++i>1e6&&!this.dry)throw new D("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let l=new ot(n);l.define(e.name,a);let c=this.resourcesEnabled?this.resources.enterScope(l,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let u of e.body.statements)await this.execStmtAsync(u,l,r);else await this.execStmtAsync(e.body,l,r)}catch(u){throw xt(this.recovery,u),c&&(c.failure=or(u)),u}finally{c&&c.records.length>0&&await this.resources.drain(c)}}catch(u){if(u instanceof qt)break;if(u instanceof Xt)continue;throw u}}return}case"ForStmt":{let s=new ot(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;for(;!this.dry?.loop(o,e);){if(e.condition){let a=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(a))break}if(++o>1e6&&!this.dry)throw new D("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,s,r):await this.execStmtAsync(e.body,s,r)}catch(a){if(a instanceof qt)break;if(!(a instanceof Xt))throw a}if(this.dry?.loop(o,e))break;e.update&&await this.evalExprAsync(e.update,s,r)}}catch(o){throw xt(this.recovery,o),i&&(i.failure=or(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 ar(s)}case"BreakStmt":throw new qt;case"ContinueStmt":throw new Xt;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 D(`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 D("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),Ze(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new D("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 D(`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 D("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":return await this.evalExprAsync(e.expr,n,r);case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new ot(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 xt(this.recovery,l),o&&(o.failure=or(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(Ke(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=Iy(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+=kd(o,i)}return s}case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let s=await this.evalExprAsync(e.value,n,r),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 D(`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),Ze(s,i,o),o;throw new D("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),Ze(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=Py()?Zr(p):void 0;if(f)throw new D(Oe(f)?`Resource ${this.resources.describe(f)} cannot be a parallel task result: it stays with the task that opened it`:hd(f,"parallel task"),u.line,u.column,"RUNTIME",u.file);return p}catch(p){throw this.dry?.captureFailure(p,u),xt(this.recovery,p),m&&(m.failure=or(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=Ja(e);if(s)try{return this.dry&&(this.dry.at(e),await this.dry.prepareProperties(s)),ht(this.dry?this.dry.propertyView:await this.resolveIdentifier("PROPS",n,e),s)}catch(a){throw this.dry?new D(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 D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(i)&&typeof o=="number"&&o<0?i[i.length+o]:Ly(i,o,e,this.dry)}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 D(`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 D("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 D(`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){this.dry?.at({line:s,column:i,file:a});let l=this.resolveCallTarget(e,r);if(Ke(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>La)throw this.asyncCallDepth.set(o,u-1),new D(`Execution fuel exhausted: maximum function call depth exceeded (${La})`,s,i,"RUNTIME",a);let d=new ot(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 ar)return p.value;throw this.dry?.captureFailure(p),xt(this.recovery,p),m&&(m.failure=or(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[Be]?.control==="warning"){Wi(c,n);let g=String(this.dry?en(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:g,line:s,column:i,file:a}),g}if(this.dry){let g=My(c,n,l,{line:s,column:i,file:a},this.dry,this.platform);if(g.skip)return g.value;let h=await this.dry.wait(Hi(c,g.args));if(this.dry.failure)throw new Gt(this.dry.failure.message);return Zr(h)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:a}),c[Be]?.taints===!1&&this.dry.captureOutput(l,h),g.handled&&this.dry.record(l,g.publicArgs,{line:s,column:i,file:a},"handled",void 0,g.taints),h}let u=Wi(c,n),d=MN(u)?await this.resourceCallArgs(c,l,u,s,i,a):u,p=c.returnsResource||c.usesResource||c.closesResource?l_.run({runtime:this.resources,scope:this.ownerFor(r,o),site:(a??"<main>")+":"+s+":"+i},()=>Hi(c,d)):Hi(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 At||u?.name==="LMScriptExit"||u?.isControlFlow?u:new D(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new D(`'${l}' is not a function`,s,i,"RUNTIME",a):new D(Xi(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},PN=[{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;"}],DN=[{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 last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:"join(arr: array, [separator: string]): string",description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"upper_first",category:"Strings",signature:"upper_first(s: string): string",description:"Capitalizes the first character of a string.",example:'c = upper_first("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the UTF-16 code unit at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"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");'}],FN=[{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);"}];cr=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=>dd(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=Zt(n,{min:n==="printf"?2:0},s,"string",r.doc),o=r.fn;n==="printf"?r.fn=(a,...l)=>a?ja(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=IN[n];s&&(r[Be]=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 PN)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of DN)this.registerFunctionDoc({...e,module:e.module??"core"});for(let e of FN)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){let n=fd({...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:Zt(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=>j.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>j.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=j.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
|
|
406
|
+
`:""),M=x.exitCode!==void 0?x.exitCode:x.success&&!x.errors?.length?0:1,P={success:x.success&&M===0,stdout:A,output:[...x.output],value:x.value,exit_code:M,code:M,errors:x.errors??[]};for(let U of[...x.errors??[],...x.diagnostics.filter(F=>F.severity==="error").map(F=>F.message)])this.recordedErrors.push(U);return P}},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 I=e.get("http_get");(!I||I.isDefault)&&this.hostFunctions.set("http_get",{...I,fn:k=>this.isAsync?VC(k):Wy(k),arity:I?.arity??1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let T=e.get("sleep_ms");if((!T||T.isDefault)&&this.hostFunctions.set("sleep_ms",{...T,fn:k=>{if(typeof k!="number"||!Number.isFinite(k)||k<0)throw new Error("sleep_ms() duration must be a non-negative finite number");if(k>2147483647)throw new Error("sleep_ms() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(C=>setTimeout(C,k));let N=Date.now()+k;for(;Date.now()<N;);return null},arity:T?.arity??1,description:"Sleeps for the specified milliseconds",isDefault:!0}),this.dry)for(let[k,N]of e)N.signature?.dryrunIndex!==void 0&&this.hostFunctions.set(k,N)}evaluateProgram(e){if(this.globalEnv=new ot,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 D("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 D("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 D(`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(Ke(this.abortSignal),this.recovery.pending.length>0)throw new D(`resumepoint path not consumed: ${this.recovery.pending.join(".")}`,e.line,e.column,"RUNTIME",e.file)}checkRootRemainder(e){if(Ke(this.abortSignal),!(this.recordedErrors.length>0)&&this.recovery.pending.length>0)throw new D(`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 D(`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){switch(this.dry?.at(e),Ke(this.abortSignal),e.kind){case"PackageStmt":{if(e.nativeModule&&!this.dry){let r=this.nativeImports?.get(e.nativeModule)?.();if(Ze(r))throw new D("Native import requires runAsync",e.line,e.column,"RUNTIME",e.file)}return}case"ImportStmt":return;case"BlockStmt":{let r=new ot(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 D(`Cannot destructure non-array value (got ${typeof r})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<r.length?r[s]:null;n.define(e.names[s],i)}return r}case"IfStmt":{let r=this.evalExpr(e.condition,n);return this.isTruthy(r)?this.execStmt(e.thenBranch,n):e.elseBranch?this.execStmt(e.elseBranch,n):void 0}case"WhileStmt":{let r=0;for(;!this.dry?.loop(r,e)&&this.isTruthy(this.evalExpr(e.condition,n));){if(++r>1e6&&!this.dry)throw new D("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(s){if(s instanceof qt)break;if(s instanceof Xt)continue;throw s}}return}case"ForInStmt":{let r=xy(this.evalExpr(e.iterable,n),e,this.dry),s=0;for(let i=0;(i<r.length||this.dry&&s===this.dry.loopLimit)&&!this.dry?.loop(s,e);i++){let o=r[i];if(++s>1e6&&!this.dry)throw new D("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new ot(n);a.define(e.name,o);try{if(e.body.kind==="BlockStmt")for(let l of e.body.statements)this.execStmt(l,a);else this.execStmt(e.body,a)}catch(l){if(l instanceof qt)break;if(l instanceof Xt)continue;throw l}}return}case"ForStmt":{let r=new ot(n);e.init&&this.execStmt(e.init,r);let s=0;for(;!this.dry?.loop(s,e);){if(e.condition){let i=this.evalExpr(e.condition,r);if(!this.isTruthy(i))break}if(++s>1e6&&!this.dry)throw new D("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(i){if(i instanceof qt)break;if(!(i instanceof Xt))throw i}if(this.dry?.loop(s,e))break;e.update&&this.evalExpr(e.update,r)}return}case"ReturnStmt":{let r=e.value?this.evalExpr(e.value,n):null;throw new ar(r)}case"BreakStmt":throw new qt;case"ContinueStmt":throw new Xt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new D("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,n);case"RecoverStmt":{let r=this.enterRecover(e,!1),s=new ot(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 xt(this.recovery,o),o}finally{this.leaveRecover(i)}return}default:return}}evalExpr(e,n){switch(Ke(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=Iy(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:kd(this.evalExpr(s.expression,n),s);return r}case"ParallelExpr":throw new D("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let r=this.evalExpr(e.value,n),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 D(`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),et(r,s,i),i;throw new D("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)et(r,s.key,this.evalExpr(s.value,n));return r}case"IndexExpr":{let r=Ja(e);if(r)try{this.dry&&this.dry.at(e);let o=this.dry?.prepareProperties(r);if(Ze(o))throw o.catch(()=>{}),Error("Async properties require dryRunAsync");return ht(this.dry?this.dry.propertyView:this.resolveIdentifier("PROPS",n,e),r)}catch(o){throw this.dry?new D(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 D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:Ly(s,i,e,this.dry)}case"UnaryExpr":{let r=this.evalExpr(e.operand,n),s=e.operator;if(s==="!")return!this.isTruthy(r);if(s==="-")return-r;throw new D(`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 D("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 D(`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"&&Od.has(s)){this.dry&&this.dry.at(r);try{let i=Od.get(s)();return Ze(i)?i.catch(o=>{throw new D(String(o.message??o),r.line,r.column,"RUNTIME",r.file)}):i}catch(i){throw new D(String(i.message??i),r.line,r.column,"RUNTIME",r.file)}}return s}if(this.userFunctions.has(e)||this.hostFunctions.has(e))return new lr(e);throw new D(`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 lr?r.name:e}invokeNamed(e,n,r,s,i,o){if(this.dry?.at({line:s,column:i,file:o}),Ke(this.abortSignal),this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>La)throw this.callDepth--,new D(`Execution fuel exhausted: maximum function call depth exceeded (${La})`,s,i,"RUNTIME",o);let l=new ot(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 ar)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{if(a[Be]?.control==="warning"){Wi(a,n);let u=String(this.dry?en(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:u,line:s,column:i,file:o}),u}if(this.dry){let u=My(a,n,e,{line:s,column:i,file:o},this.dry,this.platform);if(u.skip)return u.value;let d=Hi(a,u.args);if(this.dry.check(),Ze(d)&&(Promise.resolve(d).catch(()=>{}),this.dry.fail("Async host requires dryRunAsync",{line:s,column:i,file:o})),this.dry.failure)throw new Gt(this.dry.failure.message);return Zr(d)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:o}),a[Be]?.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=Wi(a,n);if(a.returnsResource)throw new D(`'${e}' returns a resource and requires engine.runAsync(); the synchronous engine.run refuses to call it`,s,i,"RUNTIME",o);Ke(this.abortSignal);let c=Hi(a,l);if(a.returnsResource&&Ze(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 At||l?.name==="LMScriptExit"||l?.isControlFlow?l:new D(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw r.has(e)?new D(`'${e}' is not a function`,s,i,"RUNTIME",o):new D(Xi(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){if(!this.resourcesEnabled||e.kind==="BlockStmt"){await this.execStmtAsync(e,n,r);return}let s=this.resources.temporaryScope(this.ownerFor(n,r),"iteration",this.resources.scopeFor(n));this.pushTemporaryScope(r,s);try{await this.execStmtAsync(e,n,r)}catch(i){throw xt(this.recovery,i),s.failure=or(i),i}finally{this.popTemporaryScope(r),s.records.length>0&&await this.resources.drain(s)}}resourceError(e,n,r){return new D(`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 D(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 ot,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 xt(this.recovery,s),this.resources.root.failure=or(s),s}finally{await this.resources.drain(this.resources.root)}if(this.checkRootRemainder(e),Oe(r))r=null;else if(Py()){let s=Zr(r);if(s)throw new D(Oe(s)?`Resource ${this.resources.describe(s)} cannot leave the run inside the result value`:hd(s,"run"),1,1,"RUNTIME")}return r}async execStmtAsync(e,n,r){switch(this.dry?.at(e),Ke(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 ot(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 xt(this.recovery,o),i.failure=or(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 D(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;n.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,n,r);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,n,r):e.elseBranch?await this.execStmtAsync(e.elseBranch,n,r):void 0}case"WhileStmt":{let s=0;for(;!this.dry?.loop(s,e)&&this.isTruthy(await this.evalExprAsync(e.condition,n,r));){if(++s>1e6&&!this.dry)throw new D("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,n,r):await this.execStmtAsync(e.body,n,r)}catch(i){if(i instanceof qt)break;if(i instanceof Xt)continue;throw i}}return}case"ForInStmt":{let s=xy(await this.evalExprAsync(e.iterable,n,r),e,this.dry),i=0;for(let o=0;(o<s.length||this.dry&&i===this.dry.loopLimit)&&!this.dry?.loop(i,e);o++){let a=s[o];if(++i>1e6&&!this.dry)throw new D("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let l=new ot(n);l.define(e.name,a);let c=this.resourcesEnabled?this.resources.enterScope(l,this.ownerFor(n,r),"iteration"):void 0;try{try{if(e.body.kind==="BlockStmt")for(let u of e.body.statements)await this.execStmtAsync(u,l,r);else await this.execStmtAsync(e.body,l,r)}catch(u){throw xt(this.recovery,u),c&&(c.failure=or(u)),u}finally{c&&c.records.length>0&&await this.resources.drain(c)}}catch(u){if(u instanceof qt)break;if(u instanceof Xt)continue;throw u}}return}case"ForStmt":{let s=new ot(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;for(;!this.dry?.loop(o,e);){if(e.condition){let a=await this.evalExprAsync(e.condition,s,r);if(!this.isTruthy(a))break}if(++o>1e6&&!this.dry)throw new D("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.resourcesEnabled?await this.execLoopBodyAsync(e.body,s,r):await this.execStmtAsync(e.body,s,r)}catch(a){if(a instanceof qt)break;if(!(a instanceof Xt))throw a}if(this.dry?.loop(o,e))break;e.update&&await this.evalExprAsync(e.update,s,r)}}catch(o){throw xt(this.recovery,o),i&&(i.failure=or(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 ar(s)}case"BreakStmt":throw new qt;case"ContinueStmt":throw new Xt;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 D(`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 D("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),et(s,o,a)},r);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new D("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 D(`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 D("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],n,r));await this.invokeCallAsync(s.callee,[o,...l],n,e.line,e.column,r,e.file)},r);return}case"ExprStmt":return await this.evalExprAsync(e.expr,n,r);case"RecoverStmt":{let s=this.enterRecover(e,r!==this.recovery.rootTaskId),i=new ot(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 xt(this.recovery,l),o&&(o.failure=or(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(Ke(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=Iy(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+=kd(o,i)}return s}case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,n,e);case"AssignExpr":{let s=await this.evalExprAsync(e.value,n,r),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 D(`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),et(s,i,o),o;throw new D("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),et(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=Py()?Zr(p):void 0;if(f)throw new D(Oe(f)?`Resource ${this.resources.describe(f)} cannot be a parallel task result: it stays with the task that opened it`:hd(f,"parallel task"),u.line,u.column,"RUNTIME",u.file);return p}catch(p){throw this.dry?.captureFailure(p,u),xt(this.recovery,p),m&&(m.failure=or(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=Ja(e);if(s)try{return this.dry&&(this.dry.at(e),await this.dry.prepareProperties(s)),ht(this.dry?this.dry.propertyView:await this.resolveIdentifier("PROPS",n,e),s)}catch(a){throw this.dry?new D(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 D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(i)&&typeof o=="number"&&o<0?i[i.length+o]:Ly(i,o,e,this.dry)}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 D(`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 D("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 D(`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){this.dry?.at({line:s,column:i,file:a});let l=this.resolveCallTarget(e,r);if(Ke(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>La)throw this.asyncCallDepth.set(o,u-1),new D(`Execution fuel exhausted: maximum function call depth exceeded (${La})`,s,i,"RUNTIME",a);let d=new ot(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 ar)return p.value;throw this.dry?.captureFailure(p),xt(this.recovery,p),m&&(m.failure=or(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[Be]?.control==="warning"){Wi(c,n);let g=String(this.dry?en(n)[0]:n[0]);return this.warningDiagnostics.push({severity:"warning",message:g,line:s,column:i,file:a}),g}if(this.dry){let g=My(c,n,l,{line:s,column:i,file:a},this.dry,this.platform);if(g.skip)return g.value;let h=await this.dry.wait(Hi(c,g.args));if(this.dry.failure)throw new Gt(this.dry.failure.message);return Zr(h)&&this.dry.fail("Dry host returned a live or unsupported capability",{line:s,column:i,file:a}),c[Be]?.taints===!1&&this.dry.captureOutput(l,h),g.handled&&this.dry.record(l,g.publicArgs,{line:s,column:i,file:a},"handled",void 0,g.taints),h}let u=Wi(c,n),d=MN(u)?await this.resourceCallArgs(c,l,u,s,i,a):u,p=c.returnsResource||c.usesResource||c.closesResource?l_.run({runtime:this.resources,scope:this.ownerFor(r,o),site:(a??"<main>")+":"+s+":"+i},()=>Hi(c,d)):Hi(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 At||u?.name==="LMScriptExit"||u?.isControlFlow?u:new D(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw r.has(l)?new D(`'${l}' is not a function`,s,i,"RUNTIME",a):new D(Xi(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},PN=[{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;"}],DN=[{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 last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:"join(arr: array, [separator: string]): string",description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"upper_first",category:"Strings",signature:"upper_first(s: string): string",description:"Capitalizes the first character of a string.",example:'c = upper_first("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the UTF-16 code unit at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"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");'}],FN=[{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);"}];cr=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=>dd(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=Zt(n,{min:n==="printf"?2:0},s,"string",r.doc),o=r.fn;n==="printf"?r.fn=(a,...l)=>a?ja(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=IN[n];s&&(r[Be]=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 PN)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of DN)this.registerFunctionDoc({...e,module:e.module??"core"});for(let e of FN)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){let n=fd({...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:Zt(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=>j.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>j.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let n=j.readFileSync(e,"utf-8"),r=n.length>0;return n.endsWith(`\r
|
|
407
407
|
`)?n=n.slice(0,-2):n.endsWith(`
|
|
408
408
|
`)&&(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(`
|
|
409
409
|
`)+`
|
|
@@ -412,7 +412,7 @@ fn clamp(val, low, high) {
|
|
|
412
412
|
`:""),u=l.exitCode!==void 0?l.exitCode:l.success&&!l.errors?.length?0:1;return{success:l.success&&u===0,stdout:c,output:[...l.output],value:l.value,exit_code:u,code:u,errors:l.errors??[]}})();{let l=o.run(s,a),c=l.output.join(`
|
|
413
413
|
`)+(l.output.length>0?`
|
|
414
414
|
`:""),u=l.exitCode!==void 0?l.exitCode:l.success&&!l.errors?.length?0:1;return{success:l.success&&u===0,stdout:c,output:[...l.output],value:l.value,exit_code:u,code:u,errors:l.errors??[]}}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${n}
|
|
415
|
-
`):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=>Wy(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 zy(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?Za(e):Ky(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)=>dN(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(Yr(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(Yr(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(Yr(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=Ui(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=Ui(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=Ui(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=Ui(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=Ui(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",Dd,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];(ht(i,a)==null||typeof ht(i,a)!="object")&&Ze(i,a,{}),i=ht(i,a)}return s.length>0&&Ze(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=>ht(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&ht(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&&ht(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...Yr(e),...Yr(n)}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,n)=>(e&&typeof e=="object"&&delete e[n],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints line to output log",!0),this.registerFunction("split",(e,n)=>String(e).split(n),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let n=e.split(/\r?\n/);for(let r=n.length-1;r>=0;r--){let s=n[r].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("parse_file_blocks",e=>zC(e),1,"Parses === FILE: path === ... === END === blocks into [{path, content}]"),this.registerFunction("format_file_blocks",e=>YC(e),1,"Formats [{path, content}] as file blocks; inverse of parse_file_blocks"),this.registerFunction("write_files",(e,n,r)=>nN(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)=>oN(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=>cN(e),1,"Parses key: value lines of the last paragraph into a map"),this.registerFunction("split_command",e=>uN(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 lr,1,"Checks if value is a first-class function reference"),this.registerFunction("cmd_render",(e,n)=>Fd(e,n),{min:1,max:2},"Renders argv as posix, windows or powershell text; execution never uses rendered text",!0),this.registerFunction("sprintf",(e,...n)=>ja(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>ja(e,n,"printf"),{min:1},"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules",!0),this.registerFunction("format",(e,...n)=>{let r=String(e),s=n.length===1&&typeof n[0]=="object"&&n[0]!==null&&!Array.isArray(n[0])?n[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<r.length;){let c=r[l];if(c==="{"&&r[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&r[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=r.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=r.slice(l+1,u);if(d==="")o+=i<n.length?a(n[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<n.length?a(n[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("regex_test",(e,n,r="")=>qi(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",pN,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",fN,{min:2,max:3},"Returns capture arrays with Unicode-aware zero-width progress; y is rejected"),this.registerFunction("regex_replace",(e,n,r,s="")=>String(e).replace(qi(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(qi(n,r)),{min:2,max:3},"Splits text at regular expression matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("range",(e,n,r=1)=>{let s=n===void 0?0:e,i=n===void 0?e:n,o=[];if(r>0)for(let a=s;a<i;a+=r)o.push(a);else if(r<0)for(let a=s;a>i;a+=r)o.push(a);return o},{min:1,max:3},"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...n)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...n)},{min:0},"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,n)=>Math.pow(e,n),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("sha256",e=>{if(typeof e!="string")throw new Error("sha256: expected a string");return XC("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)=>$N(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=>pd(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 lr?"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=fd(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}:{},g=typeof s=="object"?s.params?.map(Nd):void 0,h=typeof s=="object"?s.returnType:void 0,y=Zt(e,r,g,h,u);Oy(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:h,readonly:b,...typeof s=="object"&&s[Be]?{[Be]:s[Be]}:{},dryControl:Pa(e,typeof s=="object"?s.dryControl:void 0,y),signature:y,...f}),u)this.functionDocs.set(e,{...u,module:u.module??m});else{let _=y.publicArity,v=typeof _=="number"?_:_?.min??0,E=typeof _=="number"?_:_?.max,I=y.publicParams.length?y.publicParams.map(T=>T.optional?`[${T.name}]`:T.rest?`...${T.name}`:T.name):Array.from({length:E??v},(T,k)=>(k>=v?"[":"")+"arg"+(k+1)+(k>=v?"]":""));E===void 0&&!y.publicParams.some(T=>T.rest)&&I.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+I.join(", ")+")",description:a??"Host function "+e})}return this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,n){if(e==="PROPS")throw Error("PROPS is a reserved read-only map binding");if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is a reserved read-only binding: the running resumepoint path or null");return this.initialGlobals.set(e,n),this}getGlobal(e){return this.initialGlobals.get(e)}schemaFactory;registerSchemaModuleFactory(e){return this.schemaFactory=e,this}getSchemaModuleFactory(){return this.schemaFactory}moduleSpecResolver;registerModuleSpecResolver(e){return this.moduleSpecResolver=e,this}getModuleSpecResolver(){return this.moduleSpecResolver}registerNativeModule(e){if(!e.nativeNamespace||e.name!=="native:"+e.nativeNamespace||!/^[A-Za-z_]\w*$/.test(e.nativeNamespace))throw Error("Invalid native namespace");if(this.nativeCatalog.has(e.name))throw Error("Duplicate native module "+e.name);return this.nativeCatalog.set(e.name,e),this}nativeCompileOptions(){return new Map([...this.nativeCatalog].map(([e,n])=>[e,{namespace:n.nativeNamespace,members:n.declarations.functions.map(r=>r.name)}]))}registerHostModule(e){return this.hostCatalog.set(e.name,e),this}getHostModule(e){return this.hostCatalog.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}getNativeModules(){return[...this.nativeCatalog.values()]}createChildEngine(e={}){let n=new t({resolveHostModule:this.hostResolver});n.reservedFunctionPrefixes=this.reservedFunctionPrefixes,n.builtinProviderNames=this.builtinProviderNames;for(let[s,i]of this.hostFunctions)n.hasFunction(s)?i.isDefault||n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,readonly:i.readonly,dryControl:i.dryControl,[Be]:i[Be],doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...Qr(i)},!1,i.isContainerMutation):n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,readonly:i.readonly,dryControl:i.dryControl,[Be]:i[Be],doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...Qr(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 Mn.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 kN(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:vy(r,n.file)}}}scanAndCheck(e,n={}){return Mn.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??SN(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=[],g={known:[],closedTables:[],removedGlobals:{}};for(let v of[...[...this.builtinProviders.keys(),...this.hostCatalog.keys()].map(E=>({name:E,line:1,column:1,file:n.file})),...a]){if(u.some(T=>T.name===v.name))continue;let E;try{E=i.schemaModules?.get(v.name)??this.nativeCatalog.get(v.name)??this.builtinProviders.get(v.name)??this.hostCatalog.get(v.name)??(n.resolveHostModule??this.hostResolver)?.(v.name)}catch(T){let k=EN(T);throw new D(`Cannot load module '${v.name}': ${k}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!E)throw new D(`Missing host module '${v.name}'. Install with npm install ${v.name} or set LMSCRIPT_MODULES; for a file use './${v.name}.lms'.`,v.line,v.column,"CHECKER",v.file);let I;try{let T=E.declarations,k=T?.functions,N=T?.globals;Array.isArray(k)&&Array.isArray(N)&&(I={readonlyPrograms:_N(T),functions:k.map(C=>Object.freeze({...C,arity:Cd(C.arity),params:C.params?Object.freeze(C.params.map(Nd)):void 0,doc:fd(C.doc)})),globals:N.map(C=>({...C})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(E.name!==v.name||!I||typeof E.activate!="function")throw new D(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let T of I.functions){let k=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!(E.nativeNamespace?new RegExp("^"+E.nativeNamespace+"\\.[A-Za-z_]\\w*$"):/^[a-zA-Z_]\w*$/).test(T.name)||Object.hasOwn(zi,T.name)&&T.name!=="system"||T.name==="RESUMEPOINT"||!k||!Number.isSafeInteger(k.min)||k.min<0||k.max!==void 0&&(!Number.isSafeInteger(k.max)||k.max<k.min))throw new D(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let N=m.get(T.name);if(T.override===!0&&c.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new D(`Module '${v.name}' cannot override ${N===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${N}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(c.has(T.name)&&!(T.override===!0&&c.get(T.name)?.isDefault))throw new D(`Module function collision: '${T.name}' in module '${v.name}'${N===void 0?"":` is already declared by module '${N}'`}`,v.line,v.column,"CHECKER",v.file);let C=Zt(T.name,T.arity,T.params,T.returnType,T.doc);Oy(T.name,T.readonly,C),c.set(T.name,{arity:C.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:C.nativeParams,returnType:C.returnType??void 0,readonly:T.readonly===!0||void 0,dryControl:Pa(T.name,T.dryControl,C),signature:C,...Qr(T)}),m.set(T.name,v.name)}for(let T of I.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(zi,T.name)||p.has(T.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(T.name)||this.initialGlobals.has(T.name)||n.globals?.includes(T.name))throw new D(`Module global collision or invalid name: '${T.name}'`,v.line,v.column,"CHECKER",v.file);p.add(T.name),this.builtinProviders.has(v.name)&&f.push(T.name)}I.properties&&(g.known=[...g.known,...I.properties.known],g.closedTables=[...g.closedTables??[],...I.properties.closedTables??[]],g.removedGlobals={...g.removedGlobals,...I.properties.removedGlobals}),u.push(E),d.set(E,I)}let h=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],y=new Sd(c,{...n,globals:h,builtinGlobals:f,propertyDeclarations:g,sourcePackages:l}),b=[...r,...y.check(o)];for(let v of b)if(v.message.startsWith("Call to undefined function"))for(let E of this.hostCatalog.values())for(let I of E.declarations.functions)v.message.includes(`'${I.name}'`)&&(v.message+=`; provided by module '${E.name}': add import "${E.name}";`);for(let v of b)for(let E of this.nativeCatalog.values())new RegExp("(?<![\\w.])"+E.nativeNamespace+"\\.").test(v.message)&&!a.some(I=>I.name===E.name)&&(v.message+="; namespace "+E.nativeNamespace+' is not loaded: add import "'+E.name+'" before use');let _={ast:o,diagnosticPaths:s,diagnostics:b,hasConcurrency:y.hasConcurrency,hostModules:u,hostDeclarations:d,usedGlobals:[...y.usedGlobals],usedProperties:y.usedProperties,recoverLabels:[...y.recoverLabels],hasRecover:y.hasRecover,recoverScopedReads:y.recoverScopedReads,recoverScopedWrites:y.recoverScopedWrites};return Kr(_,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:vy(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 Gi(()=>i(a.name)));for(let a of o.functions){let l=Zt(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:Pa(a.name,a.dryControl,l),signature:l,...Qr(a)})}}activationContext(e,n,r,s){return{runReadonlyProgram:(o,a=6e4)=>{let l=Mn.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=en(o);if(!Array.isArray(c)||Array.from({length:c.length},(h,y)=>!Object.hasOwn(c,y)).some(Boolean)||c.some(h=>typeof h!="string"))throw Error("Readonly argv must contain strings");if(!(e.hostDeclarations?.get(r)?.readonlyPrograms??[]).some(h=>h.length<=c.length&&h.every((y,b)=>y===c[b])))throw Error("Command does not match a readonly grant");if(!Number.isSafeInteger(a)||a<0)throw Error("Readonly command timeout must be a non-negative safe integer");Ke(n.signal);let d=se(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 Qa(c,m,p,n.signal,f);let g=Xy(c,m,p,f);return d?.check(),g},noPreflight:n.noPreflight,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:o=>{let a=se(n);if(a){a.recordError(o);return}Fa(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=Zt(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:yN(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:Pa(o.name,o.dryControl,a),signature:a,...Qr(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 Mn.run(void 0,()=>this.dryRunIsolated(e,n))}dryRunIsolated(e,n){zr(n.recoveryProbe);let r=new Ka(n);try{let s=this.runPhase(e,{...n,signal:n.signal?AbortSignal.any([n.signal,r.controller.signal]):r.controller.signal,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?Kr(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Id]: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 Mn.run(void 0,()=>this.dryRunAsyncIsolated(e,n))}async dryRunAsyncIsolated(e,n){zr(n.recoveryProbe);let r=new Ka(n);try{return r.report(await r.wait(this.runPhaseAsync(e,{...n,signal:n.signal?AbortSignal.any([n.signal,r.controller.signal]):r.controller.signal,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?Kr(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Id]: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 Mn.run(void 0,()=>this.runIsolated(e,n))}runIsolated(e,n){if(n.propertyOverlay)try{n={...n,propertyOverlay:Fs(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=[],zr(n.recoveryProbe);let r=n.preparedCheck?Kr(n.preparedCheck,n):this.scanAndCheck(e,n);if(!r.ast||r.diagnostics.some(a=>a.severity==="error"))return{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]};if(n.noPreflight)return this.runPhase(e,{...n,preparedCheck:r});let s=[],i=this.dryRun(e,{...n,[Ad]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[xd]: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 Mn.run(void 0,()=>this.runAsyncIsolated(e,n))}async runAsyncIsolated(e,n){if(n.propertyOverlay)try{n={...n,propertyOverlay:Fs(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=[],zr(n.recoveryProbe);let r=n.preparedCheck?Kr(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);if(!r.ast||r.diagnostics.some(a=>a.severity==="error"))return{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]};if(n.noPreflight)return this.runPhaseAsync(e,{...n,preparedCheck:r});let s=[],i=await this.dryRunAsync(e,{...n,[Ad]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[xd]: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={}){zr(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?Kr(n.preparedCheck,n):this.scanAndCheck(e,n);if(se(n)&&(!r.ast||r.diagnostics.some(d=>d.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};se(n)?.start(),n={...n,propertyStore:n.propertyStore??new Ga(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:se(n)?new Map(en([...this.initialGlobals])):new Map(this.initialGlobals),properties:s};i.functions.get("which")?.[Be]&&i.functions.set("which",{...i.functions.get("which"),fn:d=>dd(d,n.hostContext?.cwd??process.cwd(),se(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=se(n);o&&(o.propertyView=i.globals.get("PROPS"),i.globals.set("PROPS",new Gi(()=>{let d=o.prepareProperties();return Qe(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 Oa(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)?ht(m,f.name):void 0,pd)},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:se(n)&&d!=="set_property"?(...p)=>{let g=d!=="expand"||typeof p[0]=="string"&&ji(p[0]).some(h=>typeof h!="string"&&h.kind==="property")?se(n).prepareProperties(d==="expand"?void 0:p[0]):void 0;return Qe(g)?g.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=Bi(n.resumepoint,n.recoveryProbe);i.readonlyRun=c;let u=Cy(c,n.signal);try{let d=[],m;try{Ke(n.signal);for(let f of r.hostModules??[]){if(this.builtinProviders.has(f.name)||f.nativeNamespace||se(n)){let h,y=()=>{if(h)return h;Ke(n.signal);let b=f.activate(this.activationContext(r,n,f,c));if(Qe(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 h=b,d.push(h),se(n)?.own(h),this.bindModule(f,h,r,i),h};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))),se(n)&&r.hostDeclarations?.get(f)?.properties&&(se(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)),se(n)||r.usedProperties&&r.hostDeclarations?.get(f)?.properties&&y();continue}let g=f.activate(this.activationContext(r,n,f,c));if(Qe(g))throw g.then(h=>h.dispose()).catch(()=>{}),new Error(`Module '${f.name}' requires runAsync for activation`);d.push(g),this.bindModule(f,g,r,i),Ke(n.signal)}m=this.executeSync(e,n,r,i,c),n.signal?.aborted&&(m={...m,success:!1,diagnostics:m.diagnostics.some(f=>f.severity==="error"&&f.message==="Execution aborted")?m.diagnostics:[...m.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(f){xt(c,f),m={...this.moduleFailure(f,r,n),errors:[...c.errors]}}se(n)?.capture(m);let p=c.errors.length;this.collectModuleErrors(d,m,n.recoveryProbe!==void 0),se(n)?.capture(m);for(let f of d.reverse())try{let g=se(n)?se(n).dispose(f):f.dispose();if(Qe(g))throw g.catch(()=>{}),new Error("Async disposal requires runAsync");se(n)?.check()}catch(g){let h=se(n);h&&!h.truncation&&(h.failure??={site:h.lastSite,message:g instanceof Error?g.message:String(g),untrusted:h.tainted}),this.cleanupWarning(g,m)}return m.errors=[...m.errors??[],...c.errors.slice(p)],this.lastRecordedErrors=[...m.errors],m}finally{c.finished=!0,u()}}async runPhaseAsync(e,n={}){zr(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?Kr(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(se(n)&&(!s.ast||s.diagnostics.some(m=>m.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};se(n)?.start(),n={...n,propertyStore:n.propertyStore??new Ga(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:se(n)?new Map(en([...this.initialGlobals])):new Map(this.initialGlobals),properties:i};o.functions.get("which")?.[Be]&&o.functions.set("which",{...o.functions.get("which"),fn:m=>dd(m,n.hostContext?.cwd??process.cwd(),se(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=se(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new Gi(()=>{let m=a.prepareProperties();return Qe(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 Oa(m,g=>g.kind==="property"?i.get(g.key):g.kind==="argument"?Array.isArray(f)&&Object.hasOwn(f,g.index)?f[g.index]:void 0:Object.hasOwn(p,g.name)?ht(p,g.name):void 0,pd)},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:se(n)&&m!=="set_property"?(...f)=>{let h=m!=="expand"||typeof f[0]=="string"&&ji(f[0]).some(y=>typeof y!="string"&&y.kind==="property")?se(n).prepareProperties(m==="expand"?void 0:f[0]):void 0;return Qe(h)?h.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=Bi(n.resumepoint,n.recoveryProbe);o.readonlyRun=u;let d=Cy(u,n.signal);try{let m=[],p;try{Ke(n.signal);for(let g of s.hostModules??[]){if(this.builtinProviders.has(g.name)||g.nativeNamespace||se(n)){let y,b,_=()=>y??=Promise.resolve().then(async()=>{Ke(n.signal);let v=await g.activate(this.activationContext(s,n,g,u));if(!v||typeof v.dispose!="function")throw new Error(`Module '${g.name}' did not return a disposable`);if(se(n)?.sealed){try{await v.dispose()}catch{}throw new Gt("Dry pass finished")}return b=v,m.push(v),se(n)?.own(v),this.bindModule(g,v,s,o),Ke(n.signal),v});g.nativeNamespace&&(o.nativeImports??=new Map,o.nativeImports.set(g.name,_)),this.installBuiltinStubs(g,s,o,v=>async(...E)=>{let I=await _();return se(n)?.check(),o.functions.get(v).fn(...E)},async v=>(await _(),o.globals.get(v))),se(n)&&s.hostDeclarations?.get(g)?.properties&&(se(n).propertyLoads.push(_),i.addSource(g.name,()=>{if(!b?.loadProperties)throw Error("Provider properties unavailable");return b.loadProperties()},s.hostDeclarations.get(g).properties.known)),se(n)||s.usedProperties&&s.hostDeclarations?.get(g)?.properties&&await _();continue}let h=await g.activate(this.activationContext(s,n,g,u));m.push(h),this.bindModule(g,h,s,o),Ke(n.signal)}p=await this.executeAsync(e,n,s,o,u),n.signal?.aborted&&(p={...p,success:!1,diagnostics:p.diagnostics.some(g=>g.severity==="error"&&g.message==="Execution aborted")?p.diagnostics:[...p.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(g){xt(u,g),p={...this.moduleFailure(g,s,n),errors:[...u.errors]}}se(n)?.capture(p);let f=u.errors.length;this.collectModuleErrors(m,p,n.recoveryProbe!==void 0),se(n)?.capture(p);for(let g of m.reverse())try{let h=se(n)?se(n).dispose(g):g.dispose();se(n)?await se(n).wait(h):await h}catch(h){let y=se(n);y&&!y.truncation&&(y.failure??={site:y.lastSite,message:h instanceof Error?h.message:String(h),untrusted:y.tainted}),this.cleanupWarning(h,p)}return p.errors=[...p.errors??[],...u.errors.slice(f)],this.lastRecordedErrors=[...p.errors],p}finally{u.finished=!0,d()}}executeSync(e,n,r,s,i){let o=[],{ast:a,diagnostics:l,hasConcurrency:c}=r;if(l.filter(f=>f.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??Bi(n.resumepoint,n.recoveryProbe),m,p;try{m=new za(s.functions,h=>{o.push(h),n.stdout?.(h)},!1,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,se(n),n.noPreflight,s.nativeImports),m.childEngineFactory=h=>this.createChildEngine(h),m.compileOptions=n,m.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},m.warningDiagnostics=l,m.abortSignal=n.signal,m.recoverScopedReads=r.recoverScopedReads??new WeakMap,m.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,p=this.trackResourceRun(m.resources);let f=m.evaluateProgram(a);this.outputLogs=[...o];let g=m.getRecordedErrors();return this.lastRecordedErrors=g,{success:!0,value:f,diagnostics:l,output:o,errors:g,resourceRun:p}}catch(f){xt(d,f);let g=[...d.errors];if(this.lastRecordedErrors=g,f instanceof At||f?.name==="LMScriptExit"||f?.isControlFlow){this.outputLogs=[...o];let _=typeof f.exitCode=="number"?f.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:l,output:o,errors:g,resourceRun:p}}let h=f instanceof D?f.line:1,y=f instanceof D?f.column:1,b=f instanceof D&&f.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...l,{message:f?.message||String(f),line:h,column:y,severity:"error",file:b}],output:o,errors:g,resourceRun:p}}}async executeAsync(e,n,r,s,i){let o=[],{ast:a}=r,l=[...r.diagnostics];if(l.filter(p=>p.severity==="error").length>0||!a)return this.outputLogs=o,this.lastRecordedErrors=[],{success:!1,diagnostics:l,output:o,errors:[]};let u=i??Bi(n.resumepoint,n.recoveryProbe),d,m;try{d=new za(s.functions,g=>{o.push(g),n.stdout?.(g)},!0,s.globals,n.stderr,this.promptHumanConfig,u,n.hostContext?.platform??n.platform??process.platform,se(n),n.noPreflight,s.nativeImports),d.childEngineFactory=g=>this.createChildEngine(g),d.compileOptions=n,d.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},d.warningDiagnostics=l,d.abortSignal=n.signal,d.recoverScopedReads=r.recoverScopedReads??new WeakMap,d.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,m=this.trackResourceRun(d.resources);let p=await d.evaluateProgramAsync(a);this.outputLogs=[...o];let f=d.getRecordedErrors();return this.lastRecordedErrors=f,{success:!0,value:p,diagnostics:l,output:o,errors:f,resourceRun:m}}catch(p){xt(u,p);let f=[...u.errors];if(this.lastRecordedErrors=f,p instanceof At||p?.name==="LMScriptExit"||p?.isControlFlow){this.outputLogs=[...o];let b=typeof p.exitCode=="number"?p.exitCode:0;return{success:b===0,value:b,exitCode:b,diagnostics:l,output:o,errors:f,resourceRun:m}}let g=p instanceof D?p.line:1,h=p instanceof D?p.column:1,y=p instanceof D&&p.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...l,{message:p?.message||String(p),line:g,column:h,severity:"error",file:y}],output:o,errors:f,resourceRun:m}}}lastRecordedErrors=[];resourceRuns=new Map;trackResourceRun(e){for(this.resourceRuns.set(e.token,e);this.resourceRuns.size>64;)this.resourceRuns.delete(this.resourceRuns.keys().next().value);return e.token}terminateResourceRuns(){for(let e of this.resourceRuns.values())e.terminate()}inspectResources(e){return this.resourceRuns.get(e)?.snapshot()??[]}getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getFunctionMetadata(e){let n=this.hostFunctions.get(e);return n?Object.freeze({arity:n.arity,publicArity:n.signature?.publicArity,description:n.description,params:n.signature?.nativeParams??n.params,publicParams:n.signature?.publicParams??n.params,returnType:n.signature?.returnType??r_(n.returnType),readonly:n.readonly,dryControl:n.dryControl,signature:n.signature}):void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};yd=re.basename(Pd(import.meta.url));(yd==="lmscript.ts"||yd==="lmscript.js"||yd==="lmscript")&&process.argv[1]&&j.existsSync(process.argv[1])&&j.realpathSync(Pd(import.meta.url))===j.realpathSync(re.resolve(process.argv[1]))&&UN()});function HN(t,e,n){let r=Zt(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 BN(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 Wd(t){let e=Zt(t.name,t.arity,t.params,t.returnType,t.doc),n=e.dryrunIndex===void 0&&t.doc?.signature?t.doc.signature:HN(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 WN(t,e){let n=t.getFunctionMetadata(e);if(n)return Wd({name:e,arity:n.arity,params:n.params,returnType:n.returnType??void 0,doc:t.getFunctionDoc(e)})}function d_(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,WN(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,Wd({...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.
|
|
415
|
+
`):console.error(`error: ${n}`),n},{min:1},"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("http_get",e=>Wy(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 zy(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?Za(e):Ky(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)=>dN(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(Yr(e)):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(Yr(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(Yr(e)):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("get",(e,n,r=null)=>{let s=Ui(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=Ui(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=Ui(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=Ui(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=Ui(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",Dd,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];(ht(i,a)==null||typeof ht(i,a)!="object")&&et(i,a,{}),i=ht(i,a)}return s.length>0&&et(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=>ht(r,n)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,n,r)=>Array.isArray(e)?e.filter(s=>s!=null&&ht(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&&ht(i,n)===r);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,n)=>({...Yr(e),...Yr(n)}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,n)=>(e&&typeof e=="object"&&delete e[n],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let n=e.map(r=>typeof r=="object"?JSON.stringify(r):String(r)).join(" ");return this.outputLogs.push(n),n},{min:0},"Prints line to output log",!0),this.registerFunction("split",(e,n)=>String(e).split(n),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let n=e.split(/\r?\n/);for(let r=n.length-1;r>=0;r--){let s=n[r].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("parse_file_blocks",e=>zC(e),1,"Parses === FILE: path === ... === END === blocks into [{path, content}]"),this.registerFunction("format_file_blocks",e=>YC(e),1,"Formats [{path, content}] as file blocks; inverse of parse_file_blocks"),this.registerFunction("write_files",(e,n,r)=>nN(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)=>oN(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=>cN(e),1,"Parses key: value lines of the last paragraph into a map"),this.registerFunction("split_command",e=>uN(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 lr,1,"Checks if value is a first-class function reference"),this.registerFunction("cmd_render",(e,n)=>Fd(e,n),{min:1,max:2},"Renders argv as posix, windows or powershell text; execution never uses rendered text",!0),this.registerFunction("sprintf",(e,...n)=>ja(e,n),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; use format() for {} brace syntax"),this.registerFunction("printf",(e,...n)=>ja(e,n,"printf"),{min:1},"Formats and prints %s, %d, %f and %% using the sprintf width and precision rules",!0),this.registerFunction("format",(e,...n)=>{let r=String(e),s=n.length===1&&typeof n[0]=="object"&&n[0]!==null&&!Array.isArray(n[0])?n[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<r.length;){let c=r[l];if(c==="{"&&r[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&r[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=r.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=r.slice(l+1,u);if(d==="")o+=i<n.length?a(n[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<n.length?a(n[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("regex_test",(e,n,r="")=>qi(n,r).test(String(e)),{min:2,max:3},"Tests a JavaScript regular expression against text"),this.registerFunction("regex_match",pN,{min:2,max:3},"Returns first full match and captures; g retains first-match shape, y is rejected"),this.registerFunction("regex_find_all",fN,{min:2,max:3},"Returns capture arrays with Unicode-aware zero-width progress; y is rejected"),this.registerFunction("regex_replace",(e,n,r,s="")=>String(e).replace(qi(n,s),r),{min:3,max:4},"Replaces matches using JavaScript regex replacement semantics"),this.registerFunction("split_regex",(e,n,r="")=>String(e).split(qi(n,r)),{min:2,max:3},"Splits text at regular expression matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("range",(e,n,r=1)=>{let s=n===void 0?0:e,i=n===void 0?e:n,o=[];if(r>0)for(let a=s;a<i;a+=r)o.push(a);else if(r<0)for(let a=s;a>i;a+=r)o.push(a);return o},{min:1,max:3},"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...n)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let n=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...n)},{min:0},"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,n)=>Math.pow(e,n),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("sha256",e=>{if(typeof e!="string")throw new Error("sha256: expected a string");return XC("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)=>$N(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=>pd(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 lr?"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=fd(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}:{},g=typeof s=="object"?s.params?.map(Nd):void 0,h=typeof s=="object"?s.returnType:void 0,y=Zt(e,r,g,h,u);Oy(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:h,readonly:b,...typeof s=="object"&&s[Be]?{[Be]:s[Be]}:{},dryControl:Pa(e,typeof s=="object"?s.dryControl:void 0,y),signature:y,...f}),u)this.functionDocs.set(e,{...u,module:u.module??m});else{let _=y.publicArity,v=typeof _=="number"?_:_?.min??0,E=typeof _=="number"?_:_?.max,I=y.publicParams.length?y.publicParams.map(T=>T.optional?`[${T.name}]`:T.rest?`...${T.name}`:T.name):Array.from({length:E??v},(T,k)=>(k>=v?"[":"")+"arg"+(k+1)+(k>=v?"]":""));E===void 0&&!y.publicParams.some(T=>T.rest)&&I.push("...args"),this.functionDocs.set(e,{name:e,module:m,category:"Uncategorized",signature:e+"("+I.join(", ")+")",description:a??"Host function "+e})}return this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,n){if(e==="PROPS")throw Error("PROPS is a reserved read-only map binding");if(e==="RESUMEPOINT")throw Error("RESUMEPOINT is a reserved read-only binding: the running resumepoint path or null");return this.initialGlobals.set(e,n),this}getGlobal(e){return this.initialGlobals.get(e)}schemaFactory;registerSchemaModuleFactory(e){return this.schemaFactory=e,this}getSchemaModuleFactory(){return this.schemaFactory}moduleSpecResolver;registerModuleSpecResolver(e){return this.moduleSpecResolver=e,this}getModuleSpecResolver(){return this.moduleSpecResolver}registerNativeModule(e){if(!e.nativeNamespace||e.name!=="native:"+e.nativeNamespace||!/^[A-Za-z_]\w*$/.test(e.nativeNamespace))throw Error("Invalid native namespace");if(this.nativeCatalog.has(e.name))throw Error("Duplicate native module "+e.name);return this.nativeCatalog.set(e.name,e),this}nativeCompileOptions(){return new Map([...this.nativeCatalog].map(([e,n])=>[e,{namespace:n.nativeNamespace,members:n.declarations.functions.map(r=>r.name)}]))}registerHostModule(e){return this.hostCatalog.set(e.name,e),this}getHostModule(e){return this.hostCatalog.get(e)}registerBuiltinProvider(e){if(this.builtinProviders.has(e.name))throw new Error(`Duplicate built-in provider '${e.name}'`);return this.builtinProviders.set(e.name,e),this}getBuiltinProviders(){return[...this.builtinProviders.values()]}getNativeModules(){return[...this.nativeCatalog.values()]}createChildEngine(e={}){let n=new t({resolveHostModule:this.hostResolver});n.reservedFunctionPrefixes=this.reservedFunctionPrefixes,n.builtinProviderNames=this.builtinProviderNames;for(let[s,i]of this.hostFunctions)n.hasFunction(s)?i.isDefault||n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,readonly:i.readonly,dryControl:i.dryControl,[Be]:i[Be],doc:i.doc,allowOverwrite:!0,isContainerMutation:i.isContainerMutation,...Qr(i)},!1,i.isContainerMutation):n.registerFunction(s,i.fn,i.signature?.nativeArity??i.arity,{description:i.description,params:i.signature?.nativeParams??i.params,returnType:i.returnType,readonly:i.readonly,dryControl:i.dryControl,[Be]:i[Be],doc:i.doc,isDefault:i.isDefault,isContainerMutation:i.isContainerMutation,...Qr(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 Mn.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 kN(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:vy(r,n.file)}}}scanAndCheck(e,n={}){return Mn.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??SN(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=[],g={known:[],closedTables:[],removedGlobals:{}};for(let v of[...[...this.builtinProviders.keys(),...this.hostCatalog.keys()].map(E=>({name:E,line:1,column:1,file:n.file})),...a]){if(u.some(T=>T.name===v.name))continue;let E;try{E=i.schemaModules?.get(v.name)??this.nativeCatalog.get(v.name)??this.builtinProviders.get(v.name)??this.hostCatalog.get(v.name)??(n.resolveHostModule??this.hostResolver)?.(v.name)}catch(T){let k=EN(T);throw new D(`Cannot load module '${v.name}': ${k}. Install with npm install ${v.name} or set LMSCRIPT_MODULES.`,v.line,v.column,"CHECKER",v.file)}if(!E)throw new D(`Missing host module '${v.name}'. Install with npm install ${v.name} or set LMSCRIPT_MODULES; for a file use './${v.name}.lms'.`,v.line,v.column,"CHECKER",v.file);let I;try{let T=E.declarations,k=T?.functions,N=T?.globals;Array.isArray(k)&&Array.isArray(N)&&(I={readonlyPrograms:_N(T),functions:k.map(C=>Object.freeze({...C,arity:Cd(C.arity),params:C.params?Object.freeze(C.params.map(Nd)):void 0,doc:fd(C.doc)})),globals:N.map(C=>({...C})),properties:T.properties?{known:[...T.properties.known],closedTables:[...T.properties.closedTables??[]],removedGlobals:{...T.properties.removedGlobals}}:void 0})}catch{}if(E.name!==v.name||!I||typeof E.activate!="function")throw new D(`Invalid declarations for module '${v.name}'`,v.line,v.column,"CHECKER",v.file);for(let T of I.functions){let k=typeof T.arity=="number"?{min:T.arity,max:T.arity}:T.arity;if(typeof T.name!="string"||!(E.nativeNamespace?new RegExp("^"+E.nativeNamespace+"\\.[A-Za-z_]\\w*$"):/^[a-zA-Z_]\w*$/).test(T.name)||Object.hasOwn(zi,T.name)&&T.name!=="system"||T.name==="RESUMEPOINT"||!k||!Number.isSafeInteger(k.min)||k.min<0||k.max!==void 0&&(!Number.isSafeInteger(k.max)||k.max<k.min))throw new D(`Invalid function declaration in module '${v.name}'`,v.line,v.column,"CHECKER",v.file);let N=m.get(T.name);if(T.override===!0&&c.has(T.name)&&!["prompt_human","run_script"].includes(T.name))throw new D(`Module '${v.name}' cannot override ${N===void 0?`core function '${T.name}'`:`function '${T.name}' declared by module '${N}'`}; permitted overrides: prompt_human, run_script`,v.line,v.column,"CHECKER",v.file);if(c.has(T.name)&&!(T.override===!0&&c.get(T.name)?.isDefault))throw new D(`Module function collision: '${T.name}' in module '${v.name}'${N===void 0?"":` is already declared by module '${N}'`}`,v.line,v.column,"CHECKER",v.file);let C=Zt(T.name,T.arity,T.params,T.returnType,T.doc);Oy(T.name,T.readonly,C),c.set(T.name,{arity:C.nativeArity,fn:()=>{throw new Error("Module not activated")},doc:T.doc,params:C.nativeParams,returnType:C.returnType??void 0,readonly:T.readonly===!0||void 0,dryControl:Pa(T.name,T.dryControl,C),signature:C,...Qr(T)}),m.set(T.name,v.name)}for(let T of I.globals){if(!/^[a-zA-Z_]\w*$/.test(T.name)||Object.hasOwn(zi,T.name)||p.has(T.name)||["PROPS","Directory","NonInteractive","RESUMEPOINT"].includes(T.name)||this.initialGlobals.has(T.name)||n.globals?.includes(T.name))throw new D(`Module global collision or invalid name: '${T.name}'`,v.line,v.column,"CHECKER",v.file);p.add(T.name),this.builtinProviders.has(v.name)&&f.push(T.name)}I.properties&&(g.known=[...g.known,...I.properties.known],g.closedTables=[...g.closedTables??[],...I.properties.closedTables??[]],g.removedGlobals={...g.removedGlobals,...I.properties.removedGlobals}),u.push(E),d.set(E,I)}let h=[...this.initialGlobals.keys(),...n.globals||[],...p,"PROPS","Directory","NonInteractive","RESUMEPOINT"],y=new Sd(c,{...n,globals:h,builtinGlobals:f,propertyDeclarations:g,sourcePackages:l}),b=[...r,...y.check(o)];for(let v of b)if(v.message.startsWith("Call to undefined function"))for(let E of this.hostCatalog.values())for(let I of E.declarations.functions)v.message.includes(`'${I.name}'`)&&(v.message+=`; provided by module '${E.name}': add import "${E.name}";`);for(let v of b)for(let E of this.nativeCatalog.values())new RegExp("(?<![\\w.])"+E.nativeNamespace+"\\.").test(v.message)&&!a.some(I=>I.name===E.name)&&(v.message+="; namespace "+E.nativeNamespace+' is not loaded: add import "'+E.name+'" before use');let _={ast:o,diagnosticPaths:s,diagnostics:b,hasConcurrency:y.hasConcurrency,hostModules:u,hostDeclarations:d,usedGlobals:[...y.usedGlobals],usedProperties:y.usedProperties,recoverLabels:[...y.recoverLabels],hasRecover:y.hasRecover,recoverScopedReads:y.recoverScopedReads,recoverScopedWrites:y.recoverScopedWrites};return Kr(_,n)}catch(i){return{ast:null,hasConcurrency:!1,diagnostics:vy(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 Gi(()=>i(a.name)));for(let a of o.functions){let l=Zt(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:Pa(a.name,a.dryControl,l),signature:l,...Qr(a)})}}activationContext(e,n,r,s){return{runReadonlyProgram:(o,a=6e4)=>{let l=Mn.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=en(o);if(!Array.isArray(c)||Array.from({length:c.length},(h,y)=>!Object.hasOwn(c,y)).some(Boolean)||c.some(h=>typeof h!="string"))throw Error("Readonly argv must contain strings");if(!(e.hostDeclarations?.get(r)?.readonlyPrograms??[]).some(h=>h.length<=c.length&&h.every((y,b)=>y===c[b])))throw Error("Command does not match a readonly grant");if(!Number.isSafeInteger(a)||a<0)throw Error("Readonly command timeout must be a non-negative safe integer");Ke(n.signal);let d=se(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 Qa(c,m,p,n.signal,f);let g=Xy(c,m,p,f);return d?.check(),g},noPreflight:n.noPreflight,platform:n.hostContext?.platform??n.platform??process.platform,reportRecordedError:o=>{let a=se(n);if(a){a.recordError(o);return}Fa(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=Zt(o.name,o.arity,o.params,o.returnType,o.doc);s.functions.set(o.name,{fn:yN(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:Pa(o.name,o.dryControl,a),signature:a,...Qr(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 Mn.run(void 0,()=>this.dryRunIsolated(e,n))}dryRunIsolated(e,n){zr(n.recoveryProbe);let r=new Ka(n);try{let s=this.runPhase(e,{...n,signal:n.signal?AbortSignal.any([n.signal,r.controller.signal]):r.controller.signal,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?Kr(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Id]: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 Mn.run(void 0,()=>this.dryRunAsyncIsolated(e,n))}async dryRunAsyncIsolated(e,n){zr(n.recoveryProbe);let r=new Ka(n);try{return r.report(await r.wait(this.runPhaseAsync(e,{...n,signal:n.signal?AbortSignal.any([n.signal,r.controller.signal]):r.controller.signal,resumepoint:void 0,recoveryProbe:void 0,preparedCheck:n.preparedCheck?Kr(n.preparedCheck,{...n,resumepoint:void 0}):void 0,propertyStore:n.propertyStore?.fork(),stdout:void 0,stderr:void 0,[Id]: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 Mn.run(void 0,()=>this.runIsolated(e,n))}runIsolated(e,n){if(n.propertyOverlay)try{n={...n,propertyOverlay:Fs(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=[],zr(n.recoveryProbe);let r=n.preparedCheck?Kr(n.preparedCheck,n):this.scanAndCheck(e,n);if(!r.ast||r.diagnostics.some(a=>a.severity==="error"))return{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]};if(n.noPreflight)return this.runPhase(e,{...n,preparedCheck:r});let s=[],i=this.dryRun(e,{...n,[Ad]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[xd]: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 Mn.run(void 0,()=>this.runAsyncIsolated(e,n))}async runAsyncIsolated(e,n){if(n.propertyOverlay)try{n={...n,propertyOverlay:Fs(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=[],zr(n.recoveryProbe);let r=n.preparedCheck?Kr(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);if(!r.ast||r.diagnostics.some(a=>a.severity==="error"))return{success:!1,exitCode:2,diagnostics:r.diagnostics,output:[],errors:[]};if(n.noPreflight)return this.runPhaseAsync(e,{...n,preparedCheck:r});let s=[],i=await this.dryRunAsync(e,{...n,[Ad]:s,dryrunTimeoutMs:n.dryrunTimeoutMs??100,[xd]: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={}){zr(n.recoveryProbe),this.outputLogs=[],this.lastRecordedErrors=[];let r=n.preparedCheck?Kr(n.preparedCheck,n):this.scanAndCheck(e,n);if(se(n)&&(!r.ast||r.diagnostics.some(d=>d.severity==="error")))return{success:!1,diagnostics:r.diagnostics,output:[],errors:[]};se(n)?.start(),n={...n,propertyStore:n.propertyStore??new Ga(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:se(n)?new Map(en([...this.initialGlobals])):new Map(this.initialGlobals),properties:s};i.functions.get("which")?.[Be]&&i.functions.set("which",{...i.functions.get("which"),fn:d=>dd(d,n.hostContext?.cwd??process.cwd(),se(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=se(n);o&&(o.propertyView=i.globals.get("PROPS"),i.globals.set("PROPS",new Gi(()=>{let d=o.prepareProperties();return Ze(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 Oa(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)?ht(m,f.name):void 0,pd)},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:se(n)&&d!=="set_property"?(...p)=>{let g=d!=="expand"||typeof p[0]=="string"&&ji(p[0]).some(h=>typeof h!="string"&&h.kind==="property")?se(n).prepareProperties(d==="expand"?void 0:p[0]):void 0;return Ze(g)?g.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=Bi(n.resumepoint,n.recoveryProbe);i.readonlyRun=c;let u=Cy(c,n.signal);try{let d=[],m;try{Ke(n.signal);for(let f of r.hostModules??[]){if(this.builtinProviders.has(f.name)||f.nativeNamespace||se(n)){let h,y=()=>{if(h)return h;Ke(n.signal);let b=f.activate(this.activationContext(r,n,f,c));if(Ze(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 h=b,d.push(h),se(n)?.own(h),this.bindModule(f,h,r,i),h};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))),se(n)&&r.hostDeclarations?.get(f)?.properties&&(se(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)),se(n)||r.usedProperties&&r.hostDeclarations?.get(f)?.properties&&y();continue}let g=f.activate(this.activationContext(r,n,f,c));if(Ze(g))throw g.then(h=>h.dispose()).catch(()=>{}),new Error(`Module '${f.name}' requires runAsync for activation`);d.push(g),this.bindModule(f,g,r,i),Ke(n.signal)}m=this.executeSync(e,n,r,i,c),n.signal?.aborted&&(m={...m,success:!1,diagnostics:m.diagnostics.some(f=>f.severity==="error"&&f.message==="Execution aborted")?m.diagnostics:[...m.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(f){xt(c,f),m={...this.moduleFailure(f,r,n),errors:[...c.errors]}}se(n)?.capture(m);let p=c.errors.length;this.collectModuleErrors(d,m,n.recoveryProbe!==void 0),se(n)?.capture(m);for(let f of d.reverse())try{let g=se(n)?se(n).dispose(f):f.dispose();if(Ze(g))throw g.catch(()=>{}),new Error("Async disposal requires runAsync");se(n)?.check()}catch(g){let h=se(n);h&&!h.truncation&&(h.failure??={site:h.lastSite,message:g instanceof Error?g.message:String(g),untrusted:h.tainted}),this.cleanupWarning(g,m)}return m.errors=[...m.errors??[],...c.errors.slice(p)],this.lastRecordedErrors=[...m.errors],m}finally{c.finished=!0,u()}}async runPhaseAsync(e,n={}){zr(n.recoveryProbe),n={...n,importCache:n.importCache??new Map};let r=n.preparedCheck?Kr(n.preparedCheck,n):await this.scanAndCheckAsync(e,n);this.outputLogs=[],this.lastRecordedErrors=[];let s=r;if(se(n)&&(!s.ast||s.diagnostics.some(m=>m.severity==="error")))return{success:!1,diagnostics:s.diagnostics,output:[],errors:[]};se(n)?.start(),n={...n,propertyStore:n.propertyStore??new Ga(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:se(n)?new Map(en([...this.initialGlobals])):new Map(this.initialGlobals),properties:i};o.functions.get("which")?.[Be]&&o.functions.set("which",{...o.functions.get("which"),fn:m=>dd(m,n.hostContext?.cwd??process.cwd(),se(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=se(n);a&&(a.propertyView=o.globals.get("PROPS"),o.globals.set("PROPS",new Gi(()=>{let m=a.prepareProperties();return Ze(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 Oa(m,g=>g.kind==="property"?i.get(g.key):g.kind==="argument"?Array.isArray(f)&&Object.hasOwn(f,g.index)?f[g.index]:void 0:Object.hasOwn(p,g.name)?ht(p,g.name):void 0,pd)},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:se(n)&&m!=="set_property"?(...f)=>{let h=m!=="expand"||typeof f[0]=="string"&&ji(f[0]).some(y=>typeof y!="string"&&y.kind==="property")?se(n).prepareProperties(m==="expand"?void 0:f[0]):void 0;return Ze(h)?h.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=Bi(n.resumepoint,n.recoveryProbe);o.readonlyRun=u;let d=Cy(u,n.signal);try{let m=[],p;try{Ke(n.signal);for(let g of s.hostModules??[]){if(this.builtinProviders.has(g.name)||g.nativeNamespace||se(n)){let y,b,_=()=>y??=Promise.resolve().then(async()=>{Ke(n.signal);let v=await g.activate(this.activationContext(s,n,g,u));if(!v||typeof v.dispose!="function")throw new Error(`Module '${g.name}' did not return a disposable`);if(se(n)?.sealed){try{await v.dispose()}catch{}throw new Gt("Dry pass finished")}return b=v,m.push(v),se(n)?.own(v),this.bindModule(g,v,s,o),Ke(n.signal),v});g.nativeNamespace&&(o.nativeImports??=new Map,o.nativeImports.set(g.name,_)),this.installBuiltinStubs(g,s,o,v=>async(...E)=>{let I=await _();return se(n)?.check(),o.functions.get(v).fn(...E)},async v=>(await _(),o.globals.get(v))),se(n)&&s.hostDeclarations?.get(g)?.properties&&(se(n).propertyLoads.push(_),i.addSource(g.name,()=>{if(!b?.loadProperties)throw Error("Provider properties unavailable");return b.loadProperties()},s.hostDeclarations.get(g).properties.known)),se(n)||s.usedProperties&&s.hostDeclarations?.get(g)?.properties&&await _();continue}let h=await g.activate(this.activationContext(s,n,g,u));m.push(h),this.bindModule(g,h,s,o),Ke(n.signal)}p=await this.executeAsync(e,n,s,o,u),n.signal?.aborted&&(p={...p,success:!1,diagnostics:p.diagnostics.some(g=>g.severity==="error"&&g.message==="Execution aborted")?p.diagnostics:[...p.diagnostics,{severity:"error",message:"Execution aborted",line:1,column:1}]})}catch(g){xt(u,g),p={...this.moduleFailure(g,s,n),errors:[...u.errors]}}se(n)?.capture(p);let f=u.errors.length;this.collectModuleErrors(m,p,n.recoveryProbe!==void 0),se(n)?.capture(p);for(let g of m.reverse())try{let h=se(n)?se(n).dispose(g):g.dispose();se(n)?await se(n).wait(h):await h}catch(h){let y=se(n);y&&!y.truncation&&(y.failure??={site:y.lastSite,message:h instanceof Error?h.message:String(h),untrusted:y.tainted}),this.cleanupWarning(h,p)}return p.errors=[...p.errors??[],...u.errors.slice(f)],this.lastRecordedErrors=[...p.errors],p}finally{u.finished=!0,d()}}executeSync(e,n,r,s,i){let o=[],{ast:a,diagnostics:l,hasConcurrency:c}=r;if(l.filter(f=>f.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??Bi(n.resumepoint,n.recoveryProbe),m,p;try{m=new za(s.functions,h=>{o.push(h),n.stdout?.(h)},!1,s.globals,n.stderr,this.promptHumanConfig,d,n.hostContext?.platform??n.platform??process.platform,se(n),n.noPreflight,s.nativeImports),m.childEngineFactory=h=>this.createChildEngine(h),m.compileOptions=n,m.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},m.warningDiagnostics=l,m.abortSignal=n.signal,m.recoverScopedReads=r.recoverScopedReads??new WeakMap,m.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,p=this.trackResourceRun(m.resources);let f=m.evaluateProgram(a);this.outputLogs=[...o];let g=m.getRecordedErrors();return this.lastRecordedErrors=g,{success:!0,value:f,diagnostics:l,output:o,errors:g,resourceRun:p}}catch(f){xt(d,f);let g=[...d.errors];if(this.lastRecordedErrors=g,f instanceof At||f?.name==="LMScriptExit"||f?.isControlFlow){this.outputLogs=[...o];let _=typeof f.exitCode=="number"?f.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:l,output:o,errors:g,resourceRun:p}}let h=f instanceof D?f.line:1,y=f instanceof D?f.column:1,b=f instanceof D&&f.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...l,{message:f?.message||String(f),line:h,column:y,severity:"error",file:b}],output:o,errors:g,resourceRun:p}}}async executeAsync(e,n,r,s,i){let o=[],{ast:a}=r,l=[...r.diagnostics];if(l.filter(p=>p.severity==="error").length>0||!a)return this.outputLogs=o,this.lastRecordedErrors=[],{success:!1,diagnostics:l,output:o,errors:[]};let u=i??Bi(n.resumepoint,n.recoveryProbe),d,m;try{d=new za(s.functions,g=>{o.push(g),n.stdout?.(g)},!0,s.globals,n.stderr,this.promptHumanConfig,u,n.hostContext?.platform??n.platform??process.platform,se(n),n.noPreflight,s.nativeImports),d.childEngineFactory=g=>this.createChildEngine(g),d.compileOptions=n,d.processContext={cwd:n.hostContext?.cwd??process.cwd(),env:n.hostContext?.env??process.env},d.warningDiagnostics=l,d.abortSignal=n.signal,d.recoverScopedReads=r.recoverScopedReads??new WeakMap,d.recoverScopedWrites=r.recoverScopedWrites??new WeakMap,m=this.trackResourceRun(d.resources);let p=await d.evaluateProgramAsync(a);this.outputLogs=[...o];let f=d.getRecordedErrors();return this.lastRecordedErrors=f,{success:!0,value:p,diagnostics:l,output:o,errors:f,resourceRun:m}}catch(p){xt(u,p);let f=[...u.errors];if(this.lastRecordedErrors=f,p instanceof At||p?.name==="LMScriptExit"||p?.isControlFlow){this.outputLogs=[...o];let b=typeof p.exitCode=="number"?p.exitCode:0;return{success:b===0,value:b,exitCode:b,diagnostics:l,output:o,errors:f,resourceRun:m}}let g=p instanceof D?p.line:1,h=p instanceof D?p.column:1,y=p instanceof D&&p.file||n.file;return this.outputLogs=[...o],{success:!1,diagnostics:[...l,{message:p?.message||String(p),line:g,column:h,severity:"error",file:y}],output:o,errors:f,resourceRun:m}}}lastRecordedErrors=[];resourceRuns=new Map;trackResourceRun(e){for(this.resourceRuns.set(e.token,e);this.resourceRuns.size>64;)this.resourceRuns.delete(this.resourceRuns.keys().next().value);return e.token}terminateResourceRuns(){for(let e of this.resourceRuns.values())e.terminate()}inspectResources(e){return this.resourceRuns.get(e)?.snapshot()??[]}getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getFunctionMetadata(e){let n=this.hostFunctions.get(e);return n?Object.freeze({arity:n.arity,publicArity:n.signature?.publicArity,description:n.description,params:n.signature?.nativeParams??n.params,publicParams:n.signature?.publicParams??n.params,returnType:n.signature?.returnType??r_(n.returnType),readonly:n.readonly,dryControl:n.dryControl,signature:n.signature}):void 0}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};yd=re.basename(Pd(import.meta.url));(yd==="lmscript.ts"||yd==="lmscript.js"||yd==="lmscript")&&process.argv[1]&&j.existsSync(process.argv[1])&&j.realpathSync(Pd(import.meta.url))===j.realpathSync(re.resolve(process.argv[1]))&&UN()});function HN(t,e,n){let r=Zt(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 BN(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 Wd(t){let e=Zt(t.name,t.arity,t.params,t.returnType,t.doc),n=e.dryrunIndex===void 0&&t.doc?.signature?t.doc.signature:HN(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 WN(t,e){let n=t.getFunctionMetadata(e);if(n)return Wd({name:e,arity:n.arity,params:n.params,returnType:n.returnType??void 0,doc:t.getFunctionDoc(e)})}function d_(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,WN(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,Wd({...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.
|
|
416
416
|
Example (run each statement on its own line):
|
|
417
417
|
args = cmd program a=" " b="adsfa"
|
|
418
418
|
assert(json_stringify(args) == '["program","a= ","b=adsfa"]');
|
|
@@ -474,16 +474,16 @@ ${i}`,n),this.line=r,this.column=s,this.codeblock=i}static x(e,n,r){throw new t(
|
|
|
474
474
|
`).slice(-12).join(`
|
|
475
475
|
`)));return c.stdout},s=(c,u,d)=>Fn(n(c,u,d),r),i=(c,u,d)=>Fn(s(c,["rev-parse","--verify","--end-of-options",T_(u,"revision")],d),sl),o=({r:c})=>c.code===1&&!c.stderr&&!c.signal&&!c.timed_out,a=(c,u)=>Fn(n(c,["symbolic-ref","--quiet","--short","HEAD"],u),d=>o(d)?null:sl(r(d)));return{functions:{"git.status":(c,u)=>Fn(s(c,["status","--porcelain=v2","-z","--branch","--ahead-behind","--untracked-files=all","--renames"],u),d=>{let m=S_(d);return m.detached?Fn(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)=>Fn(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 g=f.indexOf(`
|
|
476
476
|
`),h=f.slice(0,g).match(/^remote\.(.+)\.url$/);if(g<0||!h)throw Error("git: malformed remote config");return{name:h[1],url:f.slice(g+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 Fn(n(c,["rev-parse","--verify","--quiet","--end-of-options","HEAD"],d),m=>o(m)?[]:(r(m),u===0?[]:Fn(s(c,["log","--no-show-signature","--encoding=UTF-8","-n",String(u),"--format=%H%x00%an%x00%aI%x00%B","-z","--"],d),k_)))}},globals:{},dispose(){}}}var Fn,sl,ZN,I_=L(()=>{"use strict";Fn=(t,e)=>t instanceof Promise?t.then(e):e(t),sl=t=>t.endsWith(`
|
|
477
|
-
`)?t.slice(0,-1):t,ZN=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 LG,dr,ns,nO,rO,Qd,sO,Zd,pe,Yd,dn,il,ur,ol,ll,Us,x_,A_,C_,Hs,al,iO,N_,O_,at,mn=L(()=>{"use strict";LG=1,dr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))dr(e);Object.freeze(t)}return t},ns=dr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed"]),nO=dr({status:"string",error:"string|null",code:"ErrorCode?"}),rO=dr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),Qd=dr(["Provider1.Provider","Provider1.Model1","Provider1.Model2","Provider1.Model3","Provider2.Provider","Provider2.Model1","Provider2.Model2","Provider2.Model3","Provider3.Provider","Provider3.Model1","Provider3.Model2","Provider3.Model3"]),sO=dr(["Provider1","Provider2","Provider3"]),Zd=dr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),pe={name:"ctx",type:"context"},Yd={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},dn={name:"teamfile",type:"string"},il={name:"alias",type:"string"},ur={name:"prompt",type:"string"},ol={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"}]},ll=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],Us={name:"options",type:"map",optional:!0,keys:ll},x_={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},A_={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},C_={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Hs={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},al={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"}]},iO=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"}],N_={name:"options",type:"map",optional:!0,keys:iO},O_={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},at=dr([{name:"resolveProfilePath",implemented:!0,params:[pe,Yd],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[pe,Yd],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:[pe,{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:[pe,dn],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[dn]}},{name:"resolveMember",implemented:!0,params:[pe,dn,il],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:[dn,il]}},{name:"lintTeam",implemented:!0,params:[pe,dn],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:[dn]}},{name:"seedTeam",implemented:!0,params:[pe,dn,x_],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:[dn,x_]}},{name:"promptAgent",implemented:!0,params:[pe,ol,ur,Us],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...O_,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[ol,ur,Us]}},{name:"promptMember",implemented:!0,params:[pe,{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"},...ll]}],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:[dn,il,ur,{name:"options",type:"map",optional:!0,keys:[...ll,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[pe,{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:[pe,Hs,C_],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:[ol,{...C_,optional:!0}]}},{name:"getSession",implemented:!0,params:[pe,Hs],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:[Hs]}},{name:"reserveSession",implemented:!0,params:[pe,Hs],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:[pe,Hs,{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:[pe,{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"},...ll]}],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:[pe,{name:"batch",type:"BatchRef"},ur,{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:[pe,{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:[pe,A_],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:[A_]}},{name:"openTerminal",implemented:!0,params:[pe,{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:[dn,il]}},{name:"sessionAdmission",implemented:!0,params:[pe,Hs],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:[pe,{name:"reservation",type:"SessionReservation"},ol,ur,Us],statuses:["ok","busy","stalled","empty","error"],results:{...O_,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[pe,{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:[pe,{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:[pe,{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"}]},Us],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:[pe,{name:"session",type:"NativeSessionRef"},ur],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:[pe,{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:[pe,{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:[pe,al,ur,Us],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",code:"ErrorCode?"},effects:["provider","db"],summary:"Send one stateless turn to a detached native-session holder, starting one when absent.",scriptBinding:{name:"lm_session_turn",params:[al,ur,Us]}},{name:"nativeSessionClose",implemented:!0,params:[pe,al],statuses:["ok","busy","error"],results:{error:"string|null",code:"ErrorCode?"},effects:["provider","db"],summary:"Close an idle detached native-session holder; an absent holder is already closed.",scriptBinding:{name:"lm_session_close",params:[al]}},{name:"loadProperties",implemented:!0,params:[pe,Yd],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:[pe,N_],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:[N_]}}])});var L_,M_=L(()=>{"use strict";L_=[{name:"lm_session_turn",category:"lmctl Automation",signature:"lm_session_turn(member, prompt, options = {})",description:"Sends one stateless turn to a detached Kimi native-session holder addressed by provider and sessionid. The holder survives the caller; a busy or closed holder is returned as a result map. idleTimeoutMs controls holder retention (the default is 300000 ms; zero uses that default). 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? }"},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 detached Kimi native-session holder addressed by provider and sessionid. Idle holders close, active holders return busy, and an absent holder 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_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", 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", 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 de(t){return{...t,status:"ok",error:null}}function H(t,e,n){return{...n,status:"error",code:t,error:e}}var et=L(()=>{"use strict"});function D_(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?so:P_}var P_,so,em=L(()=>{"use strict";P_="root_teamfile <> '(direct)'",so=P_+" AND COALESCE(accounting_only,0)=0"});import{existsSync as oO}from"node:fs";import{createRequire as aO}from"node:module";function lO(){return tm===null&&(tm=aO(import.meta.url)("node:sqlite").DatabaseSync),tm}function dO(t){let e=uO[t];if(e!==void 0)return e;let n=cO[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function rs(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=dO(t.errcode)),t}function mO(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function pO(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function nm(t){return t.length===1&&fO(t[0])?[t[0]]:t}function fO(t){if(!im(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function im(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var tm,cO,uO,rm,Bs,sm,cl=L(()=>{"use strict";tm=null;cO={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"},uO={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"};rm=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!oO(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(lO())(e,{readOnly:n.readonly===!0})}catch(r){rs(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new sm(this.handle.prepare(e))}catch(n){rs(n)}}exec(e){try{this.handle.exec(e)}catch(n){rs(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){rs(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(!mO(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(!pO(o))throw o}throw i}}};Bs=rm,sm=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...nm(e));return this.normalizeRow(n)}catch(n){rs(n)}}all(...e){try{return this.handle.all(...nm(e)).map(n=>this.normalizeRow(n))}catch(n){rs(n)}}run(...e){try{let n=this.handle.run(...nm(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){rs(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&im(e)?Object.values(e):im(e)?{...e}:e}}});function om(t){return new Bs(t,{readonly:!0,fileMustExist:!0})}var F_=L(()=>{"use strict";cl()});import{createHash as gO}from"node:crypto";import{lstat as hO,readFile as yO,realpath as $_,stat as j_}from"node:fs/promises";import{isAbsolute as U_,relative as _O,resolve as vO,sep as bO}from"node:path";function J(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function Z(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function io(t){return Z(t)}function Lt(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function fe(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 we(t,e){return t<e?-1:t>e?1:0}function lt(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 pn(t,e,n){let r={},s=io(t.cacheWrite5m),i=io(t.cacheWrite1h),o=io(t.reasoning),a=io(t.webSearch),l=io(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 mr(t){return typeof t=="string"&&EO.has(t.toLowerCase())}function Le(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 Ws(t){let e=J(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function Ge(t,e){if(!U_(t))return null;let n=await hO(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await $_(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await $_(s).catch(()=>vO(s)),o=_O(i,r);if(o===""||!o.startsWith(`..${bO}`)&&o!==".."&&!U_(o))return r}return null}async function _t(t,e){fe(e);let n=await j_(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await yO(t,{signal:e.signal});e.signal.throwIfAborted();let s=await j_(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${oo}:sha256:${gO("sha256").update(r).digest("hex")}`,data:r}}function ul(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(`
|
|
477
|
+
`)?t.slice(0,-1):t,ZN=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 LG,dr,ns,nO,rO,Qd,sO,Zd,pe,Yd,mn,il,ur,ol,ll,Us,x_,A_,C_,Hs,al,iO,N_,O_,at,pn=L(()=>{"use strict";LG=1,dr=t=>{if(t&&typeof t=="object"){for(let e of Object.values(t))dr(e);Object.freeze(t)}return t},ns=dr(["invalid_argument","not_found","missing","read","syntax","schema","busy","provider","noninteractive","cancelled","internal","closed"]),nO=dr({status:"string",error:"string|null",code:"ErrorCode?"}),rO=dr(["Provider1","Provider2","Provider3","Model1","Model2","Model3"]),Qd=dr(["Provider1.Provider","Provider1.Model1","Provider1.Model2","Provider1.Model3","Provider2.Provider","Provider2.Model1","Provider2.Model2","Provider2.Model3","Provider3.Provider","Provider3.Model1","Provider3.Model2","Provider3.Model3"]),sO=dr(["Provider1","Provider2","Provider3"]),Zd=dr({Provider1:"PROPS.Provider1.Provider",Provider2:"PROPS.Provider2.Provider",Provider3:"PROPS.Provider3.Provider",Model1:"PROPS.Provider1.Model1",Model2:"PROPS.Provider2.Model1",Model3:"PROPS.Provider3.Model1"}),pe={name:"ctx",type:"context"},Yd={name:"options",type:"map",optional:!0,keys:[{name:"path",type:"string"}]},mn={name:"teamfile",type:"string"},il={name:"alias",type:"string"},ur={name:"prompt",type:"string"},ol={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"}]},ll=[{name:"permissionMode",type:"string",values:["yolo","plan"]},{name:"idleTimeoutMs",type:"number"}],Us={name:"options",type:"map",optional:!0,keys:ll},x_={name:"options",type:"map",optional:!0,keys:[{name:"preamble",type:"string|map"}]},A_={name:"options",type:"map",optional:!0,keys:[{name:"providers",type:"list"},{name:"provider",type:"string"},{name:"timeoutSeconds",type:"number"}]},C_={name:"options",type:"map",keys:[{name:"force",type:"boolean",required:!0,values:[!0]}]},Hs={name:"target",type:"map",keys:[{name:"provider",type:"string",required:!0},{name:"sessionid",type:"string",required:!0}]},al={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"}]},iO=[{name:"teamfile",type:"string"},{name:"member",type:"string"},{name:"since",type:"string"},{name:"tree",type:"boolean"}],N_={name:"options",type:"map",optional:!0,keys:iO},O_={error:"string|null",reply:"string",sessionid:"string|null",messageId:"string|null",teamChatLogId:"number|null"},at=dr([{name:"resolveProfilePath",implemented:!0,params:[pe,Yd],statuses:["ok","error"],results:{error:"string|null",path:"string"},effects:[],summary:"Resolve a profile path solely from explicit context."},{name:"loadProfile",implemented:!0,params:[pe,Yd],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:[pe,{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:[pe,mn],statuses:["ok","error"],results:{error:"string|null",members:"Member[]"},effects:["file-read"],summary:"List team members.",scriptBinding:{name:"lm_members",params:[mn]}},{name:"resolveMember",implemented:!0,params:[pe,mn,il],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:[mn,il]}},{name:"lintTeam",implemented:!0,params:[pe,mn],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:[mn]}},{name:"seedTeam",implemented:!0,params:[pe,mn,x_],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:[mn,x_]}},{name:"promptAgent",implemented:!0,params:[pe,ol,ur,Us],statuses:["ok","busy","stalled","empty","cancelled","error"],results:{...O_,messageId:"null",teamChatLogId:"null"},effects:["provider","db"],summary:"Turn a provider session without mutating the input member.",scriptBinding:{name:"lm_agent",params:[ol,ur,Us]}},{name:"promptMember",implemented:!0,params:[pe,{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"},...ll]}],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:[mn,il,ur,{name:"options",type:"map",optional:!0,keys:[...ll,{name:"messageType",type:"string"}]}]}},{name:"listSessions",implemented:!0,params:[pe,{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:[pe,Hs,C_],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:[ol,{...C_,optional:!0}]}},{name:"getSession",implemented:!0,params:[pe,Hs],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:[Hs]}},{name:"reserveSession",implemented:!0,params:[pe,Hs],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:[pe,Hs,{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:[pe,{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"},...ll]}],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:[pe,{name:"batch",type:"BatchRef"},ur,{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:[pe,{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:[pe,A_],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:[A_]}},{name:"openTerminal",implemented:!0,params:[pe,{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:[mn,il]}},{name:"sessionAdmission",implemented:!0,params:[pe,Hs],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:[pe,{name:"reservation",type:"SessionReservation"},ol,ur,Us],statuses:["ok","busy","stalled","empty","error"],results:{...O_,messageId:"null",teamChatLogId:"null"},effects:["provider"],summary:"Turn only the session authorized by a live context-bound reservation."},{name:"finalizeBatchSync",implemented:!0,params:[pe,{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:[pe,{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:[pe,{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"}]},Us],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:[pe,{name:"session",type:"NativeSessionRef"},ur],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:[pe,{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:[pe,{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:[pe,al,ur,Us],statuses:["ok","busy","stalled","empty","error"],results:{error:"string|null",reply:"string",messageId:"string|null",teamChatLogId:"number|null",code:"ErrorCode?"},effects:["provider","db"],summary:"Send one stateless turn to a detached native-session holder, starting one when absent.",scriptBinding:{name:"lm_session_turn",params:[al,ur,Us]}},{name:"nativeSessionClose",implemented:!0,params:[pe,al],statuses:["ok","busy","error"],results:{error:"string|null",code:"ErrorCode?"},effects:["provider","db"],summary:"Close an idle detached native-session holder; an absent holder is already closed.",scriptBinding:{name:"lm_session_close",params:[al]}},{name:"loadProperties",implemented:!0,params:[pe,Yd],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:[pe,N_],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:[N_]}}])});var L_,M_=L(()=>{"use strict";L_=[{name:"lm_session_turn",category:"lmctl Automation",signature:"lm_session_turn(member, prompt, options = {})",description:"Sends one stateless turn to a detached Kimi native-session holder addressed by provider and sessionid. The holder survives the caller; a busy or closed holder is returned as a result map. idleTimeoutMs controls holder retention (the default is 300000 ms; zero uses that default). 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? }"},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 detached Kimi native-session holder addressed by provider and sessionid. Idle holders close, active holders return busy, and an absent holder 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_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", 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", 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 de(t){return{...t,status:"ok",error:null}}function H(t,e,n){return{...n,status:"error",code:t,error:e}}var tt=L(()=>{"use strict"});function D_(t){return t.prepare("PRAGMA table_info(team_chat_log)").all().some(e=>e.name==="accounting_only")?so:P_}var P_,so,em=L(()=>{"use strict";P_="root_teamfile <> '(direct)'",so=P_+" AND COALESCE(accounting_only,0)=0"});import{existsSync as oO}from"node:fs";import{createRequire as aO}from"node:module";function lO(){return tm===null&&(tm=aO(import.meta.url)("node:sqlite").DatabaseSync),tm}function dO(t){let e=uO[t];if(e!==void 0)return e;let n=cO[t&255];return n!==void 0?n:`SQLITE_UNKNOWN_${t}`}function rs(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=dO(t.errcode)),t}function mO(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function pO(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function nm(t){return t.length===1&&fO(t[0])?[t[0]]:t}function fO(t){if(!im(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function im(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var tm,cO,uO,rm,Bs,sm,cl=L(()=>{"use strict";tm=null;cO={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"},uO={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"};rm=class{name;handle;savepointId=0;constructor(e,n={}){if(n.fileMustExist===!0&&e!==":memory:"&&!oO(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(lO())(e,{readOnly:n.readonly===!0})}catch(r){rs(r)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${n.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new sm(this.handle.prepare(e))}catch(n){rs(n)}}exec(e){try{this.handle.exec(e)}catch(n){rs(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){rs(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(!mO(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(!pO(o))throw o}throw i}}};Bs=rm,sm=class{constructor(e){this.handle=e;this.handle.setAllowBareNamedParameters(!0)}rawMode=!1;get(...e){try{let n=this.handle.get(...nm(e));return this.normalizeRow(n)}catch(n){rs(n)}}all(...e){try{return this.handle.all(...nm(e)).map(n=>this.normalizeRow(n))}catch(n){rs(n)}}run(...e){try{let n=this.handle.run(...nm(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){rs(n)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&im(e)?Object.values(e):im(e)?{...e}:e}}});function om(t){return new Bs(t,{readonly:!0,fileMustExist:!0})}var F_=L(()=>{"use strict";cl()});import{createHash as gO}from"node:crypto";import{lstat as hO,readFile as yO,realpath as $_,stat as j_}from"node:fs/promises";import{isAbsolute as U_,relative as _O,resolve as vO,sep as bO}from"node:path";function J(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function Z(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function io(t){return Z(t)}function Lt(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function fe(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 we(t,e){return t<e?-1:t>e?1:0}function lt(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 fn(t,e,n){let r={},s=io(t.cacheWrite5m),i=io(t.cacheWrite1h),o=io(t.reasoning),a=io(t.webSearch),l=io(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 mr(t){return typeof t=="string"&&EO.has(t.toLowerCase())}function Le(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 Ws(t){let e=J(t);return e&&typeof e.content=="string"?Buffer.byteLength(e.content,"utf8"):null}async function Ge(t,e){if(!U_(t))return null;let n=await hO(t).catch(()=>null);if(!n?.isFile()||n.isSymbolicLink())return null;let r=await $_(t).catch(()=>null);if(!r)return null;for(let s of e){let i=await $_(s).catch(()=>vO(s)),o=_O(i,r);if(o===""||!o.startsWith(`..${bO}`)&&o!==".."&&!U_(o))return r}return null}async function _t(t,e){fe(e);let n=await j_(t).catch(()=>null);if(!n?.isFile()||n.size>e.maxBytes)return null;let r=await yO(t,{signal:e.signal});e.signal.throwIfAborted();let s=await j_(t).catch(()=>null);return!s?.isFile()||n.dev!==s.dev||n.ino!==s.ino||n.size!==s.size||n.mtimeMs!==s.mtimeMs?null:{revision:`${oo}:sha256:${gO("sha256").update(r).digest("hex")}`,data:r}}function ul(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(`
|
|
478
478
|
`),s=[];for(let i of r)if(e.signal.throwIfAborted(),!!i.trim())try{let o=J(JSON.parse(i));if(!o)return null;s.push(o)}catch{return null}return s}var oo,yt,Nt,wO,Ot,EO,$n=L(()=>{"use strict";oo="bx3",yt={input_uncached:null,input_cached:null,input_cache_write:null,output:null};Nt=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}},wO=0,Ot=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${wO++}`,this.map.has(n)||this.map.set(n,e)}entries(){return[...this.map.values()]}};EO=new Set(["schedulewakeup","taskcreate","taskupdate","taskoutput","taskstop","todowrite","todoread","croncreate","crondelete","cronlist","monitor","listagents","toolsearch","askuserquestion","exitplanmode","agent","skill","job"])});import{readdir as TO}from"node:fs/promises";import{join as H_,sep as B_}from"node:path";var qs,am=L(()=>{"use strict";$n();qs=class{constructor(e){this.format=e}async discover(e,n,r){fe(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 TO(l,{withFileTypes:!0}).catch(m=>(m.code!=="ENOENT"&&(o=!0),[])),d=m=>H_(l,m.name)+(m.isDirectory()?B_:"");for(let m of u.sort((p,f)=>we(d(p),d(f)))){e.signal.throwIfAborted();let p=H_(l,m.name),f=m.isDirectory()&&r?.startsWith(p+B_);if(!(r&&!f&&we(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 g=this.format.sessionId(p);g&&s.push({provider:this.format.provider,sessionid:g,source_id:p})}if(s.length>=n){o=!0;break}}}};return await a(this.format.root,0),s.sort((l,c)=>we(l.source_id,c.source_id)),{sources:s.slice(0,n),truncated:o||s.length>n}}async bytes(e,n){if(fe(n),e.provider!==this.format.provider||this.format.sessionId(e.source_id)!==e.sessionid)return null;let r=await Ge(e.source_id,[this.format.root]);if(!r)return null;let s=await _t(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 Xs(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 dl=L(()=>{"use strict"});import{createReadStream as W_}from"node:fs";import{createInterface as q_}from"node:readline";import{stat as SO}from"node:fs/promises";import{homedir as kO}from"node:os";function X_(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*Ie(t,e){let n=W_(t,{encoding:"utf-8"}),r=q_({input:n,crlfDelay:1/0});try{for await(let s of r){let i=s.trim();if(!i)continue;let o=X_(i);o!==void 0?yield o:e?.()}}finally{n.destroy()}}async function Mt(t,e){let n=[],r=W_(t,{encoding:"utf-8"}),s=q_({input:r,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=X_(o);if(a!==void 0&&n.push(a),n.length>=e)break}}finally{s.close(),r.destroy()}return n}async function De(t){let e=await SO(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function Te(t){return t.replace(/\\n/g,`
|
|
479
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function z(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Jt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ie,We=L(()=>{"use strict";ie=kO()});import{readdir as RO}from"node:fs/promises";import{join as Gs,resolve as IO}from"node:path";function pl(t){return IO(t||process.env.XDG_DATA_HOME||Gs(ie,".local","share"))}function xO(t){return Gs(pl(t),"muse","sessions")}function AO(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 V_(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},g=y=>{if(y.retained_frame&&Array.isArray(y.children)){for(let T of y.children)try{if(typeof T?.record_json!="string")throw new Error("missing record_json");g(JSON.parse(T.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 T of[y.id,b])if(!(typeof T!="string"||T.length===0)&&u.has(T))return;for(let T of[y.id,b])typeof T=="string"&&T.length>0&&u.add(T);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,I=f(v.run_id);if(!E||!_||!I){E||p();return}if(E.kind==="started"&&typeof E.prompt=="string")a.push({role:"user",content:E.prompt,timestamp:_}),I.turn.startedAt=_,I.turn.prompt=E.prompt,I.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")I.turn.completedAt=_,I.turn.status=E.terminal==="completed"?"complete":"aborted",o=I.turn.status;else if(E.kind==="model_completed"){typeof E.model=="string"&&E.model.length>0&&(r=E.model,I.turn.model=E.model);let T=typeof b=="string"&&b.length>0?b:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(!T)p();else{I.responseIds.push(T);let U={};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 ee=E.usage[F];typeof ee=="number"&&Number.isSafeInteger(ee)&&ee>=0&&(U[F]=ee)}Object.keys(U).length>0&&(I.turn.rawUsage=[...I.turn.rawUsage??[],{responseId:T,values:U}]),c.set(T,AO(T,_,E.model,U))}if(!E.usage)return;let k={},N=E.usage.input_tokens,C=E.usage.cache_read_tokens??E.usage.input_cache_read_tokens,O=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,S=typeof N=="number"&&typeof C=="number"&&C>N||typeof w=="number"&&typeof C=="number"&&C>w||typeof w=="number"&&typeof O=="number"&&O>w||typeof w=="number"&&typeof C=="number"&&typeof O=="number"&&C+O>w,R=S?void 0:typeof C=="number"?C:void 0,x=S?void 0:typeof O=="number"?O:void 0,A;S||(typeof E.usage.input_uncached_tokens=="number"?A=E.usage.input_uncached_tokens:typeof w=="number"&&typeof C=="number"&&typeof O=="number"&&w>=C+O&&(A=w-C-O)),A!==void 0&&A<0&&(A=void 0);let M=E.usage.output_tokens,P=E.usage.reasoning_tokens;typeof A=="number"&&Number.isSafeInteger(A)&&A>=0&&(k.inputTokens=A),typeof R=="number"&&Number.isSafeInteger(R)&&R>=0&&(k.cachedInputTokens=R),typeof x=="number"&&Number.isSafeInteger(x)&&x>=0&&(k.cacheWriteInputTokens=x),typeof M=="number"&&Number.isSafeInteger(M)&&M>=0&&(k.outputTokens=M),typeof P=="number"&&Number.isSafeInteger(P)&&P>=0&&(k.reasoningOutputTokens=P),d=k}};return{visit:g,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=Xs(_,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 CO(t,e,n){let r=V_(e,n);for(let s of t)r.visit(s);return r.finish()}function NO(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 g;try{if(typeof f?.record_json!="string")throw new Error("missing record_json");g=JSON.parse(f.record_json)}catch{l=!0;continue}u(g)}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=CO(a,e,n);return d&&l&&(d.captureStatus="partial"),d}function K_(t){return{provider:"muse",root:xO(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:NO}}async function J_(t,e){let n=V_(t,e);for await(let r of Ie(e,n.markPartial))n.visit(r);return n.finish()}var G_,ml,lm=L(()=>{"use strict";dl();We();G_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ml=class{name="muse";dataHome;constructor(e={}){this.dataHome=pl(e.museDataHome)}get root(){return Gs(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,n=0){let r;try{r=await RO(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of r)i.isFile()&&i.name==="session.jsonl"?s.push(Gs(e,i.name)):i.isDirectory()&&n<4&&s.push(...await this.files(Gs(e,i.name),n+1));return s}async resolveSessionPath(e){return G_.test(e)?(await this.files()).find(n=>n.endsWith(Gs(e,"session.jsonl")))??null:null}async loadSession(e){let n=await this.resolveSessionPath(e);return n?J_(e,n):null}async discoverSessions(){let e=[];for(let n of await this.files())try{let r=n.split(/[\\/]/).at(-2);if(!G_.test(r))continue;let s=await J_(r,n);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});import{readFile as z_,readdir as OO,rm as LO,stat as Y_}from"node:fs/promises";import{basename as MO,join as Js,resolve as PO}from"node:path";function hl(t){return PO(t||process.env.MINIPLAYER_HOME||Js(process.env.XDG_DATA_HOME||Js(ie,".local","share"),"miniplayer"))}function fl(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function cm(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function Q_(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Z_(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ev(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 tv(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},n={};for(let[l,c]of Object.entries(e))Z(c)!==null&&(n[l]=c);let r=Z(e.inputTokens),s=Z(e.cachedInputTokens),i=Z(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=Z(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:Z(e.reasoningTokens)===null?null:{reasoning_output_tokens:Z(e.reasoningTokens)}}}function rv(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 g=new Date(f);return Number.isFinite(g.getTime())?g: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,g=new Set;for(let h of r.turns){if(!h||typeof h.responseId!="string"||!h.responseId||typeof h.input?.text!="string")return null;if(f.has(h.responseId)){u=!0;continue}f.add(h.responseId);let y=s(h.startedAt),b=s(h.completedAt??h.endedAt);if(!y)return null;let _=typeof h.model=="string"?h.model:void 0;["complete","running","failed","aborted"].includes(h.status)||(u=!0);let v=h.status==="complete"?"complete":h.status==="running"?"in_progress":h.status==="failed"?"failed":h.status==="aborted"?"aborted":"unknown";d=v==="failed"||v==="unknown"?"aborted":v,(v!=="complete"||h.partial===!0)&&(u=!0);let E=Array.isArray(h.modelResponses),I=E?h.modelResponses:[],T=[];l.push({id:h.responseId,startedAt:y,completedAt:b,model:_,prompt:h.input.text,status:v,responseIds:T}),a.push({role:"user",timestamp:y,content:h.input.text});let k=Array.isArray(h.toolEvents)&&h.toolEvents.length>0;if(!E&&!k){let S=h.usage??{},R=tv({...h,usage:S});Object.keys(R.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:h.responseId,values:R.rawUsage}]),T.push(h.responseId),c.push({response_id:h.responseId,timestamp:(b??y).toISOString(),model:_??null,model_provider:typeof h.provider=="string"?h.provider:null,tokens:R.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(h.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:h.responseId,ref:null,bytes:Buffer.byteLength(h.input.text,"utf8"),basis:"input_text"}],pricing_facts:R.pricingFacts}),v!=="complete"&&!h.usage&&(u=!0),typeof h.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:h.output.text,model:_});continue}let N=new Map,C=new Map,O=new Set,w=[];for(let S of I){if(!S||typeof S!="object"||typeof S.responseId!="string"||!S.responseId){u=!0;continue}if(T.includes(S.responseId)){u=!0;continue}let R=S,x=w.length;w.push({response:R,index:x,filesRead:[],filesWritten:[],io:[]}),T.push(S.responseId),g.has(S.responseId)&&(u=!0),g.add(S.responseId),R.toolCalls!==void 0&&!Array.isArray(R.toolCalls)&&(u=!0,w[x].io.push({direction:"read",kind:"unattributed",id:S.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:S.responseId,ref:null,bytes:null,basis:"unknown"}));for(let A of Array.isArray(R.toolCalls)?R.toolCalls:[]){let M=Q_(A),P=cm(A);if(M)N.set(M,x),C.set(M,P);else{u=!0;let U=P==="list_directory"||P==="read_file"||P==="webget"||P==="shell"||P==="tool",F=P==="write_file"||P==="shell"||P==="tool";U&&w[x].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),F&&w[x].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}T.length===0&&I.length>0&&(u=!0);for(let S of Array.isArray(h.toolEvents)?h.toolEvents:[]){let R=S&&typeof S=="object"?S:{},x=Q_(R),A=x?N.get(x):void 0,M=cm(R),P=Z_(R.result),U=R.status==="failed"||R.error!==void 0;if(R.type==="tool_call"?a.push({role:"tool_use",timestamp:s(R?.timestamp)??y,content:fl(R?.input??R?.args),toolName:M,toolInput:fl(R?.input??R?.args),toolInputData:Z_(R?.input??R?.args)??void 0,...x?{toolCallId:x}:{}}):a.push({role:"tool_result",timestamp:s(R?.timestamp)??b??y,content:fl(U?R?.error:R?.result),toolName:M,...x?{toolCallId:x}:{}}),A===void 0){u=!0;continue}let F=w[A];(R.type==="tool_result"||U||R.result!==void 0)&&O.add(x);let ee=P?.path,q=Z(P?.bytesRead??P?.bytesWritten);R.type!=="tool_call"&&(M==="read_file"&&!U&&typeof ee=="string"&&q!==null?F.filesRead.push({path:ee,bytes:q}):M==="write_file"&&!U&&typeof ee=="string"&&q!==null?F.filesWritten.push({path:ee,bytes:q}):M==="webget"&&!U&&q!==null?F.io.push({direction:"read",kind:"web",id:x,ref:ev(P?.finalUrl??P?.url),bytes:q,basis:"certified_counter"}):M==="shell"||U?(M!=="write_file"&&F.io.push({direction:"read",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"}),(M==="shell"||M==="write_file")&&F.io.push({direction:"write",kind:"unattributed",id:x,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:x,ref:M==="webget"?ev(P?.finalUrl??P?.url):null,bytes:null,basis:"unknown"}):M==="write_file"?F.io.push({direction:"write",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"}):F.io.push({direction:"read",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"}))}for(let[S,R]of C)if(!O.has(S)){let x=w[N.get(S)],A=R==="list_directory"||R==="read_file"||R==="webget"||R==="shell",M=R==="write_file"||R==="shell";A&&x.io.push({direction:"read",kind:"unattributed",id:S,ref:null,bytes:null,basis:"unknown"}),M&&x.io.push({direction:"write",kind:"unattributed",id:S,ref:null,bytes:null,basis:"unknown"}),u=!0}for(let S of w){let R=S.response,x=tv(R),A=s(R.completedAt??R.startedAt)??b??y;new Set((Array.isArray(R.toolCalls)?R.toolCalls:[]).map(F=>cm(F))).has("shell")&&!S.io.some(F=>F.kind==="unattributed"&&F.direction==="read")&&S.io.push({direction:"read",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"}),S.index===0&&S.io.unshift({direction:"read",kind:"prompt",id:h.responseId,ref:null,bytes:Buffer.byteLength(h.input.text,"utf8"),basis:"input_text"});let P=S.io.some(F=>F.direction==="read"&&F.bytes===null),U=S.io.some(F=>F.direction==="write"&&F.bytes===null);if(c.push({response_id:R.responseId,timestamp:A.toISOString(),model:typeof R.model=="string"?R.model:null,model_provider:typeof R.provider=="string"?R.provider:typeof h.provider=="string"?h.provider:null,tokens:x.tokens,files_read:P?null:S.filesRead,files_written:U?null:S.filesWritten,read_bytes:P?null:S.filesRead.reduce((F,ee)=>F+(ee.bytes??0),0)+S.io.filter(F=>F.direction==="read").reduce((F,ee)=>F+(ee.bytes??0),0),write_bytes:U?null:S.filesWritten.reduce((F,ee)=>F+(ee.bytes??0),0)+S.io.filter(F=>F.direction==="write").reduce((F,ee)=>F+(ee.bytes??0),0),external_io:S.io,pricing_facts:x.pricingFacts}),Object.keys(x.rawUsage).length){let F=l.at(-1);F.rawUsage=[...F.rawUsage??[],{responseId:R.responseId,values:x.rawUsage}]}}l.at(-1).responseIds=T,T.length!==I.length&&(u=!0),typeof h.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:h.output.text,model:_})}}let m=a.filter(f=>f.role==="user").map(f=>f.content),p=Xs(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 yl(t){return{provider:"miniplayer",root:Js(hl(t),"sessions"),revision:"miniplayer-data-v3",sessionId(e){let n=MO(e,".json");return e.endsWith(".json")&&nv.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:rv(i,n,r)}catch{return null}}}}var nv,gl,_l=L(()=>{"use strict";dl();We();$n();nv=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;gl=class{name="miniplayer";home;constructor(e={}){this.home=hl(e.miniplayerHome)}getWatchPaths(){return[{directory:Js(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await OO(Js(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(!nv.test(e))return null;let n=Js(this.home,"sessions",`${e}.json`);try{return(await Y_(n)).isFile()?n:null}catch{return null}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;try{let r=rv(JSON.parse(await z_(n,"utf8")),e,n);if(!r)return null;let s="complete";try{let i=JSON.parse(await z_(`${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 Y_(`${n}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(r){if(r.code!=="ENOENT")throw r}return await LO(n),!0}}});import{createHash as DO}from"node:crypto";import{createRequire as FO}from"node:module";import{readdir as $O,realpath as jO}from"node:fs/promises";import{basename as sv,dirname as UO,join as iv,resolve as ov}from"node:path";function BO(){return HO("node:sqlite").DatabaseSync}function WO(){return process.env.HOME||process.env.USERPROFILE||""}function ss(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 fn(t,e){return t.find(n=>n.field===e)}function qO(t){let e=new Map;for(let n of t){if(n.field!==20||n.bytes===void 0)continue;let r=ss(n.bytes),s=fn(r,1)?.bytes,i=fn(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 XO(t){let e=fn(ss(t),5)?.bytes;if(e===void 0)return null;let n=fn(ss(e),1)?.bytes;if(n===void 0)return null;let r=ss(n),s=fn(r,1)?.varint;if(s===void 0)return null;let i=fn(r,2)?.varint??0,o=s*1e3+Math.floor(i/1e6),a=new Date(o);return Number.isFinite(a.getTime())?a.toISOString():null}function GO(t){let e=fn(t,4)?.bytes,n=e!==void 0?ss(e):[],r=s=>{let i=fn(n,s)?.varint;return i===void 0?null:Z(i)};return{tokens:{input_uncached:r(2),input_cached:r(5),input_cache_write:r(4),output:r(3)},thinkingOutputTokens:r(9)}}function JO(t){let e=fn(ss(t),1)?.bytes;if(e===void 0)return null;let n=ss(e),r=qO(n),s=r.get("request_id");if(s===void 0||s.length===0)return null;let i=fn(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}=GO(n);return{requestId:s,model:o,lastStepIndex:c,tokens:u,thinkingOutputTokens:d}}function av(t,e){fe(e);let n=t.prepare("SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) AS total FROM gen_metadata").get(),r=Z(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=DO("sha256");i.update("rev:").update(vl).update(`
|
|
479
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function z(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Jt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var ie,We=L(()=>{"use strict";ie=kO()});import{readdir as RO}from"node:fs/promises";import{join as Gs,resolve as IO}from"node:path";function pl(t){return IO(t||process.env.XDG_DATA_HOME||Gs(ie,".local","share"))}function xO(t){return Gs(pl(t),"muse","sessions")}function AO(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 V_(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},g=y=>{if(y.retained_frame&&Array.isArray(y.children)){for(let T of y.children)try{if(typeof T?.record_json!="string")throw new Error("missing record_json");g(JSON.parse(T.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 T of[y.id,b])if(!(typeof T!="string"||T.length===0)&&u.has(T))return;for(let T of[y.id,b])typeof T=="string"&&T.length>0&&u.add(T);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,I=f(v.run_id);if(!E||!_||!I){E||p();return}if(E.kind==="started"&&typeof E.prompt=="string")a.push({role:"user",content:E.prompt,timestamp:_}),I.turn.startedAt=_,I.turn.prompt=E.prompt,I.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")I.turn.completedAt=_,I.turn.status=E.terminal==="completed"?"complete":"aborted",o=I.turn.status;else if(E.kind==="model_completed"){typeof E.model=="string"&&E.model.length>0&&(r=E.model,I.turn.model=E.model);let T=typeof b=="string"&&b.length>0?b:typeof y.id=="string"&&y.id.length>0?y.id:void 0;if(!T)p();else{I.responseIds.push(T);let U={};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 ee=E.usage[F];typeof ee=="number"&&Number.isSafeInteger(ee)&&ee>=0&&(U[F]=ee)}Object.keys(U).length>0&&(I.turn.rawUsage=[...I.turn.rawUsage??[],{responseId:T,values:U}]),c.set(T,AO(T,_,E.model,U))}if(!E.usage)return;let k={},N=E.usage.input_tokens,C=E.usage.cache_read_tokens??E.usage.input_cache_read_tokens,O=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,S=typeof N=="number"&&typeof C=="number"&&C>N||typeof w=="number"&&typeof C=="number"&&C>w||typeof w=="number"&&typeof O=="number"&&O>w||typeof w=="number"&&typeof C=="number"&&typeof O=="number"&&C+O>w,R=S?void 0:typeof C=="number"?C:void 0,x=S?void 0:typeof O=="number"?O:void 0,A;S||(typeof E.usage.input_uncached_tokens=="number"?A=E.usage.input_uncached_tokens:typeof w=="number"&&typeof C=="number"&&typeof O=="number"&&w>=C+O&&(A=w-C-O)),A!==void 0&&A<0&&(A=void 0);let M=E.usage.output_tokens,P=E.usage.reasoning_tokens;typeof A=="number"&&Number.isSafeInteger(A)&&A>=0&&(k.inputTokens=A),typeof R=="number"&&Number.isSafeInteger(R)&&R>=0&&(k.cachedInputTokens=R),typeof x=="number"&&Number.isSafeInteger(x)&&x>=0&&(k.cacheWriteInputTokens=x),typeof M=="number"&&Number.isSafeInteger(M)&&M>=0&&(k.outputTokens=M),typeof P=="number"&&Number.isSafeInteger(P)&&P>=0&&(k.reasoningOutputTokens=P),d=k}};return{visit:g,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=Xs(_,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 CO(t,e,n){let r=V_(e,n);for(let s of t)r.visit(s);return r.finish()}function NO(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 g;try{if(typeof f?.record_json!="string")throw new Error("missing record_json");g=JSON.parse(f.record_json)}catch{l=!0;continue}u(g)}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=CO(a,e,n);return d&&l&&(d.captureStatus="partial"),d}function K_(t){return{provider:"muse",root:xO(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:NO}}async function J_(t,e){let n=V_(t,e);for await(let r of Ie(e,n.markPartial))n.visit(r);return n.finish()}var G_,ml,lm=L(()=>{"use strict";dl();We();G_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;ml=class{name="muse";dataHome;constructor(e={}){this.dataHome=pl(e.museDataHome)}get root(){return Gs(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,n=0){let r;try{r=await RO(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of r)i.isFile()&&i.name==="session.jsonl"?s.push(Gs(e,i.name)):i.isDirectory()&&n<4&&s.push(...await this.files(Gs(e,i.name),n+1));return s}async resolveSessionPath(e){return G_.test(e)?(await this.files()).find(n=>n.endsWith(Gs(e,"session.jsonl")))??null:null}async loadSession(e){let n=await this.resolveSessionPath(e);return n?J_(e,n):null}async discoverSessions(){let e=[];for(let n of await this.files())try{let r=n.split(/[\\/]/).at(-2);if(!G_.test(r))continue;let s=await J_(r,n);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});import{readFile as z_,readdir as OO,rm as LO,stat as Y_}from"node:fs/promises";import{basename as MO,join as Js,resolve as PO}from"node:path";function hl(t){return PO(t||process.env.MINIPLAYER_HOME||Js(process.env.XDG_DATA_HOME||Js(ie,".local","share"),"miniplayer"))}function fl(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function cm(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function Q_(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Z_(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ev(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 tv(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},n={};for(let[l,c]of Object.entries(e))Z(c)!==null&&(n[l]=c);let r=Z(e.inputTokens),s=Z(e.cachedInputTokens),i=Z(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=Z(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:Z(e.reasoningTokens)===null?null:{reasoning_output_tokens:Z(e.reasoningTokens)}}}function rv(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 g=new Date(f);return Number.isFinite(g.getTime())?g: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,g=new Set;for(let h of r.turns){if(!h||typeof h.responseId!="string"||!h.responseId||typeof h.input?.text!="string")return null;if(f.has(h.responseId)){u=!0;continue}f.add(h.responseId);let y=s(h.startedAt),b=s(h.completedAt??h.endedAt);if(!y)return null;let _=typeof h.model=="string"?h.model:void 0;["complete","running","failed","aborted"].includes(h.status)||(u=!0);let v=h.status==="complete"?"complete":h.status==="running"?"in_progress":h.status==="failed"?"failed":h.status==="aborted"?"aborted":"unknown";d=v==="failed"||v==="unknown"?"aborted":v,(v!=="complete"||h.partial===!0)&&(u=!0);let E=Array.isArray(h.modelResponses),I=E?h.modelResponses:[],T=[];l.push({id:h.responseId,startedAt:y,completedAt:b,model:_,prompt:h.input.text,status:v,responseIds:T}),a.push({role:"user",timestamp:y,content:h.input.text});let k=Array.isArray(h.toolEvents)&&h.toolEvents.length>0;if(!E&&!k){let S=h.usage??{},R=tv({...h,usage:S});Object.keys(R.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:h.responseId,values:R.rawUsage}]),T.push(h.responseId),c.push({response_id:h.responseId,timestamp:(b??y).toISOString(),model:_??null,model_provider:typeof h.provider=="string"?h.provider:null,tokens:R.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(h.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:h.responseId,ref:null,bytes:Buffer.byteLength(h.input.text,"utf8"),basis:"input_text"}],pricing_facts:R.pricingFacts}),v!=="complete"&&!h.usage&&(u=!0),typeof h.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:h.output.text,model:_});continue}let N=new Map,C=new Map,O=new Set,w=[];for(let S of I){if(!S||typeof S!="object"||typeof S.responseId!="string"||!S.responseId){u=!0;continue}if(T.includes(S.responseId)){u=!0;continue}let R=S,x=w.length;w.push({response:R,index:x,filesRead:[],filesWritten:[],io:[]}),T.push(S.responseId),g.has(S.responseId)&&(u=!0),g.add(S.responseId),R.toolCalls!==void 0&&!Array.isArray(R.toolCalls)&&(u=!0,w[x].io.push({direction:"read",kind:"unattributed",id:S.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:S.responseId,ref:null,bytes:null,basis:"unknown"}));for(let A of Array.isArray(R.toolCalls)?R.toolCalls:[]){let M=Q_(A),P=cm(A);if(M)N.set(M,x),C.set(M,P);else{u=!0;let U=P==="list_directory"||P==="read_file"||P==="webget"||P==="shell"||P==="tool",F=P==="write_file"||P==="shell"||P==="tool";U&&w[x].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),F&&w[x].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}T.length===0&&I.length>0&&(u=!0);for(let S of Array.isArray(h.toolEvents)?h.toolEvents:[]){let R=S&&typeof S=="object"?S:{},x=Q_(R),A=x?N.get(x):void 0,M=cm(R),P=Z_(R.result),U=R.status==="failed"||R.error!==void 0;if(R.type==="tool_call"?a.push({role:"tool_use",timestamp:s(R?.timestamp)??y,content:fl(R?.input??R?.args),toolName:M,toolInput:fl(R?.input??R?.args),toolInputData:Z_(R?.input??R?.args)??void 0,...x?{toolCallId:x}:{}}):a.push({role:"tool_result",timestamp:s(R?.timestamp)??b??y,content:fl(U?R?.error:R?.result),toolName:M,...x?{toolCallId:x}:{}}),A===void 0){u=!0;continue}let F=w[A];(R.type==="tool_result"||U||R.result!==void 0)&&O.add(x);let ee=P?.path,q=Z(P?.bytesRead??P?.bytesWritten);R.type!=="tool_call"&&(M==="read_file"&&!U&&typeof ee=="string"&&q!==null?F.filesRead.push({path:ee,bytes:q}):M==="write_file"&&!U&&typeof ee=="string"&&q!==null?F.filesWritten.push({path:ee,bytes:q}):M==="webget"&&!U&&q!==null?F.io.push({direction:"read",kind:"web",id:x,ref:ev(P?.finalUrl??P?.url),bytes:q,basis:"certified_counter"}):M==="shell"||U?(M!=="write_file"&&F.io.push({direction:"read",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"}),(M==="shell"||M==="write_file")&&F.io.push({direction:"write",kind:"unattributed",id:x,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:x,ref:M==="webget"?ev(P?.finalUrl??P?.url):null,bytes:null,basis:"unknown"}):M==="write_file"?F.io.push({direction:"write",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"}):F.io.push({direction:"read",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:x,ref:null,bytes:null,basis:"unknown"}))}for(let[S,R]of C)if(!O.has(S)){let x=w[N.get(S)],A=R==="list_directory"||R==="read_file"||R==="webget"||R==="shell",M=R==="write_file"||R==="shell";A&&x.io.push({direction:"read",kind:"unattributed",id:S,ref:null,bytes:null,basis:"unknown"}),M&&x.io.push({direction:"write",kind:"unattributed",id:S,ref:null,bytes:null,basis:"unknown"}),u=!0}for(let S of w){let R=S.response,x=tv(R),A=s(R.completedAt??R.startedAt)??b??y;new Set((Array.isArray(R.toolCalls)?R.toolCalls:[]).map(F=>cm(F))).has("shell")&&!S.io.some(F=>F.kind==="unattributed"&&F.direction==="read")&&S.io.push({direction:"read",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"}),S.index===0&&S.io.unshift({direction:"read",kind:"prompt",id:h.responseId,ref:null,bytes:Buffer.byteLength(h.input.text,"utf8"),basis:"input_text"});let P=S.io.some(F=>F.direction==="read"&&F.bytes===null),U=S.io.some(F=>F.direction==="write"&&F.bytes===null);if(c.push({response_id:R.responseId,timestamp:A.toISOString(),model:typeof R.model=="string"?R.model:null,model_provider:typeof R.provider=="string"?R.provider:typeof h.provider=="string"?h.provider:null,tokens:x.tokens,files_read:P?null:S.filesRead,files_written:U?null:S.filesWritten,read_bytes:P?null:S.filesRead.reduce((F,ee)=>F+(ee.bytes??0),0)+S.io.filter(F=>F.direction==="read").reduce((F,ee)=>F+(ee.bytes??0),0),write_bytes:U?null:S.filesWritten.reduce((F,ee)=>F+(ee.bytes??0),0)+S.io.filter(F=>F.direction==="write").reduce((F,ee)=>F+(ee.bytes??0),0),external_io:S.io,pricing_facts:x.pricingFacts}),Object.keys(x.rawUsage).length){let F=l.at(-1);F.rawUsage=[...F.rawUsage??[],{responseId:R.responseId,values:x.rawUsage}]}}l.at(-1).responseIds=T,T.length!==I.length&&(u=!0),typeof h.output?.text=="string"&&a.push({role:"assistant",timestamp:b??y,content:h.output.text,model:_})}}let m=a.filter(f=>f.role==="user").map(f=>f.content),p=Xs(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 yl(t){return{provider:"miniplayer",root:Js(hl(t),"sessions"),revision:"miniplayer-data-v3",sessionId(e){let n=MO(e,".json");return e.endsWith(".json")&&nv.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:rv(i,n,r)}catch{return null}}}}var nv,gl,_l=L(()=>{"use strict";dl();We();$n();nv=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;gl=class{name="miniplayer";home;constructor(e={}){this.home=hl(e.miniplayerHome)}getWatchPaths(){return[{directory:Js(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await OO(Js(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(!nv.test(e))return null;let n=Js(this.home,"sessions",`${e}.json`);try{return(await Y_(n)).isFile()?n:null}catch{return null}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;try{let r=rv(JSON.parse(await z_(n,"utf8")),e,n);if(!r)return null;let s="complete";try{let i=JSON.parse(await z_(`${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 Y_(`${n}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(r){if(r.code!=="ENOENT")throw r}return await LO(n),!0}}});import{createHash as DO}from"node:crypto";import{createRequire as FO}from"node:module";import{readdir as $O,realpath as jO}from"node:fs/promises";import{basename as sv,dirname as UO,join as iv,resolve as ov}from"node:path";function BO(){return HO("node:sqlite").DatabaseSync}function WO(){return process.env.HOME||process.env.USERPROFILE||""}function ss(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 gn(t,e){return t.find(n=>n.field===e)}function qO(t){let e=new Map;for(let n of t){if(n.field!==20||n.bytes===void 0)continue;let r=ss(n.bytes),s=gn(r,1)?.bytes,i=gn(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 XO(t){let e=gn(ss(t),5)?.bytes;if(e===void 0)return null;let n=gn(ss(e),1)?.bytes;if(n===void 0)return null;let r=ss(n),s=gn(r,1)?.varint;if(s===void 0)return null;let i=gn(r,2)?.varint??0,o=s*1e3+Math.floor(i/1e6),a=new Date(o);return Number.isFinite(a.getTime())?a.toISOString():null}function GO(t){let e=gn(t,4)?.bytes,n=e!==void 0?ss(e):[],r=s=>{let i=gn(n,s)?.varint;return i===void 0?null:Z(i)};return{tokens:{input_uncached:r(2),input_cached:r(5),input_cache_write:r(4),output:r(3)},thinkingOutputTokens:r(9)}}function JO(t){let e=gn(ss(t),1)?.bytes;if(e===void 0)return null;let n=ss(e),r=qO(n),s=r.get("request_id");if(s===void 0||s.length===0)return null;let i=gn(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}=GO(n);return{requestId:s,model:o,lastStepIndex:c,tokens:u,thinkingOutputTokens:d}}function av(t,e){fe(e);let n=t.prepare("SELECT COALESCE(SUM(LENGTH(CAST(data AS BLOB))),0) AS total FROM gen_metadata").get(),r=Z(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=DO("sha256");i.update("rev:").update(vl).update(`
|
|
480
480
|
`);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(`
|
|
481
481
|
`);let p=JO(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(`
|
|
482
|
-
`);let g=XO(f);g!==null&&c.set(d,g)}return{revision:`${oo}+${vl}:sha256:${i.digest("hex")}`,generations:o,timestamps:c}}function VO(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:
|
|
483
|
-
`)){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 bL(t){if(typeof t=="string")try{return J(JSON.parse(t))}catch{return null}return J(t)}function mv(t,e){return typeof t!="number"||typeof e!="number"?null:`${t}\0${e}`}function wL(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),g=J(f?.usage),h=mv(p?.turn,p?.step);g&&h!==null&&typeof p?.turn=="number"&&typeof p?.step=="number"&&a.set(h,{turn:p.turn,step:p.step,usage:g,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 g=typeof p?.id=="string"&&p.id?p.id:null;i.push({id:g,bytes:hL(p?.content)});continue}if(m.type==="assistant/message"){let f=J(p?.message),g=J(f?.source),h=typeof f?.id=="string"&&f.id?f.id:null,y=mv(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=h}if(b===null)return{status:"partial"};let _=dv(J(p?.usage)),v=s.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Lt(typeof m.time=="number"?m.time:null),model:(typeof g?.model=="string"&&g.model?g.model:null)??c,tokens:_??{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,reasoning:null,provider:typeof g?.provider=="string"&&g.provider?g.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=Z(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 g=typeof p?.callId=="string"&&p.callId?p.callId:null,h=typeof p?.name=="string"?p.name.toLowerCase():"",y=bL(p?.arguments),b=(typeof y?.file_path=="string"&&y.file_path?y.file_path:null)??(typeof y?.path=="string"&&y.path?y.path:null);dL.has(h)?b!==null?f.obs.record(g??"","read",b,null):Le(f.io,g):mL.has(h)?b!==null?f.obs.record(g??"","written",b,Ws(y)):Le(f.io,g):fL(h)||Le(f.io,g);continue}}for(let[m,{turn:p,step:f,usage:g,time:h}]of a){if(o.has(m))continue;r.signal.throwIfAborted();let y=dv(g),b=new Ot;Le(b,null);let _={meta:{response_id:`dsh:turn-step:${p}/${f}`,timestamp:Lt(typeof h=="number"?h:null),model:c,tokens:y??{...yt},files_read:[],files_written:[]},obs:new Nt,io:b,reasoning:Z(g.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:g,provider:h}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:lt(y,_,"read"),write_bytes:lt(b,_,"written"),model_provider:l??h,pricing_facts:pn({reasoning:g??void 0},m.tokens.output,m.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:d}}async function EL(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c,u){r.signal.throwIfAborted();let d=await oL(c,{withFileTypes:!0}).catch(()=>[]);d.sort((m,p)=>we(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=pv(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()&&gv(m.name)){let f=await aL(p).catch(()=>fv(p));(s===null||we(f,s)>0)&&i.push(f)}}}return await l(t,0),{paths:i.sort(we),truncated:a}}function hv(t={}){return new mm(t)}var fr,cL,uL,dL,mL,pL,mm,yv=L(()=>{"use strict";$n();wl();fr="dsh",cL=lL.zstdDecompressSync;uL=5e5,dL=new Set(["read","read_image"]),mL=new Set(["write","edit"]),pL=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"]);mm=class{sessionsDir;maxDiscoveryTraversalVisits;constructor(e={}){let n=e.dshHome??process.env.DSH_HOME??pv(gL(),".dsh");this.sessionsDir=fv(n,"sessions"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):uL}async discover(e,n,r=null){fe(e);let{paths:s,truncated:i}=await EL(this.sessionsDir,n,this.maxDiscoveryTraversalVisits,e,r);return{sources:s.map(o=>({provider:fr,sessionid:dm(uv(o)),source_id:o})),truncated:i}}matches(e,n){return gv(dm(n))&&dm(uv(n))===e.sessionid}async inspect(e,n){if(fe(n),e.provider!==fr)return{status:"unsupported"};let r=await Ge(e.source_id,[this.sessionsDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(fe(r),e.provider!==fr)return{status:"unsupported"};let s=await Ge(e.source_id,[this.sessionsDir]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await _t(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let{text:o,truncated:a}=_L(i.data,r);return a?{status:"partial"}:wL(vL(o),e,n,r)}}});import{readdir as TL,realpath as SL}from"node:fs/promises";import{basename as El,dirname as kL,join as pm,resolve as _v}from"node:path";function NL(){return process.env.HOME||process.env.USERPROFILE||""}function OL(){let t=NL();return[pm(t,".qwen","projects"),pm(t,".qwen.bk1","projects")]}function LL(t){return t.type!=="system"||t.subtype!=="ui_telemetry"?null:J(J(t.systemPayload)?.uiEvent)}function ML(t){let e=t["event.name"];return typeof e=="string"&&e.length>0?e:null}function PL(t){let e=Z(t.input_token_count),n=Z(t.output_token_count),r=Z(t.cached_content_token_count),s=Z(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:Z(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 DL(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 FL(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=DL(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 $L(t,e,n,r){let{promptBytes:s,resolve:i}=FL(t),o=new Set,a=new Map,l=0;for(let u of t){r.signal.throwIfAborted();let d=LL(u);if(d===null)continue;let m=ML(d);if(m===RL){let b=typeof d.response_id=="string"&&d.response_id?d.response_id:null;if(b===null)return{status:"unsupported"};let _=PL(d);if(_===null)return{status:"partial"};let v=a.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Lt(d["event.timestamp"]??u.timestamp),model:typeof d.model=="string"&&d.model?d.model:null,tokens:{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,thoughts:null},a.set(b,v),a.size>r.maxRows)return{status:"partial"};let I=typeof u.uuid=="string"&&u.uuid?u.uuid:null,T=I===null?{kind:"broken"}:i(I);if(T.kind==="broken")v.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"});else if(T.kind==="found"&&!o.has(T.uuid)){o.add(T.uuid);let k=s.get(T.uuid)??null;v.io.record({direction:"read",kind:"prompt",id:T.uuid,ref:null,bytes:k,basis:k===null?"unknown":"input_text"})}}v.meta.tokens=_,typeof d.model=="string"&&d.model&&(v.meta.model=d.model);let E=Z(d.thoughts_token_count);E!==null&&(v.thoughts=E);continue}if(m!==IL)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 g=typeof d.function_name=="string"?d.function_name.toLowerCase():"",h=J(d.function_args),y=`tool-${l++}`;if(xL.has(g)){let b=typeof h?.file_path=="string"?h.file_path:null;b!==null?f.obs.record(y,"read",b,null):Le(f.io,y)}else if(AL.has(g)){let b=typeof h?.file_path=="string"?h.file_path:null;b!==null?f.obs.record(y,"written",b,Ws(h)):Le(f.io,y)}else mr(g)||Le(f.io,y)}let c=[];for(let{meta:u,obs:d,io:m,thoughts:p}of a.values()){let f=d.files("read"),g=d.files("written"),h=m.entries();c.push({...u,files_read:f,files_written:g,external_io:h,read_bytes:lt(f,h,"read"),write_bytes:lt(g,h,"written"),model_provider:null,pricing_facts:pn({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 jL(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c){r.signal.throwIfAborted();let u=await TL(c,{withFileTypes:!0}).catch(()=>[]);u.sort((d,m)=>we(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=pm(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")&&El(c)===vv){let p=await SL(m).catch(()=>_v(m));(s===null||we(p,s)>0)&&i.push(p)}}}return await l(t),{paths:i.sort(we),truncated:a}}function UL(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 bv(t={}){return new fm(t)}var gr,RL,IL,vv,xL,AL,CL,fm,wv=L(()=>{"use strict";$n();gr="qwen",RL="qwen-code.api_response",IL="qwen-code.tool_call",vv="chats",xL=new Set(["read_file"]),AL=new Set(["write_file"]),CL=5e5;fm=class{roots;maxDiscoveryTraversalVisits;constructor(e={}){this.roots=(e.qwenProjectsDirs??OL()).map(n=>_v(n)),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):CL}async discover(e,n,r=null){fe(e);let s=new Map,i=!1;for(let a of this.roots){e.signal.throwIfAborted();let l=await jL(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(we).slice(0,n).map(a=>({provider:gr,sessionid:El(a,".jsonl"),source_id:a})),truncated:i}}matches(e,n){return El(n,".jsonl")===e.sessionid&&El(kL(n))===vv}async inspect(e,n){if(fe(n),e.provider!==gr)return{status:"unsupported"};let r=await Ge(e.source_id,[...this.roots]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(fe(r),e.provider!==gr)return{status:"unsupported"};let s=await Ge(e.source_id,[...this.roots]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await _t(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let o=ul(i.data,r);return o?UL(o,e.sessionid)?$L(o,e,n,r):{status:"unavailable"}:{status:"partial"}}}});import{createHash as HL}from"node:crypto";import{createRequire as BL}from"node:module";import{join as co,resolve as gm}from"node:path";function qL(){return WL("node:sqlite").DatabaseSync}function Ev(){return process.env.HOME||process.env.USERPROFILE||""}function XL(){let t=process.env.XDG_DATA_HOME||co(Ev(),".local","share"),e=process.env.XDG_CONFIG_HOME||co(Ev(),".config");return[co(t,"opencode","opencode.db"),co(t,"opencode","opencode-local.db"),co(e,"opencode","opencode.db")]}function zL(t){if(typeof t!="string")return null;let e=t.toLowerCase();return e==="apply_patch"?"apply_patch":GL.includes(e)?"read":JL.includes(e)?"written":null}function Tv(t,e=VL){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 YL(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 QL(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(`
|
|
482
|
+
`);let g=XO(f);g!==null&&c.set(d,g)}return{revision:`${oo}+${vl}:sha256:${i.digest("hex")}`,generations:o,timestamps:c}}function VO(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:fn({reasoning:e.thinkingOutputTokens},e.tokens.output,e.tokens.input_cache_write)}))}function lv(t={}){return new ao(t)}var pr,vl,HO,ao,um=L(()=>{"use strict";$n();pr="agy",vl="agy-tokens-v1",HO=FO(import.meta.url);ao=class{conversationsDir;sqliteBusyTimeoutMs;constructor(e={}){this.conversationsDir=ov(e.agyConversationsDir??iv(WO(),".gemini","antigravity-cli","conversations")),this.sqliteBusyTimeoutMs=e.sqliteBusyTimeoutMs??5e3}async discover(e,n,r=null){fe(e);let s=await $O(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 jO(iv(this.conversationsDir,o.name)).catch(()=>null);a!==null&&(r!==null&&we(a,r)<=0||i.push(a))}return i.sort(we),{sources:i.slice(0,n).map(o=>({provider:pr,sessionid:sv(o,".db"),source_id:o})),truncated:!1}}async open(e){let n=await Ge(e.source_id,[this.conversationsDir]);if(n===null||sv(n,".db")!==e.sessionid||ov(UO(n))!==this.conversationsDir)return null;try{let r=new(BO())(n,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.sqliteBusyTimeoutMs}`),r}catch{return null}}async inspect(e,n){if(fe(n),e.provider!==pr)return{status:"unsupported"};let r=await this.open(e);if(r===null)return{status:"unavailable"};try{let s=av(r,n);return s?{status:"ready",revision:s.revision}:{status:"partial"}}catch{return{status:"unsupported"}}finally{r.close()}}async read(e,n,r){if(fe(r),e.provider!==pr)return{status:"unsupported"};let s=await this.open(e);if(s===null)return{status:"unavailable"};try{s.exec("BEGIN");let i=av(s,r);if(i===null||i.revision!==n)return s.exec("ROLLBACK"),{status:"partial"};let o=VO(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 KO from"node:zlib";function sL(t,e){return t[e]===YO&&t[e+1]===QO&&t[e+2]===ZO&&t[e+3]===eL}function cv(t,e){return(t[e]&240)===80&&t[e+1]===tL&&t[e+2]===nL&&t[e+3]===rL}function iL(t,e){if(cv(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!sL(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 lo(t){let e=[],n=0;for(;n+4<=t.length;){let r=iL(t,n);if(r===void 0||r<=0)break;e.push(t.subarray(n,n+r)),n+=r}return e}function bl(t){let e=[];for(let n of lo(t))cv(n,0)||e.push(zO(n).toString("utf8"));return e.join("")}var zO,YO,QO,ZO,eL,tL,nL,rL,wl=L(()=>{"use strict";zO=KO.zstdDecompressSync,YO=40,QO=181,ZO=47,eL=253,tL=42,nL=77,rL=24});import{readdir as oL,realpath as aL}from"node:fs/promises";import{basename as dm,dirname as uv,join as pv,resolve as fv}from"node:path";import lL from"node:zlib";function gv(t){return/^session(\.v\d+)?\.jsonl\.zstd$/.test(t)}function fL(t){return pL.has(t)||mr(t)}function gL(){return process.env.HOME||process.env.USERPROFILE||""}function hL(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=J(r);s?.type==="text"&&typeof s.text=="string"&&(e+=Buffer.byteLength(s.text,"utf8"),n=!0)}return n?e:null}function dv(t){if(!t)return null;let e=Z(t.inputTokens),n=Z(t.outputTokens);if(e===null||n===null)return null;let r=t.cacheReadTokens===void 0?null:Z(t.cacheReadTokens);return{input_uncached:e,input_cached:r,input_cache_write:null,output:n}}function yL(t){return t.length>=4&&(t[0]&240)===80&&t[1]===42&&t[2]===77&&t[3]===24}function _L(t,e){let n=lo(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(),yL(o))continue;if(o.length>e.maxBytes)return{text:s.join(""),truncated:!0};let a;try{a=cL(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 vL(t){let e=[];for(let n of t.split(`
|
|
483
|
+
`)){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 bL(t){if(typeof t=="string")try{return J(JSON.parse(t))}catch{return null}return J(t)}function mv(t,e){return typeof t!="number"||typeof e!="number"?null:`${t}\0${e}`}function wL(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),g=J(f?.usage),h=mv(p?.turn,p?.step);g&&h!==null&&typeof p?.turn=="number"&&typeof p?.step=="number"&&a.set(h,{turn:p.turn,step:p.step,usage:g,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 g=typeof p?.id=="string"&&p.id?p.id:null;i.push({id:g,bytes:hL(p?.content)});continue}if(m.type==="assistant/message"){let f=J(p?.message),g=J(f?.source),h=typeof f?.id=="string"&&f.id?f.id:null,y=mv(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=h}if(b===null)return{status:"partial"};let _=dv(J(p?.usage)),v=s.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Lt(typeof m.time=="number"?m.time:null),model:(typeof g?.model=="string"&&g.model?g.model:null)??c,tokens:_??{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,reasoning:null,provider:typeof g?.provider=="string"&&g.provider?g.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=Z(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 g=typeof p?.callId=="string"&&p.callId?p.callId:null,h=typeof p?.name=="string"?p.name.toLowerCase():"",y=bL(p?.arguments),b=(typeof y?.file_path=="string"&&y.file_path?y.file_path:null)??(typeof y?.path=="string"&&y.path?y.path:null);dL.has(h)?b!==null?f.obs.record(g??"","read",b,null):Le(f.io,g):mL.has(h)?b!==null?f.obs.record(g??"","written",b,Ws(y)):Le(f.io,g):fL(h)||Le(f.io,g);continue}}for(let[m,{turn:p,step:f,usage:g,time:h}]of a){if(o.has(m))continue;r.signal.throwIfAborted();let y=dv(g),b=new Ot;Le(b,null);let _={meta:{response_id:`dsh:turn-step:${p}/${f}`,timestamp:Lt(typeof h=="number"?h:null),model:c,tokens:y??{...yt},files_read:[],files_written:[]},obs:new Nt,io:b,reasoning:Z(g.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:g,provider:h}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:lt(y,_,"read"),write_bytes:lt(b,_,"written"),model_provider:l??h,pricing_facts:fn({reasoning:g??void 0},m.tokens.output,m.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:d}}async function EL(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c,u){r.signal.throwIfAborted();let d=await oL(c,{withFileTypes:!0}).catch(()=>[]);d.sort((m,p)=>we(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=pv(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()&&gv(m.name)){let f=await aL(p).catch(()=>fv(p));(s===null||we(f,s)>0)&&i.push(f)}}}return await l(t,0),{paths:i.sort(we),truncated:a}}function hv(t={}){return new mm(t)}var fr,cL,uL,dL,mL,pL,mm,yv=L(()=>{"use strict";$n();wl();fr="dsh",cL=lL.zstdDecompressSync;uL=5e5,dL=new Set(["read","read_image"]),mL=new Set(["write","edit"]),pL=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"]);mm=class{sessionsDir;maxDiscoveryTraversalVisits;constructor(e={}){let n=e.dshHome??process.env.DSH_HOME??pv(gL(),".dsh");this.sessionsDir=fv(n,"sessions"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):uL}async discover(e,n,r=null){fe(e);let{paths:s,truncated:i}=await EL(this.sessionsDir,n,this.maxDiscoveryTraversalVisits,e,r);return{sources:s.map(o=>({provider:fr,sessionid:dm(uv(o)),source_id:o})),truncated:i}}matches(e,n){return gv(dm(n))&&dm(uv(n))===e.sessionid}async inspect(e,n){if(fe(n),e.provider!==fr)return{status:"unsupported"};let r=await Ge(e.source_id,[this.sessionsDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(fe(r),e.provider!==fr)return{status:"unsupported"};let s=await Ge(e.source_id,[this.sessionsDir]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await _t(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let{text:o,truncated:a}=_L(i.data,r);return a?{status:"partial"}:wL(vL(o),e,n,r)}}});import{readdir as TL,realpath as SL}from"node:fs/promises";import{basename as El,dirname as kL,join as pm,resolve as _v}from"node:path";function NL(){return process.env.HOME||process.env.USERPROFILE||""}function OL(){let t=NL();return[pm(t,".qwen","projects"),pm(t,".qwen.bk1","projects")]}function LL(t){return t.type!=="system"||t.subtype!=="ui_telemetry"?null:J(J(t.systemPayload)?.uiEvent)}function ML(t){let e=t["event.name"];return typeof e=="string"&&e.length>0?e:null}function PL(t){let e=Z(t.input_token_count),n=Z(t.output_token_count),r=Z(t.cached_content_token_count),s=Z(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:Z(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 DL(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 FL(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=DL(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 $L(t,e,n,r){let{promptBytes:s,resolve:i}=FL(t),o=new Set,a=new Map,l=0;for(let u of t){r.signal.throwIfAborted();let d=LL(u);if(d===null)continue;let m=ML(d);if(m===RL){let b=typeof d.response_id=="string"&&d.response_id?d.response_id:null;if(b===null)return{status:"unsupported"};let _=PL(d);if(_===null)return{status:"partial"};let v=a.get(b);if(!v){if(v={meta:{response_id:b,timestamp:Lt(d["event.timestamp"]??u.timestamp),model:typeof d.model=="string"&&d.model?d.model:null,tokens:{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,thoughts:null},a.set(b,v),a.size>r.maxRows)return{status:"partial"};let I=typeof u.uuid=="string"&&u.uuid?u.uuid:null,T=I===null?{kind:"broken"}:i(I);if(T.kind==="broken")v.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"});else if(T.kind==="found"&&!o.has(T.uuid)){o.add(T.uuid);let k=s.get(T.uuid)??null;v.io.record({direction:"read",kind:"prompt",id:T.uuid,ref:null,bytes:k,basis:k===null?"unknown":"input_text"})}}v.meta.tokens=_,typeof d.model=="string"&&d.model&&(v.meta.model=d.model);let E=Z(d.thoughts_token_count);E!==null&&(v.thoughts=E);continue}if(m!==IL)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 g=typeof d.function_name=="string"?d.function_name.toLowerCase():"",h=J(d.function_args),y=`tool-${l++}`;if(xL.has(g)){let b=typeof h?.file_path=="string"?h.file_path:null;b!==null?f.obs.record(y,"read",b,null):Le(f.io,y)}else if(AL.has(g)){let b=typeof h?.file_path=="string"?h.file_path:null;b!==null?f.obs.record(y,"written",b,Ws(h)):Le(f.io,y)}else mr(g)||Le(f.io,y)}let c=[];for(let{meta:u,obs:d,io:m,thoughts:p}of a.values()){let f=d.files("read"),g=d.files("written"),h=m.entries();c.push({...u,files_read:f,files_written:g,external_io:h,read_bytes:lt(f,h,"read"),write_bytes:lt(g,h,"written"),model_provider:null,pricing_facts:fn({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 jL(t,e,n,r,s){let i=[],o=0,a=!1;async function l(c){r.signal.throwIfAborted();let u=await TL(c,{withFileTypes:!0}).catch(()=>[]);u.sort((d,m)=>we(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=pm(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")&&El(c)===vv){let p=await SL(m).catch(()=>_v(m));(s===null||we(p,s)>0)&&i.push(p)}}}return await l(t),{paths:i.sort(we),truncated:a}}function UL(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 bv(t={}){return new fm(t)}var gr,RL,IL,vv,xL,AL,CL,fm,wv=L(()=>{"use strict";$n();gr="qwen",RL="qwen-code.api_response",IL="qwen-code.tool_call",vv="chats",xL=new Set(["read_file"]),AL=new Set(["write_file"]),CL=5e5;fm=class{roots;maxDiscoveryTraversalVisits;constructor(e={}){this.roots=(e.qwenProjectsDirs??OL()).map(n=>_v(n)),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):CL}async discover(e,n,r=null){fe(e);let s=new Map,i=!1;for(let a of this.roots){e.signal.throwIfAborted();let l=await jL(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(we).slice(0,n).map(a=>({provider:gr,sessionid:El(a,".jsonl"),source_id:a})),truncated:i}}matches(e,n){return El(n,".jsonl")===e.sessionid&&El(kL(n))===vv}async inspect(e,n){if(fe(n),e.provider!==gr)return{status:"unsupported"};let r=await Ge(e.source_id,[...this.roots]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(fe(r),e.provider!==gr)return{status:"unsupported"};let s=await Ge(e.source_id,[...this.roots]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await _t(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let o=ul(i.data,r);return o?UL(o,e.sessionid)?$L(o,e,n,r):{status:"unavailable"}:{status:"partial"}}}});import{createHash as HL}from"node:crypto";import{createRequire as BL}from"node:module";import{join as co,resolve as gm}from"node:path";function qL(){return WL("node:sqlite").DatabaseSync}function Ev(){return process.env.HOME||process.env.USERPROFILE||""}function XL(){let t=process.env.XDG_DATA_HOME||co(Ev(),".local","share"),e=process.env.XDG_CONFIG_HOME||co(Ev(),".config");return[co(t,"opencode","opencode.db"),co(t,"opencode","opencode-local.db"),co(e,"opencode","opencode.db")]}function zL(t){if(typeof t!="string")return null;let e=t.toLowerCase();return e==="apply_patch"?"apply_patch":GL.includes(e)?"read":JL.includes(e)?"written":null}function Tv(t,e=VL){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 YL(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 QL(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(`
|
|
484
484
|
`)){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 ZL(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 eM(t,e=!1){let n=J(t);if(!n)return{...yt};let r=n.input===void 0?e?null:0:Z(n.input),s=n.output===void 0?e?null:0:Z(n.output),i=n.reasoning===void 0?e?null:0:Z(n.reasoning),o=J(n.cache),a=o?.read===void 0?e?null:0:Z(o.read),l=o?.write===void 0?e?null:0:Z(o.write);return e&&r===0&&s===0&&i===0&&a===0&&l===0?{...yt}: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?{...yt}:r+s+i+a+l===0?{...yt}:{input_uncached:r+l,input_cached:a,input_cache_write:l,output:s+i}}function Sv(t,e,n){fe(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=Z(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=HL("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(`
|
|
485
|
-
`)}return{revision:`${oo}:sha256:${c.digest("hex")}`,messages:o,parts:a}}function tM(t){let e=0,n=!1,r=!1;for(let s of t){let i;try{i=J(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&&!KL.has(o)&&(r=!0))}return n?e:r?"unknown":null}function nM(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=J(JSON.parse(c.data))}catch{continue}if(u?.role!=="user")continue;let d=tM(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=J(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=J(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 Nt,m=new Ot,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 T of s.get(c.id)??[]){let k;try{k=J(JSON.parse(T.data))}catch{return{status:"partial"}}if(k?.type!=="tool")continue;let N=typeof k.tool=="string"?k.tool.toLowerCase():"",C=zL(k.tool),O=J(k.state),w=J(O?.input),S=typeof k.callID=="string"&&k.callID?k.callID:typeof O?.callID=="string"&&O.callID?O.callID:T.id;if(C==="written")d.record(S,"written",Tv(w),YL(w));else if(C==="apply_patch"){let R=w?.patchText;if(typeof R=="string")for(let x of QL(R))d.record(S,"written",x.path,x.bytes);else Le(m,S)}else if(C==="read"){let R=Tv(w,["filePath","path","file","file_path"]);if(R===null)continue;let x=null;if(O?.status==="completed"){let A=J(J(O.metadata)?.display);A?.type==="file"&&typeof A.text=="string"&&(x=Buffer.byteLength(A.text,"utf8"))}d.record(S,"read",R,x)}else if(N==="webfetch"){p+=1;let R=O?.status==="completed"?O.output:void 0;m.record({direction:"read",kind:"web",id:S,ref:ZL(w?.url),bytes:typeof R=="string"?Buffer.byteLength(R,"utf8"):null,basis:typeof R=="string"?"normalized_content":"unknown"})}else mr(k.tool)||Le(m,S)}let g=J(u.time),h=J(u.model)?.modelID??u.modelID,y=eM(u.tokens,r.requireBillingCounters),b=J(u.tokens),_=d.files("read"),v=d.files("written"),E=m.entries(),I=
|
|
486
|
-
`)){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 uM(t){let e=t?.content;return typeof e=="string"?Buffer.byteLength(e,"utf8"):null}function dM(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?Z(d.count):null,input_tokens:u?Z(u.inputTokens):null,input_other_tokens:p?Z(p.tokenCount):null,cache_read_tokens:u?Z(u.cacheReadTokens):null,cache_write_tokens:u?Z(u.cacheWriteTokens):null,output_tokens:u?Z(u.outputTokens):null,reasoning_tokens:u?Z(u.reasoningTokens):null})}s.sort((a,l)=>we(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 mM(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=uM(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=Lt(d.timestamp),{entry:_,incomplete:v}=dM(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,g=i.get(p);if(!g){if(g={meta:{response_id:p,timestamp:Lt(d.timestamp),model:typeof m.model=="string"&&m.model?m.model:null,tokens:{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,promptRecorded:!1},i.set(p,g),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);g.io.record({direction:"read",kind:"prompt",id:f,ref:null,bytes:y,basis:y===null?"unknown":"input_text"}),g.promptRecorded=!0}}else g.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"})}let h=Z(m.outputTokens);if(h!==null&&(g.meta.tokens.output=(g.meta.tokens.output??0)+h),g.meta.model===null&&typeof m.model=="string"&&m.model&&(g.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 I=J(E),T=typeof I?.path=="string"?I.path:null,k=typeof I?.file_text=="string"?Buffer.byteLength(I.file_text,"utf8"):null;T!==null?g.obs.record(v??p,"written",T,k):Le(g.io,v)}else if(_==="apply_patch")if(typeof E=="string"){let I=cM(E);if(I.length>0)for(let T of I)g.obs.record(v??p,"written",T.path,T.bytes);else Le(g.io,v)}else Le(g.io,v);else if(lM.has(_)){let I=J(E),T=typeof I?.path=="string"?I.path:null;T!==null?g.obs.record(v??p,"read",T,null):Le(g.io,v)}else aM.has(_)||Le(g.io,v)}}let u=[];for(let{meta:d,obs:m,io:p}of i.values()){let f=m.files("read"),g=m.files("written"),h=p.entries();u.push({...d,files_read:f,files_written:g,external_io:h,read_bytes:lt(f,h,"read"),write_bytes:lt(g,h,"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 pM(){return process.env.HOME||process.env.USERPROFILE||""}function Cv(t={}){return new ym(t)}var hr,Av,aM,lM,ym,Nv=L(()=>{"use strict";$n();hr="copilot",Av="events.jsonl",aM=new Set(["report_intent"]),lM=new Set(["view"]);ym=class{sessionStateDir;constructor(e={}){this.sessionStateDir=xv(e.copilotSessionStateDir??Iv(pM(),".copilot","session-state"))}async discover(e,n,r=null){fe(e);let s;try{s=await rM(this.sessionStateDir)}catch{return{sources:[],truncated:!1}}let i=[];for(let o of s.sort(we)){e.signal.throwIfAborted();let a=Iv(this.sessionStateDir,o,Av);if(!(await iM(a).catch(()=>null))?.isFile())continue;let c=await sM(a).catch(()=>xv(a)),u={provider:hr,sessionid:o,source_id:c};r!==null&&we(`${c}\0${o}`,r)<=0||i.push(u)}return i.sort((o,a)=>we(`${o.source_id}\0${o.sessionid}`,`${a.source_id}\0${a.sessionid}`)),{sources:i.slice(0,n),truncated:!1}}matches(e,n){return Rv(n)===Av&&Rv(oM(n))===e.sessionid}async inspect(e,n){if(fe(n),e.provider!==hr)return{status:"unsupported"};let r=await Ge(e.source_id,[this.sessionStateDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(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(fe(r),e.provider!==hr)return{snapshot:{status:"unsupported"},sessionUsage:null};let s=await Ge(e.source_id,[this.sessionStateDir]);if(!s||!this.matches(e,s))return{snapshot:{status:"unavailable"},sessionUsage:null};let i=await _t(s,r).catch(()=>null);if(!i||i.revision!==n)return{snapshot:{status:"partial"},sessionUsage:null};let o=ul(i.data,r);return o?mM(o,e,n,r):{snapshot:{status:"partial"},sessionUsage:null}}}});import{readdir as Ov,readFile as fM,realpath as _m,stat as Lv}from"node:fs/promises";import{basename as po,dirname as Ks,isAbsolute as bm,join as Vs,relative as Dv,resolve as mo,sep as Fv}from"node:path";function wM(t){return bM.has(t)||mr(t)}function EM(){return process.env.HOME||process.env.USERPROFILE||""}function TM(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 Mv(t){let e=J(t);if(!e)return null;let n=Z(e.inputOther),r=Z(e.inputCacheRead),s=Z(e.inputCacheCreation),i=Z(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 SM(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 RM(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&&!gM.has(i))return{status:"unsupported"};let o=IM(e.source_id),a=new Map,l=new Map,c=[],u=new Set,d=new Set,m=null,p=!1,f=b=>`${o}/${b}`,g=(b,_)=>{let v=f(b),E=a.get(v);return E||(E={meta:{response_id:v,timestamp:Lt(typeof _=="number"?_:null),model:null,tokens:{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,turnStepKey:null,tokensSource:"none"},a.set(v,E)),E},h=(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,I=typeof b.promptId=="string"&&b.promptId?b.promptId:null;if(E!==null&&kM.has(E))continue;if(I!==null){if(u.has(I))continue;u.add(I)}E==="user"?c.push({bytes:SM(b.input),id:I}):c.push({bytes:null,id:I});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 I=Mv(b.usage);I&&(E.meta.tokens=I,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=g(v,b.time);if(a.size>r.maxRows)return{status:"partial"};if(d.add(v),h(E,_),c.length>0){for(let I of c)E.io.record({direction:"read",kind:"prompt",id:I.id,ref:null,bytes:I.bytes,basis:I.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=g(v,b.time);if(a.size>r.maxRows)return{status:"partial"};d.delete(v),m=v,h(E,_);let I=Mv(_.usage);I&&(E.meta.tokens=I),E.tokensSource="end",E.meta.timestamp===null&&(E.meta.timestamp=Lt(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=g(v,b.time);if(a.size>r.maxRows)return{status:"partial"};let I=typeof _.name=="string"?_.name.toLowerCase():"",T=typeof _.toolCallId=="string"&&_.toolCallId?_.toolCallId:null,k=J(_.args),N=typeof k?.path=="string"&&k.path?k.path:typeof k?.file_path=="string"&&k.file_path?k.file_path:null;_M.has(I)?N!==null?E.obs.record(T??"","read",N,null):Le(E.io,T):vM.has(I)?N!==null?E.obs.record(T??"","written",N,Ws(k)):Le(E.io,T):wM(I)||Le(E.io,T);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 I=_.files("read"),T=_.files("written"),k=v.entries();y.push({...b,files_read:I,files_written:T,external_io:k,read_bytes:lt(I,k,"read"),write_bytes:lt(T,k,"written"),model_provider:null,pricing_facts:pn({},b.tokens.output,b.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:y,...p?{capture_status:"partial"}:{}}}function vm(t){return po(t)===wm&&po(Ks(Ks(t)))===$v}function Pv(t){return po(Ks(Ks(Ks(t))))}function IM(t){return po(Ks(t))}function xM(t,e){let n=Dv(e,t);return n===""||!n.startsWith(`..${Fv}`)&&n!==".."&&!bm(n)}function AM(t){if(t instanceof Error&&t.name==="AbortError")throw t}function jv(t={}){return new fo(t)}var yr,wm,$v,gM,hM,yM,_M,vM,bM,kM,fo,Em=L(()=>{"use strict";$n();yr="kimi",wm="wire.jsonl",$v="agents",gM=new Set(["1.4","1.5"]),hM=5e5,yM=8*1024*1024,_M=new Set(["read"]),vM=new Set(["write","edit"]),bM=new Set(["todolist","tasklist","taskoutput","taskstop","waitfor","creategoal","updategoal","getgoal","enterplanmode","exitplanmode","agentswarm","agent","skill","croncreate","crondelete","cronlist"]);kM=new Set(["system_trigger","cron_job","task"]);fo=class{home;sessionsDir;indexPath;maxDiscoveryTraversalVisits;constructor(e={}){this.home=mo(e.kimiHome??process.env.KIMI_CODE_HOME??Vs(EM(),".kimi-code")),this.sessionsDir=Vs(this.home,"sessions"),this.indexPath=Vs(this.home,"session_index.jsonl"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):hM}async discover(e,n,r=null){fe(e);let s=new Set,i=!1,o=await _m(this.sessionsDir).catch(()=>mo(this.sessionsDir)),a=m=>{vm(m)&&xM(m,o)&&s.add(m)},l=0,c=async(m,p)=>{if(e.signal.throwIfAborted(),i)return;let f=await Ov(m,{withFileTypes:!0}).catch(()=>[]);f.sort((g,h)=>we(g.name,h.name));for(let g of f){if(e.signal.throwIfAborted(),l+=1,l>this.maxDiscoveryTraversalVisits){i=!0;return}let h=Vs(m,g.name);if(g.isDirectory()&&!g.isSymbolicLink()&&p<4){if(await c(h,p+1),i)return}else g.isFile()&&g.name===wm&&vm(h)&&a(await _m(h).catch(()=>mo(h)))}};await c(this.sessionsDir,0);try{await this.unionIndex(a,e)}catch(m){AM(m)}let u=[...s].sort(we);return{sources:(r===null?u:u.filter(m=>we(m,r)>0)).slice(0,n).map(m=>({provider:yr,sessionid:Pv(m),source_id:m})),truncated:i}}async unionIndex(e,n){let r=await Lv(this.indexPath).catch(()=>null);if(!r?.isFile()||r.size>yM)return;let s=await fM(this.indexPath,{signal:n.signal});for(let i of s.toString("utf8").split(`
|
|
485
|
+
`)}return{revision:`${oo}:sha256:${c.digest("hex")}`,messages:o,parts:a}}function tM(t){let e=0,n=!1,r=!1;for(let s of t){let i;try{i=J(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&&!KL.has(o)&&(r=!0))}return n?e:r?"unknown":null}function nM(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=J(JSON.parse(c.data))}catch{continue}if(u?.role!=="user")continue;let d=tM(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=J(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=J(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 Nt,m=new Ot,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 T of s.get(c.id)??[]){let k;try{k=J(JSON.parse(T.data))}catch{return{status:"partial"}}if(k?.type!=="tool")continue;let N=typeof k.tool=="string"?k.tool.toLowerCase():"",C=zL(k.tool),O=J(k.state),w=J(O?.input),S=typeof k.callID=="string"&&k.callID?k.callID:typeof O?.callID=="string"&&O.callID?O.callID:T.id;if(C==="written")d.record(S,"written",Tv(w),YL(w));else if(C==="apply_patch"){let R=w?.patchText;if(typeof R=="string")for(let x of QL(R))d.record(S,"written",x.path,x.bytes);else Le(m,S)}else if(C==="read"){let R=Tv(w,["filePath","path","file","file_path"]);if(R===null)continue;let x=null;if(O?.status==="completed"){let A=J(J(O.metadata)?.display);A?.type==="file"&&typeof A.text=="string"&&(x=Buffer.byteLength(A.text,"utf8"))}d.record(S,"read",R,x)}else if(N==="webfetch"){p+=1;let R=O?.status==="completed"?O.output:void 0;m.record({direction:"read",kind:"web",id:S,ref:ZL(w?.url),bytes:typeof R=="string"?Buffer.byteLength(R,"utf8"):null,basis:typeof R=="string"?"normalized_content":"unknown"})}else mr(k.tool)||Le(m,S)}let g=J(u.time),h=J(u.model)?.modelID??u.modelID,y=eM(u.tokens,r.requireBillingCounters),b=J(u.tokens),_=d.files("read"),v=d.files("written"),E=m.entries(),I=fn({reasoning:b?.reasoning,webFetch:p>0?p:void 0},y.output,y.input_cache_write);if(l.push({response_id:c.id,timestamp:Lt(g?.created??c.time_created),model:typeof h=="string"&&h?h:null,tokens:y,files_read:_,files_written:v,external_io:E,read_bytes:lt(_,E,"read"),write_bytes:lt(v,E,"written"),model_provider:typeof u.providerID=="string"&&u.providerID?u.providerID:null,pricing_facts:I}),l.length>r.maxRows)return{status:"partial"}}return{status:"complete",source:t,revision:e,checkpoint:e,responses:l}}function kv(t={}){return new uo(t)}var is,WL,GL,JL,VL,KL,uo,hm=L(()=>{"use strict";$n();is="opencode",WL=BL(import.meta.url);GL=["read","read_file","view","view_file","view_image"],JL=["write","write_file","edit","edit_file","multiedit","notebookedit","notebook_edit"],VL=["filePath","path","file","file_path","filepath","notebook_path","paths"],KL=new Set(["session-job-notification"]);uo=class{dbPaths;sqliteBusyTimeoutMs;constructor(e={}){this.dbPaths=(e.dbPaths??XL()).map(n=>gm(n)),this.sqliteBusyTimeoutMs=e.sqliteBusyTimeoutMs??5e3}openDb(e){if(!this.dbPaths.includes(gm(e)))return null;try{let n=new(qL())(e,{open:!0,readOnly:!0});return n.exec(`PRAGMA busy_timeout = ${this.sqliteBusyTimeoutMs}`),n}catch{return null}}async discover(e,n,r=null){fe(e);let s=new Map;for(let o of this.dbPaths){e.signal.throwIfAborted();let a=await Ge(o,[gm(o,"..")]);if(!a||r&&we(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:is,sessionid:d.id,source_id:a})}catch{}finally{l.close()}}return{sources:[...s.values()].sort((o,a)=>we(`${o.source_id}\0${o.sessionid}`,`${a.source_id}\0${a.sessionid}`)).slice(0,n),truncated:!1}}inspect(e,n){if(fe(n),e.provider!==is)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=Sv(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(fe(r),e.provider!==is)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=Sv(s,e.sessionid,r);if(!o||o.revision!==n)return s.exec("ROLLBACK"),{status:"partial"};let a=nM(e,n,o,r);return s.exec("COMMIT"),a}catch{try{s.exec("ROLLBACK")}catch{}return{status:"unsupported"}}finally{s.close()}}}});import{readdir as rM,realpath as sM,stat as iM}from"node:fs/promises";import{basename as Rv,dirname as oM,join as Iv,resolve as xv}from"node:path";function cM(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(`
|
|
486
|
+
`)){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 uM(t){let e=t?.content;return typeof e=="string"?Buffer.byteLength(e,"utf8"):null}function dM(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?Z(d.count):null,input_tokens:u?Z(u.inputTokens):null,input_other_tokens:p?Z(p.tokenCount):null,cache_read_tokens:u?Z(u.cacheReadTokens):null,cache_write_tokens:u?Z(u.cacheWriteTokens):null,output_tokens:u?Z(u.outputTokens):null,reasoning_tokens:u?Z(u.reasoningTokens):null})}s.sort((a,l)=>we(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 mM(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=uM(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=Lt(d.timestamp),{entry:_,incomplete:v}=dM(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,g=i.get(p);if(!g){if(g={meta:{response_id:p,timestamp:Lt(d.timestamp),model:typeof m.model=="string"&&m.model?m.model:null,tokens:{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,promptRecorded:!1},i.set(p,g),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);g.io.record({direction:"read",kind:"prompt",id:f,ref:null,bytes:y,basis:y===null?"unknown":"input_text"}),g.promptRecorded=!0}}else g.io.record({direction:"read",kind:"prompt",id:null,ref:null,bytes:null,basis:"unknown"})}let h=Z(m.outputTokens);if(h!==null&&(g.meta.tokens.output=(g.meta.tokens.output??0)+h),g.meta.model===null&&typeof m.model=="string"&&m.model&&(g.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 I=J(E),T=typeof I?.path=="string"?I.path:null,k=typeof I?.file_text=="string"?Buffer.byteLength(I.file_text,"utf8"):null;T!==null?g.obs.record(v??p,"written",T,k):Le(g.io,v)}else if(_==="apply_patch")if(typeof E=="string"){let I=cM(E);if(I.length>0)for(let T of I)g.obs.record(v??p,"written",T.path,T.bytes);else Le(g.io,v)}else Le(g.io,v);else if(lM.has(_)){let I=J(E),T=typeof I?.path=="string"?I.path:null;T!==null?g.obs.record(v??p,"read",T,null):Le(g.io,v)}else aM.has(_)||Le(g.io,v)}}let u=[];for(let{meta:d,obs:m,io:p}of i.values()){let f=m.files("read"),g=m.files("written"),h=p.entries();u.push({...d,files_read:f,files_written:g,external_io:h,read_bytes:lt(f,h,"read"),write_bytes:lt(g,h,"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 pM(){return process.env.HOME||process.env.USERPROFILE||""}function Cv(t={}){return new ym(t)}var hr,Av,aM,lM,ym,Nv=L(()=>{"use strict";$n();hr="copilot",Av="events.jsonl",aM=new Set(["report_intent"]),lM=new Set(["view"]);ym=class{sessionStateDir;constructor(e={}){this.sessionStateDir=xv(e.copilotSessionStateDir??Iv(pM(),".copilot","session-state"))}async discover(e,n,r=null){fe(e);let s;try{s=await rM(this.sessionStateDir)}catch{return{sources:[],truncated:!1}}let i=[];for(let o of s.sort(we)){e.signal.throwIfAborted();let a=Iv(this.sessionStateDir,o,Av);if(!(await iM(a).catch(()=>null))?.isFile())continue;let c=await sM(a).catch(()=>xv(a)),u={provider:hr,sessionid:o,source_id:c};r!==null&&we(`${c}\0${o}`,r)<=0||i.push(u)}return i.sort((o,a)=>we(`${o.source_id}\0${o.sessionid}`,`${a.source_id}\0${a.sessionid}`)),{sources:i.slice(0,n),truncated:!1}}matches(e,n){return Rv(n)===Av&&Rv(oM(n))===e.sessionid}async inspect(e,n){if(fe(n),e.provider!==hr)return{status:"unsupported"};let r=await Ge(e.source_id,[this.sessionStateDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(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(fe(r),e.provider!==hr)return{snapshot:{status:"unsupported"},sessionUsage:null};let s=await Ge(e.source_id,[this.sessionStateDir]);if(!s||!this.matches(e,s))return{snapshot:{status:"unavailable"},sessionUsage:null};let i=await _t(s,r).catch(()=>null);if(!i||i.revision!==n)return{snapshot:{status:"partial"},sessionUsage:null};let o=ul(i.data,r);return o?mM(o,e,n,r):{snapshot:{status:"partial"},sessionUsage:null}}}});import{readdir as Ov,readFile as fM,realpath as _m,stat as Lv}from"node:fs/promises";import{basename as po,dirname as Ks,isAbsolute as bm,join as Vs,relative as Dv,resolve as mo,sep as Fv}from"node:path";function wM(t){return bM.has(t)||mr(t)}function EM(){return process.env.HOME||process.env.USERPROFILE||""}function TM(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 Mv(t){let e=J(t);if(!e)return null;let n=Z(e.inputOther),r=Z(e.inputCacheRead),s=Z(e.inputCacheCreation),i=Z(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 SM(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 RM(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&&!gM.has(i))return{status:"unsupported"};let o=IM(e.source_id),a=new Map,l=new Map,c=[],u=new Set,d=new Set,m=null,p=!1,f=b=>`${o}/${b}`,g=(b,_)=>{let v=f(b),E=a.get(v);return E||(E={meta:{response_id:v,timestamp:Lt(typeof _=="number"?_:null),model:null,tokens:{...yt},files_read:[],files_written:[]},obs:new Nt,io:new Ot,turnStepKey:null,tokensSource:"none"},a.set(v,E)),E},h=(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,I=typeof b.promptId=="string"&&b.promptId?b.promptId:null;if(E!==null&&kM.has(E))continue;if(I!==null){if(u.has(I))continue;u.add(I)}E==="user"?c.push({bytes:SM(b.input),id:I}):c.push({bytes:null,id:I});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 I=Mv(b.usage);I&&(E.meta.tokens=I,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=g(v,b.time);if(a.size>r.maxRows)return{status:"partial"};if(d.add(v),h(E,_),c.length>0){for(let I of c)E.io.record({direction:"read",kind:"prompt",id:I.id,ref:null,bytes:I.bytes,basis:I.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=g(v,b.time);if(a.size>r.maxRows)return{status:"partial"};d.delete(v),m=v,h(E,_);let I=Mv(_.usage);I&&(E.meta.tokens=I),E.tokensSource="end",E.meta.timestamp===null&&(E.meta.timestamp=Lt(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=g(v,b.time);if(a.size>r.maxRows)return{status:"partial"};let I=typeof _.name=="string"?_.name.toLowerCase():"",T=typeof _.toolCallId=="string"&&_.toolCallId?_.toolCallId:null,k=J(_.args),N=typeof k?.path=="string"&&k.path?k.path:typeof k?.file_path=="string"&&k.file_path?k.file_path:null;_M.has(I)?N!==null?E.obs.record(T??"","read",N,null):Le(E.io,T):vM.has(I)?N!==null?E.obs.record(T??"","written",N,Ws(k)):Le(E.io,T):wM(I)||Le(E.io,T);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 I=_.files("read"),T=_.files("written"),k=v.entries();y.push({...b,files_read:I,files_written:T,external_io:k,read_bytes:lt(I,k,"read"),write_bytes:lt(T,k,"written"),model_provider:null,pricing_facts:fn({},b.tokens.output,b.tokens.input_cache_write)})}return{status:"complete",source:e,revision:n,checkpoint:n,responses:y,...p?{capture_status:"partial"}:{}}}function vm(t){return po(t)===wm&&po(Ks(Ks(t)))===$v}function Pv(t){return po(Ks(Ks(Ks(t))))}function IM(t){return po(Ks(t))}function xM(t,e){let n=Dv(e,t);return n===""||!n.startsWith(`..${Fv}`)&&n!==".."&&!bm(n)}function AM(t){if(t instanceof Error&&t.name==="AbortError")throw t}function jv(t={}){return new fo(t)}var yr,wm,$v,gM,hM,yM,_M,vM,bM,kM,fo,Em=L(()=>{"use strict";$n();yr="kimi",wm="wire.jsonl",$v="agents",gM=new Set(["1.4","1.5"]),hM=5e5,yM=8*1024*1024,_M=new Set(["read"]),vM=new Set(["write","edit"]),bM=new Set(["todolist","tasklist","taskoutput","taskstop","waitfor","creategoal","updategoal","getgoal","enterplanmode","exitplanmode","agentswarm","agent","skill","croncreate","crondelete","cronlist"]);kM=new Set(["system_trigger","cron_job","task"]);fo=class{home;sessionsDir;indexPath;maxDiscoveryTraversalVisits;constructor(e={}){this.home=mo(e.kimiHome??process.env.KIMI_CODE_HOME??Vs(EM(),".kimi-code")),this.sessionsDir=Vs(this.home,"sessions"),this.indexPath=Vs(this.home,"session_index.jsonl"),this.maxDiscoveryTraversalVisits=e.maxDiscoveryTraversalVisits&&e.maxDiscoveryTraversalVisits>0?Math.trunc(e.maxDiscoveryTraversalVisits):hM}async discover(e,n,r=null){fe(e);let s=new Set,i=!1,o=await _m(this.sessionsDir).catch(()=>mo(this.sessionsDir)),a=m=>{vm(m)&&xM(m,o)&&s.add(m)},l=0,c=async(m,p)=>{if(e.signal.throwIfAborted(),i)return;let f=await Ov(m,{withFileTypes:!0}).catch(()=>[]);f.sort((g,h)=>we(g.name,h.name));for(let g of f){if(e.signal.throwIfAborted(),l+=1,l>this.maxDiscoveryTraversalVisits){i=!0;return}let h=Vs(m,g.name);if(g.isDirectory()&&!g.isSymbolicLink()&&p<4){if(await c(h,p+1),i)return}else g.isFile()&&g.name===wm&&vm(h)&&a(await _m(h).catch(()=>mo(h)))}};await c(this.sessionsDir,0);try{await this.unionIndex(a,e)}catch(m){AM(m)}let u=[...s].sort(we);return{sources:(r===null?u:u.filter(m=>we(m,r)>0)).slice(0,n).map(m=>({provider:yr,sessionid:Pv(m),source_id:m})),truncated:i}}async unionIndex(e,n){let r=await Lv(this.indexPath).catch(()=>null);if(!r?.isFile()||r.size>yM)return;let s=await fM(this.indexPath,{signal:n.signal});for(let i of s.toString("utf8").split(`
|
|
487
487
|
`)){if(n.signal.throwIfAborted(),!i.trim())continue;let o;try{o=J(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||!bm(l)||po(l)!==a)continue;let c=Dv(this.sessionsDir,mo(l));if(c.startsWith(`..${Fv}`)||c===".."||bm(c))continue;let u=Vs(l,$v),d=await Ov(u,{withFileTypes:!0}).catch(()=>[]);for(let m of d){if(!m.isDirectory())continue;let p=Vs(u,m.name,wm);(await Lv(p).catch(()=>null))?.isFile()&&e(await _m(p).catch(()=>mo(p)))}}}matches(e,n){return vm(n)&&Pv(n)===e.sessionid}async inspect(e,n){if(fe(n),e.provider!==yr)return{status:"unsupported"};let r=await Ge(e.source_id,[this.sessionsDir]);if(!r||!this.matches(e,r))return{status:"unavailable"};let s=await _t(r,n).catch(()=>null);return s?{status:"ready",revision:s.revision}:{status:"partial"}}async read(e,n,r){if(fe(r),e.provider!==yr)return{status:"unsupported"};let s=await Ge(e.source_id,[this.sessionsDir]);if(!s||!this.matches(e,s))return{status:"unavailable"};let i=await _t(s,r).catch(()=>null);if(!i)return{status:"partial"};if(i.revision!==n)return{status:"partial"};let o=TM(i.data,r);return o?RM(o,e,n,r):{status:"partial"}}}});import{createHash as xm}from"node:crypto";import{createRequire as CM}from"node:module";import{lstat as NM,readFile as OM,readdir as LM,realpath as Rm,stat as Uv}from"node:fs/promises";import{basename as Tl,dirname as MM,isAbsolute as Hv,join as os,relative as PM,resolve as jn,sep as DM}from"node:path";function Am(t){return typeof t=="string"&&$M.has(t.toLowerCase())}function yo(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 Jv(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 Qs(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 Ys(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Cm(t,e,n){let r={},s=Ys(t.cacheWrite5m),i=Ys(t.cacheWrite1h),o=Ys(t.reasoning),a=Ys(t.webSearch),l=Ys(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 Sl(){return process.env.HOME||process.env.USERPROFILE||""}function HM(){if(process.env.OPENCODE_DB)return[jn(process.env.OPENCODE_DB)];let t=process.env.XDG_DATA_HOME||os(Sl(),".local","share");return[os(t,"lmplayer","opencode-local.db"),os(t,"lmplayer","opencode-dev.db")]}function BM(){return UM("node:sqlite").DatabaseSync}function ne(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}function vt(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}function Om(t){if(typeof t!="string"&&typeof t!="number")return null;let e=new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function ho(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 kl(t){return`${t.source_id}\0${t.sessionid}`}function br(t,e){return t<e?-1:t>e?1:0}function Tm(t,e){return br(kl(t),kl(e))}function WM(t){let e={version:2,pos:t.pos,done:t.done,rr:t.rr};return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function Bv(t){let e=ne(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 qM(t){if(t===void 0)return null;let e;try{e=ne(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>=Sm.length)throw new Error("invalid passive session discovery cursor");let o=i,a=Bv({source_id:e.source_id,sessionid:e.sessionid}),l=new Map([[Sm[o],a]]),c=new Set(Sm.slice(0,o));return{pos:l,done:c,rr:0}}if(e.version!==2)throw new Error("invalid passive session discovery cursor");let n=ne(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,Bv(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 Vv(t){if(typeof t!="string")return null;let e=t.toLowerCase();return e==="apply_patch"?"apply_patch":XM.includes(e)?"read":GM.includes(e)?"written":null}function VM(t){return typeof t=="string"?(()=>{try{return JSON.parse(t)}catch{return t}})():t}function Rl(t,e=JM){let n=ne(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 Kv(t){let e=ne(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=ne(r),i=s?.new_string??s?.newString;if(typeof i!="string")return null;n+=Buffer.byteLength(i,"utf8")}return n}return null}function Il(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(`
|
|
488
488
|
`)){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 zM(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 KM)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 Wv(t){if(t.length===0||t.endsWith(`
|
|
489
489
|
`))return null;let e=[];for(let n of t.split(`
|
|
@@ -497,7 +497,7 @@ ${i}`,n),this.line=r,this.column=s,this.codeblock=i}static x(e,n,r){throw new t(
|
|
|
497
497
|
`).filter(u=>u.trim()).map(u=>JSON.parse(u));if((Array.isArray(r?.messages)?r:s[0])?.sessionId!==n)return;let o=new Map,a=new Map;for(let u of s){if(!u||typeof u!="object"||Array.isArray(u)||u.$set?.sessionId!==void 0&&u.$set.sessionId!==n)return;if(typeof u.id!="string")continue;let d=o.get(u.id)??{};for(let m of["model","timestamp","type"]){let p=u[m];if(!(m==="model"&&p===null&&d.model===void 0)&&p!==void 0){if(typeof p!="string"||d[m]!==void 0&&d[m]!==p)return;d[m]=p}}o.set(u.id,d),Object.hasOwn(u,"tokens")&&a.set(u.id,u.tokens)}let l=as(e);if(!l||l.sessionId!==n)return;let c=[];for(let u of l.messages){if(u.tokens!==void 0&&!["gemini","assistant"].includes(u.type??""))return;if(!["gemini","assistant"].includes(u.type??""))continue;if(!u.id||!u.tokens)return;let d=a.get(u.id)??u.tokens,m=Un(d.input),p=Un(d.cached),f=Un(d.output),g=Un(d.thoughts),h=nb(u.id,u.timestamp,u.model);h.tokens={input_uncached:m!==null&&p!==null&&p<=m?m-p:null,input_cached:p,input_cache_write:null,output:f!==null&&g!==null&&Number.isSafeInteger(f+g)?f+g:null},h.pricing_facts={reasoning_output_tokens:g},c.push(h)}return c}catch{return}}function Mm(t,e){let n=async(s,i)=>{i.signal.throwIfAborted();let o=await tb(s),a=await tb(e),l=vP(a,o);if(l===".."||l.startsWith("../")||l.startsWith("..\\")||bP(l))throw Error("outside native root");let c=await yP(o,Lm.O_RDONLY|Lm.O_NOFOLLOW|Lm.O_NONBLOCK);try{let u=await c.stat({bigint:!0});if(!u.isFile()||u.size>BigInt(i.maxBytes))throw Error("native byte limit");let d=Buffer.alloc(Number(u.size)+1),m=0;for(;m<d.length;){i.signal.throwIfAborted();let f=await c.read(d,m,d.length-m,m);if(!f.bytesRead)break;m+=f.bytesRead}let p=await c.stat({bigint:!0});if(i.signal.throwIfAborted(),m!==Number(u.size)||u.size!==p.size||u.mtimeNs!==p.mtimeNs||u.ctimeNs!==p.ctimeNs||u.ino!==p.ino||u.dev!==p.dev)throw Error("changing native file");return new TextDecoder("utf-8",{fatal:!0}).decode(d.subarray(0,m))}finally{await c.close()}},r=s=>{try{return t==="pi"?JSON.parse(s.slice(0,s.indexOf(`
|
|
498
498
|
`)<0?s.length:s.indexOf(`
|
|
499
499
|
`))).id:as(s)?.sessionId}catch{return}};return{async discover(s){let i=[],o=0,a=!0,l=async(c,u)=>{if(s.signal.throwIfAborted(),u>4){a=!1;return}let d=await hP(c).catch(()=>{a=!1});if(d)for await(let m of d){if(s.signal.throwIfAborted(),++o>s.maxRows||i.length>=s.maxSources){a=!1;break}let p=_P(c,m.name);if(m.isDirectory())await l(p,u+1);else if(m.isFile()&&/\.jsonl?$/.test(m.name)&&(t!=="gemini"||wP(EP(p))==="chats"&&m.name.startsWith("session-"))){let f=await n(p,s).catch(()=>{});if(f===void 0){s.signal.throwIfAborted(),a=!1;continue}let g=r(f);typeof g=="string"&&g?i.push({provider:t,sessionid:g,source_id:p}):a=!1}}};return await l(e,0),{sources:i,complete:a,cursor:null}},async inspect(s,i){let o=await n(s.source_id,i);return{status:"ready",revision:eb("sha256").update(o).digest("hex")}},async read(s,i,o){let a=await n(s.source_id,o);if(eb("sha256").update(a).digest("hex")!==i)return{status:"partial"};if(a.split(`
|
|
500
|
-
`).length>o.maxRows)return{status:"partial"};let l=SP(t,a,s.sessionid);return l&&l.length<=o.maxRows?{status:"complete",source:s,revision:i,responses:l}:{status:"partial"}}}}var Un,TP,nb,rb=L(()=>{"use strict";xl();Un=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,TP=t=>{let e=typeof t=="number"||typeof t=="string"?new Date(t):null;return e&&Number.isFinite(e.getTime())?e.toISOString():null},nb=(t,e,n)=>({response_id:t,timestamp:TP(e),model:typeof n=="string"&&n?n:null,tokens:{input_uncached:null,input_cached:null,input_cache_write:null,output:null},files_read:null,files_written:null})});import{stat as kP,realpath as RP}from"node:fs/promises";import{join as bt,resolve as ib}from"node:path";import{homedir as IP}from"node:os";function xP(t,e){if(!e.length||e.some(u=>typeof u.response_id!="string"||!u.response_id)||new Set(e.map(u=>u.response_id)).size!==e.length)return;let n=t==="agy"&&e.some(u=>(u.tokens.input_cache_write??0)>0),r=e.map(u=>{let d=u.tokens,m=d.input_cache_write,p=d.input_uncached;for(let g of Object.values(d))g!==null&&Pm(g)===null&&(n=!0);let f=p;return["kimi","opencode","miniplayer","lmplayer"].includes(t)&&(m===null||p===null||m>p?(f=null,n=!0):f=p-m),(f===null||d.input_cached===null||d.output===null)&&(n=!0),{...u,tokens:{...d,input_uncached:f}}}),s=Xs(r);s.input_cache_write===null&&(t==="pi"||r.some(u=>u.tokens.input_cache_write!=null))&&(n=!0);let i=new Set(e.map(u=>u.model).filter(u=>typeof u=="string"&&u.length>0));for(let u of["input_uncached","input_cached","output"])s[u]===null&&(n=!0);let o=u=>{if(u.some(m=>m==null))return null;if(u.some(m=>Pm(m)===null))return n=!0,null;let d=u.reduce((m,p)=>m+p,0);return Pm(d)===null?(n=!0,null):d};e.some(u=>u.pricing_facts?.reasoning_output_tokens!=null&&u.tokens.output!=null&&u.pricing_facts.reasoning_output_tokens>u.tokens.output)&&(n=!0);let a=o(e.map(u=>u.pricing_facts?.reasoning_output_tokens)),l=e.map(u=>u.providerCostUsd),c=l.every(u=>typeof u=="number"&&Number.isFinite(u)&&u>=0)?l.reduce((u,d)=>u+d,0):null;return{source:"native",inputUncached:s.input_uncached,cacheRead:s.input_cached,cacheWrite:s.input_cache_write,output:s.output,reasoning:a,modelReported:i.size===1?[...i][0]:null,mixedModels:i.size>1,providerCostUsd:c,reason:n||s.input_cache_write===null?"counter_not_exposed":null,invalidCounters:n}}async function sb(t,e,n,r){let s=[],i=new Set;for(let o of t){r.signal?.throwIfAborted();let a=ib(o),l;try{if(!(await kP(a)).isFile())return{sources:s,complete:!1};let c=await RP(a);if(i.has(c))continue;i.add(c),l=om(a),l.pragma("busy_timeout = 0"),l.prepare("SELECT id FROM session WHERE id=?").get(n)&&s.push({provider:e,sessionid:n,source_id:a})}catch(c){if(c.code!=="ENOENT")return{sources:s,complete:!1}}finally{try{l?.close()}catch{}}}return{sources:s,complete:!0}}function AP(t,e,n){let r=e.HOME||e.USERPROFILE||IP(),s=e.XDG_DATA_HOME||bt(r,".local","share"),i=e.XDG_CONFIG_HOME||bt(r,".config");if(t==="pi")return Mm("pi",e.PI_CODING_AGENT_DIR?bt(e.PI_CODING_AGENT_DIR,"sessions"):bt(r,".pi","agent","sessions"));if(t==="gemini")return Mm("gemini",bt(e.GEMINI_CLI_HOME||bt(r,".gemini"),"tmp"));if(t==="miniplayer"){let l=new qs(yl(e.MINIPLAYER_HOME||bt(s,"miniplayer")));return{discover:async c=>{let u=await l.discover(c,c.maxSources,null);return{...u,complete:!u.truncated&&u.sources.length<c.maxSources}},inspect:(c,u)=>l.inspect(c,u),read:(c,u,d)=>l.read(c,u,d)}}if(t==="opencode"){let l=[bt(s,"opencode","opencode.db"),bt(s,"opencode","opencode-local.db"),bt(i,"opencode","opencode.db")].map(u=>ib(u)),c=new uo({dbPaths:l,sqliteBusyTimeoutMs:0});return{discover:u=>sb(l,t,n,u),inspect:(u,d)=>c.inspect(u,d),read:(u,d,m)=>c.read(u,d,m)}}if(t==="kimi"||t==="agy"){let l=t==="kimi"?new fo({kimiHome:e.KIMI_CODE_HOME||bt(r,".kimi-code")}):new ao({agyConversationsDir:bt(r,".gemini","antigravity-cli","conversations"),sqliteBusyTimeoutMs:0});return{discover:async c=>{let u=await l.discover(c,c.maxSources,null);return{...u,complete:!u.truncated&&u.sources.length<c.maxSources}},inspect:(c,u)=>l.inspect(c,u),read:(c,u,d)=>l.read(c,u,d)}}let o=e.OPENCODE_DB?[e.OPENCODE_DB]:[bt(s,"lmplayer","opencode-local.db"),bt(s,"lmplayer","opencode-dev.db")],a=zv({lmplayerDbPaths:o,sqliteBusyTimeoutMs:0});return{discover:l=>sb(o,t,n,l),inspect:(l,c)=>a.inspect(l,c),read:(l,c,u)=>a.read(l,c,u)}}async function ob(t,e,n,r){if(!Al.includes(t.provider)||!e||t.native_session_id&&t.native_session_id!==e)return;let s=new AbortController,i,o,a=async()=>{let l=r.db??(o=om(r.dbPath));o&&o.pragma("busy_timeout = 0");let c={signal:s.signal,maxBytes:8*1024*1024,maxRows:1e4,maxSources:512,requireBillingCounters:!0},u=r.reader??AP(t.provider,r.env??process.env,e),d=await u.discover(c);if(d.complete!==!0)return;let m=d.sources.filter(f=>f.provider===t.provider&&(f.sessionid===e||t.provider==="lmplayer"&&f.sessionid==="")).map(f=>({...f,sessionid:e}));if(!m.length)return;let p;for(let f of m){s.signal.throwIfAborted();let g=await u.inspect(f,c);if(g.status!=="ready")return;let h=await u.read(f,g.revision,c);if(s.signal.throwIfAborted(),h.status!=="complete"||h.capture_status!==void 0||h.source?.provider!==t.provider||h.source?.sessionid!==e||h.source?.source_id!==f.source_id||h.revision!==g.revision)return;let y=Date.parse(t.startedAt),b=Date.parse(n);if(!Number.isFinite(y)||!Number.isFinite(b)||b<y)return;let _=h.responses;if(!Array.isArray(_)||_.some(I=>!I.timestamp||!Number.isFinite(Date.parse(I.timestamp))))return;let v=_.filter(I=>Date.parse(I.timestamp)>=y&&Date.parse(I.timestamp)<=b);if(!v.length)continue;if(p)return;let E=l.pragma("busy_timeout",{simple:!0});try{l.pragma("busy_timeout = 0");let I=l.prepare("SELECT 1 FROM team_chat_log WHERE attempt_key IS NOT NULL AND attempt_key<>? AND provider=? AND (native_session_id=? OR native_session_id IS NULL) AND julianday(created_at)<=julianday(?) AND (ended_at IS NULL OR julianday(ended_at)>=julianday(?)) LIMIT 1");for(let T of v){let k=new Date(T.timestamp).toISOString();if(I.get(t.attempt_key,t.provider,e,k,k))return}}finally{l.pragma("busy_timeout = "+E)}p=v}return p?xP(t.provider,p):void 0};try{return await Promise.race([a(),new Promise(l=>{i=setTimeout(()=>{s.abort(),l(void 0)},2e3)})])}catch{return}finally{clearTimeout(i),s.abort();try{o?.close()}catch{}}}var Al,Pm,ab=L(()=>{"use strict";F_();Yv();Em();hm();um();am();_l();dl();rb();Al=["kimi","opencode","gemini","miniplayer","pi","agy","lmplayer"],Pm=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null});function
|
|
500
|
+
`).length>o.maxRows)return{status:"partial"};let l=SP(t,a,s.sessionid);return l&&l.length<=o.maxRows?{status:"complete",source:s,revision:i,responses:l}:{status:"partial"}}}}var Un,TP,nb,rb=L(()=>{"use strict";xl();Un=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,TP=t=>{let e=typeof t=="number"||typeof t=="string"?new Date(t):null;return e&&Number.isFinite(e.getTime())?e.toISOString():null},nb=(t,e,n)=>({response_id:t,timestamp:TP(e),model:typeof n=="string"&&n?n:null,tokens:{input_uncached:null,input_cached:null,input_cache_write:null,output:null},files_read:null,files_written:null})});import{stat as kP,realpath as RP}from"node:fs/promises";import{join as bt,resolve as ib}from"node:path";import{homedir as IP}from"node:os";function xP(t,e){if(!e.length||e.some(u=>typeof u.response_id!="string"||!u.response_id)||new Set(e.map(u=>u.response_id)).size!==e.length)return;let n=t==="agy"&&e.some(u=>(u.tokens.input_cache_write??0)>0),r=e.map(u=>{let d=u.tokens,m=d.input_cache_write,p=d.input_uncached;for(let g of Object.values(d))g!==null&&Pm(g)===null&&(n=!0);let f=p;return["kimi","opencode","miniplayer","lmplayer"].includes(t)&&(m===null||p===null||m>p?(f=null,n=!0):f=p-m),(f===null||d.input_cached===null||d.output===null)&&(n=!0),{...u,tokens:{...d,input_uncached:f}}}),s=Xs(r);s.input_cache_write===null&&(t==="pi"||r.some(u=>u.tokens.input_cache_write!=null))&&(n=!0);let i=new Set(e.map(u=>u.model).filter(u=>typeof u=="string"&&u.length>0));for(let u of["input_uncached","input_cached","output"])s[u]===null&&(n=!0);let o=u=>{if(u.some(m=>m==null))return null;if(u.some(m=>Pm(m)===null))return n=!0,null;let d=u.reduce((m,p)=>m+p,0);return Pm(d)===null?(n=!0,null):d};e.some(u=>u.pricing_facts?.reasoning_output_tokens!=null&&u.tokens.output!=null&&u.pricing_facts.reasoning_output_tokens>u.tokens.output)&&(n=!0);let a=o(e.map(u=>u.pricing_facts?.reasoning_output_tokens)),l=e.map(u=>u.providerCostUsd),c=l.every(u=>typeof u=="number"&&Number.isFinite(u)&&u>=0)?l.reduce((u,d)=>u+d,0):null;return{source:"native",inputUncached:s.input_uncached,cacheRead:s.input_cached,cacheWrite:s.input_cache_write,output:s.output,reasoning:a,modelReported:i.size===1?[...i][0]:null,mixedModels:i.size>1,providerCostUsd:c,reason:n||s.input_cache_write===null?"counter_not_exposed":null,invalidCounters:n}}async function sb(t,e,n,r){let s=[],i=new Set;for(let o of t){r.signal?.throwIfAborted();let a=ib(o),l;try{if(!(await kP(a)).isFile())return{sources:s,complete:!1};let c=await RP(a);if(i.has(c))continue;i.add(c),l=om(a),l.pragma("busy_timeout = 0"),l.prepare("SELECT id FROM session WHERE id=?").get(n)&&s.push({provider:e,sessionid:n,source_id:a})}catch(c){if(c.code!=="ENOENT")return{sources:s,complete:!1}}finally{try{l?.close()}catch{}}}return{sources:s,complete:!0}}function AP(t,e,n){let r=e.HOME||e.USERPROFILE||IP(),s=e.XDG_DATA_HOME||bt(r,".local","share"),i=e.XDG_CONFIG_HOME||bt(r,".config");if(t==="pi")return Mm("pi",e.PI_CODING_AGENT_DIR?bt(e.PI_CODING_AGENT_DIR,"sessions"):bt(r,".pi","agent","sessions"));if(t==="gemini")return Mm("gemini",bt(e.GEMINI_CLI_HOME||bt(r,".gemini"),"tmp"));if(t==="miniplayer"){let l=new qs(yl(e.MINIPLAYER_HOME||bt(s,"miniplayer")));return{discover:async c=>{let u=await l.discover(c,c.maxSources,null);return{...u,complete:!u.truncated&&u.sources.length<c.maxSources}},inspect:(c,u)=>l.inspect(c,u),read:(c,u,d)=>l.read(c,u,d)}}if(t==="opencode"){let l=[bt(s,"opencode","opencode.db"),bt(s,"opencode","opencode-local.db"),bt(i,"opencode","opencode.db")].map(u=>ib(u)),c=new uo({dbPaths:l,sqliteBusyTimeoutMs:0});return{discover:u=>sb(l,t,n,u),inspect:(u,d)=>c.inspect(u,d),read:(u,d,m)=>c.read(u,d,m)}}if(t==="kimi"||t==="agy"){let l=t==="kimi"?new fo({kimiHome:e.KIMI_CODE_HOME||bt(r,".kimi-code")}):new ao({agyConversationsDir:bt(r,".gemini","antigravity-cli","conversations"),sqliteBusyTimeoutMs:0});return{discover:async c=>{let u=await l.discover(c,c.maxSources,null);return{...u,complete:!u.truncated&&u.sources.length<c.maxSources}},inspect:(c,u)=>l.inspect(c,u),read:(c,u,d)=>l.read(c,u,d)}}let o=e.OPENCODE_DB?[e.OPENCODE_DB]:[bt(s,"lmplayer","opencode-local.db"),bt(s,"lmplayer","opencode-dev.db")],a=zv({lmplayerDbPaths:o,sqliteBusyTimeoutMs:0});return{discover:l=>sb(o,t,n,l),inspect:(l,c)=>a.inspect(l,c),read:(l,c,u)=>a.read(l,c,u)}}async function ob(t,e,n,r){if(!Al.includes(t.provider)||!e||t.native_session_id&&t.native_session_id!==e)return;let s=new AbortController,i,o,a=async()=>{let l=r.db??(o=om(r.dbPath));o&&o.pragma("busy_timeout = 0");let c={signal:s.signal,maxBytes:8*1024*1024,maxRows:1e4,maxSources:512,requireBillingCounters:!0},u=r.reader??AP(t.provider,r.env??process.env,e),d=await u.discover(c);if(d.complete!==!0)return;let m=d.sources.filter(f=>f.provider===t.provider&&(f.sessionid===e||t.provider==="lmplayer"&&f.sessionid==="")).map(f=>({...f,sessionid:e}));if(!m.length)return;let p;for(let f of m){s.signal.throwIfAborted();let g=await u.inspect(f,c);if(g.status!=="ready")return;let h=await u.read(f,g.revision,c);if(s.signal.throwIfAborted(),h.status!=="complete"||h.capture_status!==void 0||h.source?.provider!==t.provider||h.source?.sessionid!==e||h.source?.source_id!==f.source_id||h.revision!==g.revision)return;let y=Date.parse(t.startedAt),b=Date.parse(n);if(!Number.isFinite(y)||!Number.isFinite(b)||b<y)return;let _=h.responses;if(!Array.isArray(_)||_.some(I=>!I.timestamp||!Number.isFinite(Date.parse(I.timestamp))))return;let v=_.filter(I=>Date.parse(I.timestamp)>=y&&Date.parse(I.timestamp)<=b);if(!v.length)continue;if(p)return;let E=l.pragma("busy_timeout",{simple:!0});try{l.pragma("busy_timeout = 0");let I=l.prepare("SELECT 1 FROM team_chat_log WHERE attempt_key IS NOT NULL AND attempt_key<>? AND provider=? AND (native_session_id=? OR native_session_id IS NULL) AND julianday(created_at)<=julianday(?) AND (ended_at IS NULL OR julianday(ended_at)>=julianday(?)) LIMIT 1");for(let T of v){let k=new Date(T.timestamp).toISOString();if(I.get(t.attempt_key,t.provider,e,k,k))return}}finally{l.pragma("busy_timeout = "+E)}p=v}return p?xP(t.provider,p):void 0};try{return await Promise.race([a(),new Promise(l=>{i=setTimeout(()=>{s.abort(),l(void 0)},2e3)})])}catch{return}finally{clearTimeout(i),s.abort();try{o?.close()}catch{}}}var Al,Pm,ab=L(()=>{"use strict";F_();Yv();Em();hm();um();am();_l();dl();rb();Al=["kimi","opencode","gemini","miniplayer","pi","agy","lmplayer"],Pm=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null});function hn(t){return t.some(e=>e!=null&&(typeof e!="number"||!Number.isSafeInteger(e)||e<0))}var vo=L(()=>{"use strict"});var Cl,lb,Dm=L(()=>{"use strict";Cl={attempt_key:"TEXT",provider:"TEXT",native_session_id:"TEXT",cwd:"TEXT",ended_at:"TEXT",turn_outcome:"TEXT",model_requested:"TEXT",model_reported:"TEXT",tok_input_uncached:"INTEGER",tok_cache_read:"INTEGER",tok_cache_write:"INTEGER",tok_output:"INTEGER",tok_reasoning:"INTEGER",usage_source:"TEXT CHECK(usage_source IN ('wire','native','cumulative_delta'))",usage_reason:"TEXT",price_record_id:"TEXT",price_snapshot_sha256:"TEXT",rate_input_1m:"REAL",rate_output_1m:"REAL",rate_cache_read_1m:"REAL",rate_cache_write_1m:"REAL",cost_reason:"TEXT",provider_cost_usd:"REAL"},lb=`CREATE UNIQUE INDEX IF NOT EXISTS idx_team_chat_attempt_unique ON team_chat_log(attempt_key) WHERE attempt_key IS NOT NULL;
|
|
501
501
|
CREATE INDEX IF NOT EXISTS idx_team_chat_started ON team_chat_log(created_at);
|
|
502
502
|
CREATE INDEX IF NOT EXISTS idx_team_chat_provider_model ON team_chat_log(provider, model_reported);
|
|
503
503
|
CREATE INDEX IF NOT EXISTS idx_team_chat_provider_session ON team_chat_log(provider, native_session_id);
|
|
@@ -516,7 +516,7 @@ CREATE VIEW IF NOT EXISTS turn_usage AS SELECT
|
|
|
516
516
|
+COALESCE(tok_cache_write,0)*COALESCE(rate_cache_write_1m,rate_input_1m,0)
|
|
517
517
|
+COALESCE(tok_output,0)*COALESCE(rate_output_1m,0))/1e6 END AS cost_usd
|
|
518
518
|
FROM team_chat_log WHERE attempt_key IS NOT NULL;
|
|
519
|
-
`});import{createHash as yb}from"node:crypto";import{mkdirSync as _b,readFileSync as CP,renameSync as NP,writeFileSync as OP,existsSync as vb}from"node:fs";import{homedir as LP}from"node:os";import{dirname as bb,join as Ml,resolve as Pl}from"node:path";import{fileURLToPath as MP}from"node:url";function jP(){return Ml(LP(),".lmctl","cache","lmprice")}function ti(t,e){return Ml(t,e)}function Dl(t,e){if(!t||!e)return null;let n=bo.get(t),r=bo.get(e);return n===void 0||r===void 0?null:yb("sha256").update(n).update(r).digest("hex")}function ls(t){try{let e=CP(t,"utf-8"),n=JSON.parse(e);return n&&typeof n=="object"&&bo.set(n,e),n}catch{return null}}function Eb(t,e){let n=`${t}.tmp-${process.pid}`;OP(n,e),NP(n,t)}function Fm(t){return t===null||typeof t=="number"}function cs(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.schema_version!==1||!Array.isArray(e.records)||e.records.length===0?!1:e.records.every(n=>{if(typeof n!="object"||n===null)return!1;let r=n;if(typeof r.source!="string"||typeof r.source_model_id!="string"||typeof r.pricing!="object"||r.pricing===null)return!1;let s=r.pricing;return Fm(s.input_per_1m_tokens)&&Fm(s.output_per_1m_tokens)&&Fm(s.input_cache_read_per_1m_tokens)})}function us(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.schema_version!==1||!Array.isArray(e.standards)||!Array.isArray(e.aliases))return!1;let n=e.standards.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.standard_slug=="string"&&(i.catalog_record_id===null||typeof i.catalog_record_id=="string")}),r=e.aliases.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.alias=="string"&&(i.standard_slug===null||typeof i.standard_slug=="string")&&typeof i.evidence=="string"&&HP.has(i.evidence)});return n&&r}function BP(t){let e=ls(ti(t,wb)),n={etag:typeof e?.model_list?.etag=="string"?e.model_list.etag:null,last_checked:typeof e?.model_list?.last_checked=="string"?e.model_list.last_checked:null},r={etag:typeof e?.aliases?.etag=="string"?e.aliases.etag:null,last_checked:typeof e?.aliases?.last_checked=="string"?e.aliases.last_checked:null};if(e===null){let s=ls(ti(t,UP));s&&(n.etag=typeof s.etag=="string"?s.etag:null,n.last_checked=typeof s.fetchedAt=="string"?s.fetchedAt:null)}return{model_list:n,aliases:r,...typeof e?.pair_sha256=="string"?{pair_sha256:e.pair_sha256}:{}}}function WP(t){let e=BP(t),n=ls(ti(t,Ol)),r=ls(ti(t,Ll));return e.pair_sha256&&Dl(cs(n)?n:null,us(r)?r:null)!==e.pair_sha256?{catalog:null,aliases:null,meta:{model_list:{...ub},aliases:{...ub}}}:{catalog:cs(n)?n:null,aliases:us(r)?r:null,meta:e}}function db(t,e){try{return _b(t,{recursive:!0}),Eb(ti(t,wb),JSON.stringify(e)),!0}catch{return!1}}function $m(t){return(t&&typeof t=="object"?bo.get(t):void 0)??JSON.stringify(t)}function Nl(t,e,n){try{_b(t,{recursive:!0}),Eb(ti(t,e),$m(n))}catch{}}function qP(t,e){let n=XP(t),r=n?[Pl(n,"data",e)]:[Pl(t,"..","..","data",e)];for(let s of r)if(vb(s))return s;return null}function XP(t){let e=Pl(t);for(;;){if(vb(Pl(e,"package.json")))return e;let n=bb(e);if(n===e)return null;e=n}}function mb(t,e,n){let r=n!==void 0?n:qP(t,e);return r===null?null:ls(r)}function Fl(t=process.env){let e=t.LMCTL_PRICE_TTL;if(e===void 0||e==="")return cb;let n=Number(e);return!Number.isFinite(n)||n<0?cb:n*1e3}function GP(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function pb(t,e,n,r){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(FP)});if(!s.ok)return{kind:"failed"};let i=s.headers.get("etag");if(n!==null&&i!==null&&i===r)return{kind:"match"};let o=await t(e,{signal:AbortSignal.timeout($P)});if(!o.ok)return{kind:"failed"};let a=await o.text(),l=JSON.parse(a);return l&&typeof l=="object"&&bo.set(l,a),{kind:"payload",payload:l,etag:o.headers.get("etag")??i}}catch{return{kind:"failed"}}}function $l(t={}){return Object.keys(t).length===0?(fb??=gb(t),fb):gb(t)}async function gb(t){let e=bb(MP(import.meta.url)),n=t.pinDir!==void 0?t.pinDir:GP();if(n!==null&&n!==""){let g=ls(Ml(n,Ol)),h=ls(Ml(n,Ll));if(cs(g)&&us(h)){let y={sha256:Dl(g,h),catalog:g,aliases:h,source:"pinned",generatedAt:g.generated_at??null};return jm=y.generatedAt,y}return hb(t,e)}let r=t.fetchImpl??fetch,s=t.cacheDir??jP(),i=t.now??Date.now(),o=t.ttlMs??Fl(),a=WP(s),l=(g,h)=>g!==null&&h.last_checked!==null&&i>=Date.parse(h.last_checked)&&i-Date.parse(h.last_checked)<o,c=a.catalog,u=a.aliases,d=!1,m=!1,p={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},f=!1;if(!l(c,a.meta.model_list)){let g=await pb(r,PP,c,a.meta.model_list.etag);g.kind==="failed"&&(m=!0),g.kind==="match"?(p.model_list.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(cs(g.payload)?(p.model_list.last_checked=new Date(i).toISOString(),f=!0,c=g.payload,g.etag!==null&&(p.model_list.etag=g.etag),d=!0):m=!0)}if(!l(u,a.meta.aliases)){let g=await pb(r,DP,u,a.meta.aliases.etag);g.kind==="failed"&&(m=!0),g.kind==="match"?(p.aliases.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(us(g.payload)?(p.aliases.last_checked=new Date(i).toISOString(),f=!0,u=g.payload,g.etag!==null&&(p.aliases.etag=g.etag),d=!0):m=!0)}if(!m&&(f||d))if(c!==null&&u!==null){let g=yb("sha256").update($m(c)).update($m(u)).digest("hex");db(s,{...p,pair_sha256:g})&&g!==a.meta.pair_sha256&&(Nl(s,Ol,c),Nl(s,Ll,u))}else c!==a.catalog&&c!==null&&Nl(s,Ol,c),u!==a.aliases&&u!==null&&Nl(s,Ll,u),db(s,p);if(c!==null||u!==null){let g={catalog:c,aliases:u,sha256:Dl(c,u),source:d?"network":"cache",refreshFailed:m,generatedAt:c?.generated_at??null};return jm=g.generatedAt,g}return{...hb(t,e),refreshFailed:m}}function hb(t,e){let n=mb(e,"price-data.json",t.bundledPath),r=mb(e,"price-aliases.json",t.bundledAliasesPath),s=cs(n)?n:null,i=us(r)?r:null,o={catalog:s,aliases:i,sha256:Dl(s,i),source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return jm=o.generatedAt,o}function Tb(t){if(t.cacheWrite!==void 0)return ei(t.cacheWrite);if(t.cacheWrite5m===void 0&&t.cacheWrite1h===void 0)return 0;let e=ei(t.cacheWrite5m),n=ei(t.cacheWrite1h);return e===null||n===null?null:ei(e+n)}function Um(t,e){let n=ei(t.cacheWrite5m===void 0?0:t.cacheWrite5m),r=ei(t.cacheWrite1h===void 0?0:t.cacheWrite1h);return n!==null&&r!==null&&Number.isSafeInteger(n+r)&&n+r===e?{five:n,one:r}:null}function Hm(t,e){let n=Zs(e.input_per_1m_tokens),r=Zs(e.output_per_1m_tokens),s=Zs(e.input_cache_read_per_1m_tokens),i=Zs(e.source_cost_fields?.cache_creation_input_token_cost),o=Zs(e.input_cache_write_per_1m_tokens)??(i===null?n:i*1e6),a=Zs(e.source_cost_fields?.cache_creation_input_token_cost_above_1hr),l=a===null?o:a*1e6,c=Tb(t),u=Um(t,c),d=c===null?null:u===null||c===0?o:u.five>0&&o===null||u.one>0&&l===null?null:(u.five*(o??0)+u.one*(l??0))/c;return{inputPer1m:n,outputPer1m:r,cacheReadPer1m:s,cacheWritePer1m:d}}function Sb(t,e){if(e===null)return null;let n=Hm(t,e),r=Tb(t);if(r===null||t.input>0&&n.inputPer1m===null||t.output>0&&n.outputPer1m===null||t.cachedInput>0&&n.cacheReadPer1m===null||r>0&&n.cacheWritePer1m===null)return null;let s=(t.input*(n.inputPer1m??0)+t.output*(n.outputPer1m??0)+t.cachedInput*(n.cacheReadPer1m??0)+r*(n.cacheWritePer1m??0))/1e6;return Number(s.toPrecision(10))}var PP,DP,FP,$P,cb,Ol,Ll,wb,UP,bo,HP,ub,jm,fb,Zs,ei,wo=L(()=>{"use strict";PP="https://lmctl.com/dataset/model_list.json",DP="https://lmctl.com/dataset/aliases.json",FP=1e3,$P=1e4,cb=6*60*60*1e3;Ol="model_list.json",Ll="aliases.json",wb="meta.json",UP="model_list.meta.json";bo=new WeakMap;HP=new Set(["established","asserted","unresolved"]);ub={etag:null,last_checked:null};jm=null,fb=null;Zs=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null,ei=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null});function ms(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function ds(t){let e=t.source_model_id.toLowerCase(),n=e.slice(e.lastIndexOf("/")+1);return ms(n)}function Rb(t){let e=new Set,n=r=>{let s=r.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(ms(s.slice(i).join("/")))};return n(t.source_model_id),t.gateway_id&&n(t.gateway_id),e}function JP(t,e){let n=new Set,r=l=>{n.add(ms(l))},s=t.trim().toLowerCase(),i=null,o=s.indexOf(":");o>0&&!s.slice(0,o).includes("/")&&(i=s.slice(0,o),r(s),s=s.slice(o+1)),r(s);let a=s.slice(s.lastIndexOf("/")+1);r(a);for(let l of e)r(`${l}/${a}`);return i!==null&&r(`${i}/${a}`),[...n]}function ps(t){let e=r=>!(r.mode!==void 0&&r.mode!==null&&r.mode!=="chat"||t.nonChatName&&t.nonChatName.test(r.source_model_id.toLowerCase())),n=r=>e(r)&&t.family.test(r.source_model_id.toLowerCase());return{firstPartyProviders:t.firstPartyProviders,isChatModel:e,coversRecord:n,normalize:r=>JP(r,t.vendorPrefixes),matchRow(r,s){if(!n(r))return!1;let i=Rb(r);return s.some(o=>i.has(o))}}}function KP(t){let e=t.trim(),n=VP.exec(e);return n?{model:e.slice(0,n.index).trim(),effort:n[1].trim()}:{model:e,effort:null}}function ZP(t,e,n){let r=e.trim().toLowerCase(),s=ms(r);if(n.records.some(o=>o.source_model_id.toLowerCase()===r&&t.matchRow(o,[s])))return!0;let i=t.normalize(e);return i.length>0&&n.records.some(o=>t.matchRow(o,i))}function eD(t,e,n){let r=[];for(let[s,i]of Object.entries(Eo))s!==n&&ZP(i,t,e)&&r.push(s);return r}function jl(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function tD(t,e){return t.input_per_1m_tokens===e.input_per_1m_tokens&&t.output_per_1m_tokens===e.output_per_1m_tokens&&t.input_cache_read_per_1m_tokens===e.input_cache_read_per_1m_tokens&&(t.input_cache_write_per_1m_tokens??null)===(e.input_cache_write_per_1m_tokens??null)&&(t.source_cost_fields?.cache_creation_input_token_cost??null)===(e.source_cost_fields?.cache_creation_input_token_cost??null)&&(t.source_cost_fields?.cache_creation_input_token_cost_above_1hr??null)===(e.source_cost_fields?.cache_creation_input_token_cost_above_1hr??null)}function nD(t){let e=new Map,n=[];for(let r of t){let s=r.source_model_id.toLowerCase(),i=s.lastIndexOf("/"),o=i===-1?"":s.slice(0,i+1),a=i===-1?s:s.slice(i+1),l=`${r.source}:${o}${ms(a)}`,c=e.get(l);if(c===void 0){e.set(l,r);continue}if(!tD(c.pricing,r.pricing)){n.push(r);continue}/\d\.\d/.test(c.source_model_id)&&!/\d\.\d/.test(r.source_model_id)&&e.set(l,r)}return[...e.values(),...n]}function Mb(t){return{route:t.record_id??`${t.source}:${t.source_model_id}`,source:t.source,sourceModelId:t.source_model_id,provider:t.provider??null,pricing:t.pricing,estimated:t.source==="manual"}}function Pb(t,e){return t.map(Mb).sort((n,r)=>{let s=jl(n.source)-jl(r.source);if(s!==0)return s;let i=n.provider!==null&&e.includes(n.provider)?0:1,o=r.provider!==null&&e.includes(r.provider)?0:1;return i!==o?i-o:n.sourceModelId.localeCompare(r.sourceModelId)})}function Ul(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function rD(t,e,n){let r=nD(t),s=Pb(r,n),o=r.find(a=>(a.record_id??`${a.source}:${a.source_model_id}`)===s[0].route)?.context_window?.input_tokens??void 0;return{id:s[0].sourceModelId,normalizedId:e,offers:s,...o!=null?{contextWindow:o}:{}}}function Bm(t,e,n,r){if(t.length===0)return{kind:"known-unpriced",id:e};let s=rD(t,e,n);if(r!==void 0){let o=t.map(Mb),a=o.filter(u=>u.provider===r&&!u.sourceModelId.includes("/")&&u.source!=="openrouter"&&!u.estimated),l=a.length>0?a:o;if(l.length!==1||!Ul(l[0]))return{kind:"known-unpriced",id:e};let c=l[0];s.offers=[c,...s.offers.filter(u=>u.route!==c.route)],s.id=c.sourceModelId}let i=s.offers.find(Ul);return i===void 0?{kind:"known-unpriced",id:e}:i.estimated?{kind:"estimated",model:s}:{kind:"priced",model:s}}function sD(t,e){return t.standards.find(n=>n.standard_slug.toLowerCase()===e.toLowerCase())??null}function iD(t,e,n){let r=t.standard_slug;if(e===null||e.catalog_record_id===null)return{kind:"known-unpriced",id:r};let s=e.catalog_record_id,i=d=>d.record_id??d.source+":"+d.source_model_id,o=n.records.find(d=>i(d)===s),a=o?[]:n.records.filter(d=>i(d).toLowerCase()===s.toLowerCase()),l=o??(a.length===1?a[0]:void 0);if(!l)return{kind:"known-unpriced",id:r};let c=ds(l),u=n.records.filter(d=>ds(d)!==c?!1:d.mode===void 0||d.mode===null||d.mode==="chat");return u.length===0?{kind:"known-unpriced",id:r}:Bm(u,c,Wm)}function Db(t,e,n,r){if(n===null||!Array.isArray(n.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(r!==null){let g=[e.trim().toLowerCase()];g.push(`${t.toLowerCase()}/${g[0]}`);let h=r.aliases.find(y=>g.includes(y.alias.toLowerCase()));if(h){if(h.evidence==="unresolved"||h.standard_slug===null)return{state:{kind:"unresolved",alias:h.alias},viaAlias:!0,pinRoute:null};let y=sD(r,h.standard_slug);return{state:iD(h,y,n),viaAlias:!0,pinRoute:y?.catalog_record_id??null}}}let s=Eo[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=g=>({state:g,viaAlias:!1,pinRoute:null}),l=ms(i),c=n.records.filter(g=>g.source_model_id.toLowerCase()===i&&s.matchRow(g,[l]));if(c.length>0){let g=ds(c[0]),h=n.records.filter(y=>s.matchRow(y,[g])&&ds(y)===g);return a(Bm(h.length>0?h:c,g,kb[t]??Wm,t==="codex"?"openai":void 0))}let u=n.records.filter(g=>s.matchRow(g,o));if(u.length===0){let g=eD(e,n,t);return g.length>0?a({kind:"wrong-provider",declared:e,otherProviders:g}):a({kind:"unknown",declared:e})}let d=new Map;for(let g of u){let h=ds(g),y=d.get(h);y?y.push(g):d.set(h,[g])}let m=kb[t]??Wm,p=null,f=null;for(let g of d.values()){let h=Pb(g,m);(f===null||oD(h[0],f[0],m)<0)&&(p=g,f=h)}return a(Bm(p,ds(p[0]),m,t==="codex"?"openai":void 0))}function Fb(t,e,n,r){return Db(t,e,n,r).state}function $b(t,e,n,r){let{state:s,viaAlias:i,pinRoute:o}=Db(t,e,n,r);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(u=>u.route===o)??a.find(u=>u.route.toLowerCase()===o.toLowerCase());if(c!==void 0&&Ul(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Ul)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function jb(t,e){let n=Eo[e];if(!n)return null;let r=new Set;for(let s of t.records)n.coversRecord(s)&&r.add(ds(s));return r.size}function oD(t,e,n){let r=jl(t.source)-jl(e.source);if(r!==0)return r;let s=t.provider!==null&&n.includes(t.provider)?0:1,i=e.provider!==null&&n.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var Ib,xb,Ab,Cb,Nb,Ob,VP,zP,YP,QP,Lb,Eo,kb,Wm,qm=L(()=>{"use strict";Ib=ps({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),xb=ps({vendorPrefixes:["openai"],family:/(^|\/)(gpt-|o\d|chatgpt|ft:gpt)|openai\//,firstPartyProviders:["openai"],nonChatName:/(^|[-/])(tts|transcribe(?:-\w+)?|realtime(?:-\w+)?|search(?:-\w+)*|image(?:-\w+)?|audio(?:-\w+)?|whisper(?:-\w+)?|dall-e(?:-\w+)?|embedding|moderation)(-|$)/}),Ab=ps({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),Cb=ps({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Nb=ps({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),Ob=ps({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),VP=/\s*\(([^()]+)\)\s*$/;zP={"gemini 3.8 flash":"gemini-3.8-flash","gemini 3.7 flash":"gemini-3.7-flash","gemini 3.6 flash":"gemini-3.6-flash","gemini 3.1 pro":"gemini/gemini-3.1-pro-preview","claude sonnet 4.6":"claude-sonnet-4-6"},YP=["gemini","google","vertex_ai-language-models","anthropic"],QP={normalize(t){let{model:e}=KP(t),n=zP[e.toLowerCase()];return n===void 0?[]:[ms(n)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let n=Rb(t);return e.some(r=>n.has(r))}},Lb=ps({vendorPrefixes:["deepseek"],family:/deepseek/,firstPartyProviders:["deepseek"]}),Eo={claude:Ib,codex:xb,gemini:Ab,agy:QP,kimi:Cb,qwen:Nb,hermes:Ob,deepseek:Lb},kb={claude:Ib.firstPartyProviders,codex:xb.firstPartyProviders,gemini:Ab.firstPartyProviders,agy:YP,kimi:Cb.firstPartyProviders,qwen:Nb.firstPartyProviders,hermes:Ob.firstPartyProviders,deepseek:Lb.firstPartyProviders};Wm=[]});import{randomUUID as aD}from"node:crypto";function Hl(t){return{startedAt:new Date().toISOString(),attempt_key:aD(),provider:t.provider,model_requested:t.modelRequested,cwd:t.cwd,native_session_id:t.sessionId||null}}function ni(t,e){return e?"cancelled":/\bstall(?:ed|ing)?\b/i.test(t)?"stalled":"error"}async function To(t,e,n=async()=>({catalog:null,aliases:null,source:"unavailable",generatedAt:null}),r){let s={...t,ended_at:new Date().toISOString(),turn_outcome:e.status,native_session_id:e.sessionId||t.native_session_id||null};try{let i=["claude","codex","muse","dsh"].includes(t.provider)||Al.includes(t.provider)&&e.usage?.source==="wire"?e.usage:r&&Al.includes(t.provider)?await ob(t,e.sessionId||String(t.native_session_id??""),String(s.ended_at),r):void 0;if(e.status!=="cancelled"&&(i?.outcome==="cancelled"||i?.outcome==="error")&&(s.turn_outcome=i.outcome),!i||i.source===null)return s.usage_source=null,s.usage_reason=t.provider==="ClaudeMock"?"mock_estimate":s.turn_outcome!=="ok"?"turn_not_completed":["copilot","hermes"].includes(t.provider)?"session_totals_only":"native_record_missing",s.cost_reason="usage_unavailable",s;if(Object.assign(s,{usage_source:i.source,usage_reason:i.reason,tok_input_uncached:Hn(i.inputUncached),tok_cache_read:Hn(i.cacheRead),tok_cache_write:Hn(i.cacheWrite),tok_output:Hn(i.output),tok_reasoning:Hn(i.reasoning),model_reported:i.modelReported,provider_cost_usd:lD(i.providerCostUsd)}),i.invalidCounters||gn([i.inputUncached,i.cacheRead,i.cacheWrite,i.output,i.reasoning]))return s.usage_reason="counter_not_exposed",s.cost_reason="usage_unavailable",s;if(i.mixedModels)return s.cost_reason="mixed_models",s.model_reported=null,s;let o=i.modelReported||t.model_requested;if(!o)return s.cost_reason="model_unknown",s;let a,l=await Promise.race([n(),new Promise(f=>{a=setTimeout(()=>f(null),1e3)})]).finally(()=>{a&&clearTimeout(a)});if(!l||!l.catalog)return s.cost_reason="price_data_unavailable",s;let c=$b(t.provider,o,l.catalog,l.aliases);if(!c.offer)return s.cost_reason=c.state.kind==="unresolved"?"model_unresolved":c.state.kind==="unknown"||c.state.kind==="wrong-provider"?"model_unknown":"model_unpriced",s;let u=l.catalog.records.find(f=>(f.record_id??f.source+":"+f.source_model_id)===c.offer.route),d=c.offer.pricing,m={input:Hn(i.inputUncached)??0,output:Hn(i.output)??0,cachedInput:Hn(i.cacheRead)??0,cacheWrite:Hn(i.cacheWrite)??0,...i.cacheWrite5m==null?{}:{cacheWrite5m:i.cacheWrite5m},...i.cacheWrite1h==null?{}:{cacheWrite1h:i.cacheWrite1h}},p=Hm(m,d);return Object.assign(s,{price_record_id:u?.record_id??null,price_snapshot_sha256:l.sha256??null,rate_input_1m:p.inputPer1m,rate_output_1m:p.outputPer1m,rate_cache_read_1m:p.cacheReadPer1m,rate_cache_write_1m:p.cacheWritePer1m}),s.cost_reason=Sb(m,d)===null?"rate_missing":null,s}catch{return{...s,usage_reason:"recorder_failed",cost_reason:"usage_unavailable"}}}function fs(t,e,n){try{let r=Object.entries(n).filter(([s])=>Object.hasOwn(Cl,s));if(!r.length)return;t.prepare(`UPDATE team_chat_log SET ${r.map(([s])=>`${s}=?`).join(",")} WHERE id=? AND ended_at IS NULL`).run(...r.map(([,s])=>s??null),e)}catch(r){for(let i of["usage_source","model_reported","tok_input_uncached","tok_cache_read","tok_cache_write","tok_output","tok_reasoning","price_record_id","price_snapshot_sha256","rate_input_1m","rate_output_1m","rate_cache_read_1m","rate_cache_write_1m","provider_cost_usd"])n[i]=null;n.usage_reason="recorder_failed",n.cost_reason="usage_unavailable";let s=r?.code??"";if(/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/.test(s))return;try{t.prepare("UPDATE team_chat_log SET attempt_key=COALESCE(attempt_key,?),provider=COALESCE(provider,?),native_session_id=COALESCE(native_session_id,?),cwd=COALESCE(cwd,?),model_requested=COALESCE(model_requested,?),ended_at=COALESCE(ended_at,?),turn_outcome=COALESCE(turn_outcome,?),usage_reason='recorder_failed',cost_reason='usage_unavailable' WHERE id=? AND ended_at IS NULL").run(n.attempt_key??null,n.provider??null,n.native_session_id??null,n.cwd??null,n.model_requested??null,n.ended_at??null,n.turn_outcome??null,e)}catch{}}}var Hn,lD,So=L(()=>{"use strict";ab();vo();Dm();wo();qm();Hn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,lD=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null});var Ub,Hb=L(()=>{"use strict";Ub=`
|
|
519
|
+
`});import{createHash as yb}from"node:crypto";import{mkdirSync as _b,readFileSync as CP,renameSync as NP,writeFileSync as OP,existsSync as vb}from"node:fs";import{homedir as LP}from"node:os";import{dirname as bb,join as Ml,resolve as Pl}from"node:path";import{fileURLToPath as MP}from"node:url";function jP(){return Ml(LP(),".lmctl","cache","lmprice")}function ti(t,e){return Ml(t,e)}function Dl(t,e){if(!t||!e)return null;let n=bo.get(t),r=bo.get(e);return n===void 0||r===void 0?null:yb("sha256").update(n).update(r).digest("hex")}function ls(t){try{let e=CP(t,"utf-8"),n=JSON.parse(e);return n&&typeof n=="object"&&bo.set(n,e),n}catch{return null}}function Eb(t,e){let n=`${t}.tmp-${process.pid}`;OP(n,e),NP(n,t)}function Fm(t){return t===null||typeof t=="number"}function cs(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.schema_version!==1||!Array.isArray(e.records)||e.records.length===0?!1:e.records.every(n=>{if(typeof n!="object"||n===null)return!1;let r=n;if(typeof r.source!="string"||typeof r.source_model_id!="string"||typeof r.pricing!="object"||r.pricing===null)return!1;let s=r.pricing;return Fm(s.input_per_1m_tokens)&&Fm(s.output_per_1m_tokens)&&Fm(s.input_cache_read_per_1m_tokens)})}function us(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.schema_version!==1||!Array.isArray(e.standards)||!Array.isArray(e.aliases))return!1;let n=e.standards.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.standard_slug=="string"&&(i.catalog_record_id===null||typeof i.catalog_record_id=="string")}),r=e.aliases.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.alias=="string"&&(i.standard_slug===null||typeof i.standard_slug=="string")&&typeof i.evidence=="string"&&HP.has(i.evidence)});return n&&r}function BP(t){let e=ls(ti(t,wb)),n={etag:typeof e?.model_list?.etag=="string"?e.model_list.etag:null,last_checked:typeof e?.model_list?.last_checked=="string"?e.model_list.last_checked:null},r={etag:typeof e?.aliases?.etag=="string"?e.aliases.etag:null,last_checked:typeof e?.aliases?.last_checked=="string"?e.aliases.last_checked:null};if(e===null){let s=ls(ti(t,UP));s&&(n.etag=typeof s.etag=="string"?s.etag:null,n.last_checked=typeof s.fetchedAt=="string"?s.fetchedAt:null)}return{model_list:n,aliases:r,...typeof e?.pair_sha256=="string"?{pair_sha256:e.pair_sha256}:{}}}function WP(t){let e=BP(t),n=ls(ti(t,Ol)),r=ls(ti(t,Ll));return e.pair_sha256&&Dl(cs(n)?n:null,us(r)?r:null)!==e.pair_sha256?{catalog:null,aliases:null,meta:{model_list:{...ub},aliases:{...ub}}}:{catalog:cs(n)?n:null,aliases:us(r)?r:null,meta:e}}function db(t,e){try{return _b(t,{recursive:!0}),Eb(ti(t,wb),JSON.stringify(e)),!0}catch{return!1}}function $m(t){return(t&&typeof t=="object"?bo.get(t):void 0)??JSON.stringify(t)}function Nl(t,e,n){try{_b(t,{recursive:!0}),Eb(ti(t,e),$m(n))}catch{}}function qP(t,e){let n=XP(t),r=n?[Pl(n,"data",e)]:[Pl(t,"..","..","data",e)];for(let s of r)if(vb(s))return s;return null}function XP(t){let e=Pl(t);for(;;){if(vb(Pl(e,"package.json")))return e;let n=bb(e);if(n===e)return null;e=n}}function mb(t,e,n){let r=n!==void 0?n:qP(t,e);return r===null?null:ls(r)}function Fl(t=process.env){let e=t.LMCTL_PRICE_TTL;if(e===void 0||e==="")return cb;let n=Number(e);return!Number.isFinite(n)||n<0?cb:n*1e3}function GP(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function pb(t,e,n,r){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(FP)});if(!s.ok)return{kind:"failed"};let i=s.headers.get("etag");if(n!==null&&i!==null&&i===r)return{kind:"match"};let o=await t(e,{signal:AbortSignal.timeout($P)});if(!o.ok)return{kind:"failed"};let a=await o.text(),l=JSON.parse(a);return l&&typeof l=="object"&&bo.set(l,a),{kind:"payload",payload:l,etag:o.headers.get("etag")??i}}catch{return{kind:"failed"}}}function $l(t={}){return Object.keys(t).length===0?(fb??=gb(t),fb):gb(t)}async function gb(t){let e=bb(MP(import.meta.url)),n=t.pinDir!==void 0?t.pinDir:GP();if(n!==null&&n!==""){let g=ls(Ml(n,Ol)),h=ls(Ml(n,Ll));if(cs(g)&&us(h)){let y={sha256:Dl(g,h),catalog:g,aliases:h,source:"pinned",generatedAt:g.generated_at??null};return jm=y.generatedAt,y}return hb(t,e)}let r=t.fetchImpl??fetch,s=t.cacheDir??jP(),i=t.now??Date.now(),o=t.ttlMs??Fl(),a=WP(s),l=(g,h)=>g!==null&&h.last_checked!==null&&i>=Date.parse(h.last_checked)&&i-Date.parse(h.last_checked)<o,c=a.catalog,u=a.aliases,d=!1,m=!1,p={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},f=!1;if(!l(c,a.meta.model_list)){let g=await pb(r,PP,c,a.meta.model_list.etag);g.kind==="failed"&&(m=!0),g.kind==="match"?(p.model_list.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(cs(g.payload)?(p.model_list.last_checked=new Date(i).toISOString(),f=!0,c=g.payload,g.etag!==null&&(p.model_list.etag=g.etag),d=!0):m=!0)}if(!l(u,a.meta.aliases)){let g=await pb(r,DP,u,a.meta.aliases.etag);g.kind==="failed"&&(m=!0),g.kind==="match"?(p.aliases.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(us(g.payload)?(p.aliases.last_checked=new Date(i).toISOString(),f=!0,u=g.payload,g.etag!==null&&(p.aliases.etag=g.etag),d=!0):m=!0)}if(!m&&(f||d))if(c!==null&&u!==null){let g=yb("sha256").update($m(c)).update($m(u)).digest("hex");db(s,{...p,pair_sha256:g})&&g!==a.meta.pair_sha256&&(Nl(s,Ol,c),Nl(s,Ll,u))}else c!==a.catalog&&c!==null&&Nl(s,Ol,c),u!==a.aliases&&u!==null&&Nl(s,Ll,u),db(s,p);if(c!==null||u!==null){let g={catalog:c,aliases:u,sha256:Dl(c,u),source:d?"network":"cache",refreshFailed:m,generatedAt:c?.generated_at??null};return jm=g.generatedAt,g}return{...hb(t,e),refreshFailed:m}}function hb(t,e){let n=mb(e,"price-data.json",t.bundledPath),r=mb(e,"price-aliases.json",t.bundledAliasesPath),s=cs(n)?n:null,i=us(r)?r:null,o={catalog:s,aliases:i,sha256:Dl(s,i),source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return jm=o.generatedAt,o}function Tb(t){if(t.cacheWrite!==void 0)return ei(t.cacheWrite);if(t.cacheWrite5m===void 0&&t.cacheWrite1h===void 0)return 0;let e=ei(t.cacheWrite5m),n=ei(t.cacheWrite1h);return e===null||n===null?null:ei(e+n)}function Um(t,e){let n=ei(t.cacheWrite5m===void 0?0:t.cacheWrite5m),r=ei(t.cacheWrite1h===void 0?0:t.cacheWrite1h);return n!==null&&r!==null&&Number.isSafeInteger(n+r)&&n+r===e?{five:n,one:r}:null}function Hm(t,e){let n=Zs(e.input_per_1m_tokens),r=Zs(e.output_per_1m_tokens),s=Zs(e.input_cache_read_per_1m_tokens),i=Zs(e.source_cost_fields?.cache_creation_input_token_cost),o=Zs(e.input_cache_write_per_1m_tokens)??(i===null?n:i*1e6),a=Zs(e.source_cost_fields?.cache_creation_input_token_cost_above_1hr),l=a===null?o:a*1e6,c=Tb(t),u=Um(t,c),d=c===null?null:u===null||c===0?o:u.five>0&&o===null||u.one>0&&l===null?null:(u.five*(o??0)+u.one*(l??0))/c;return{inputPer1m:n,outputPer1m:r,cacheReadPer1m:s,cacheWritePer1m:d}}function Sb(t,e){if(e===null)return null;let n=Hm(t,e),r=Tb(t);if(r===null||t.input>0&&n.inputPer1m===null||t.output>0&&n.outputPer1m===null||t.cachedInput>0&&n.cacheReadPer1m===null||r>0&&n.cacheWritePer1m===null)return null;let s=(t.input*(n.inputPer1m??0)+t.output*(n.outputPer1m??0)+t.cachedInput*(n.cacheReadPer1m??0)+r*(n.cacheWritePer1m??0))/1e6;return Number(s.toPrecision(10))}var PP,DP,FP,$P,cb,Ol,Ll,wb,UP,bo,HP,ub,jm,fb,Zs,ei,wo=L(()=>{"use strict";PP="https://lmctl.com/dataset/model_list.json",DP="https://lmctl.com/dataset/aliases.json",FP=1e3,$P=1e4,cb=6*60*60*1e3;Ol="model_list.json",Ll="aliases.json",wb="meta.json",UP="model_list.meta.json";bo=new WeakMap;HP=new Set(["established","asserted","unresolved"]);ub={etag:null,last_checked:null};jm=null,fb=null;Zs=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null,ei=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null});function ms(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function ds(t){let e=t.source_model_id.toLowerCase(),n=e.slice(e.lastIndexOf("/")+1);return ms(n)}function Rb(t){let e=new Set,n=r=>{let s=r.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(ms(s.slice(i).join("/")))};return n(t.source_model_id),t.gateway_id&&n(t.gateway_id),e}function JP(t,e){let n=new Set,r=l=>{n.add(ms(l))},s=t.trim().toLowerCase(),i=null,o=s.indexOf(":");o>0&&!s.slice(0,o).includes("/")&&(i=s.slice(0,o),r(s),s=s.slice(o+1)),r(s);let a=s.slice(s.lastIndexOf("/")+1);r(a);for(let l of e)r(`${l}/${a}`);return i!==null&&r(`${i}/${a}`),[...n]}function ps(t){let e=r=>!(r.mode!==void 0&&r.mode!==null&&r.mode!=="chat"||t.nonChatName&&t.nonChatName.test(r.source_model_id.toLowerCase())),n=r=>e(r)&&t.family.test(r.source_model_id.toLowerCase());return{firstPartyProviders:t.firstPartyProviders,isChatModel:e,coversRecord:n,normalize:r=>JP(r,t.vendorPrefixes),matchRow(r,s){if(!n(r))return!1;let i=Rb(r);return s.some(o=>i.has(o))}}}function KP(t){let e=t.trim(),n=VP.exec(e);return n?{model:e.slice(0,n.index).trim(),effort:n[1].trim()}:{model:e,effort:null}}function ZP(t,e,n){let r=e.trim().toLowerCase(),s=ms(r);if(n.records.some(o=>o.source_model_id.toLowerCase()===r&&t.matchRow(o,[s])))return!0;let i=t.normalize(e);return i.length>0&&n.records.some(o=>t.matchRow(o,i))}function eD(t,e,n){let r=[];for(let[s,i]of Object.entries(Eo))s!==n&&ZP(i,t,e)&&r.push(s);return r}function jl(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function tD(t,e){return t.input_per_1m_tokens===e.input_per_1m_tokens&&t.output_per_1m_tokens===e.output_per_1m_tokens&&t.input_cache_read_per_1m_tokens===e.input_cache_read_per_1m_tokens&&(t.input_cache_write_per_1m_tokens??null)===(e.input_cache_write_per_1m_tokens??null)&&(t.source_cost_fields?.cache_creation_input_token_cost??null)===(e.source_cost_fields?.cache_creation_input_token_cost??null)&&(t.source_cost_fields?.cache_creation_input_token_cost_above_1hr??null)===(e.source_cost_fields?.cache_creation_input_token_cost_above_1hr??null)}function nD(t){let e=new Map,n=[];for(let r of t){let s=r.source_model_id.toLowerCase(),i=s.lastIndexOf("/"),o=i===-1?"":s.slice(0,i+1),a=i===-1?s:s.slice(i+1),l=`${r.source}:${o}${ms(a)}`,c=e.get(l);if(c===void 0){e.set(l,r);continue}if(!tD(c.pricing,r.pricing)){n.push(r);continue}/\d\.\d/.test(c.source_model_id)&&!/\d\.\d/.test(r.source_model_id)&&e.set(l,r)}return[...e.values(),...n]}function Mb(t){return{route:t.record_id??`${t.source}:${t.source_model_id}`,source:t.source,sourceModelId:t.source_model_id,provider:t.provider??null,pricing:t.pricing,estimated:t.source==="manual"}}function Pb(t,e){return t.map(Mb).sort((n,r)=>{let s=jl(n.source)-jl(r.source);if(s!==0)return s;let i=n.provider!==null&&e.includes(n.provider)?0:1,o=r.provider!==null&&e.includes(r.provider)?0:1;return i!==o?i-o:n.sourceModelId.localeCompare(r.sourceModelId)})}function Ul(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function rD(t,e,n){let r=nD(t),s=Pb(r,n),o=r.find(a=>(a.record_id??`${a.source}:${a.source_model_id}`)===s[0].route)?.context_window?.input_tokens??void 0;return{id:s[0].sourceModelId,normalizedId:e,offers:s,...o!=null?{contextWindow:o}:{}}}function Bm(t,e,n,r){if(t.length===0)return{kind:"known-unpriced",id:e};let s=rD(t,e,n);if(r!==void 0){let o=t.map(Mb),a=o.filter(u=>u.provider===r&&!u.sourceModelId.includes("/")&&u.source!=="openrouter"&&!u.estimated),l=a.length>0?a:o;if(l.length!==1||!Ul(l[0]))return{kind:"known-unpriced",id:e};let c=l[0];s.offers=[c,...s.offers.filter(u=>u.route!==c.route)],s.id=c.sourceModelId}let i=s.offers.find(Ul);return i===void 0?{kind:"known-unpriced",id:e}:i.estimated?{kind:"estimated",model:s}:{kind:"priced",model:s}}function sD(t,e){return t.standards.find(n=>n.standard_slug.toLowerCase()===e.toLowerCase())??null}function iD(t,e,n){let r=t.standard_slug;if(e===null||e.catalog_record_id===null)return{kind:"known-unpriced",id:r};let s=e.catalog_record_id,i=d=>d.record_id??d.source+":"+d.source_model_id,o=n.records.find(d=>i(d)===s),a=o?[]:n.records.filter(d=>i(d).toLowerCase()===s.toLowerCase()),l=o??(a.length===1?a[0]:void 0);if(!l)return{kind:"known-unpriced",id:r};let c=ds(l),u=n.records.filter(d=>ds(d)!==c?!1:d.mode===void 0||d.mode===null||d.mode==="chat");return u.length===0?{kind:"known-unpriced",id:r}:Bm(u,c,Wm)}function Db(t,e,n,r){if(n===null||!Array.isArray(n.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(r!==null){let g=[e.trim().toLowerCase()];g.push(`${t.toLowerCase()}/${g[0]}`);let h=r.aliases.find(y=>g.includes(y.alias.toLowerCase()));if(h){if(h.evidence==="unresolved"||h.standard_slug===null)return{state:{kind:"unresolved",alias:h.alias},viaAlias:!0,pinRoute:null};let y=sD(r,h.standard_slug);return{state:iD(h,y,n),viaAlias:!0,pinRoute:y?.catalog_record_id??null}}}let s=Eo[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=g=>({state:g,viaAlias:!1,pinRoute:null}),l=ms(i),c=n.records.filter(g=>g.source_model_id.toLowerCase()===i&&s.matchRow(g,[l]));if(c.length>0){let g=ds(c[0]),h=n.records.filter(y=>s.matchRow(y,[g])&&ds(y)===g);return a(Bm(h.length>0?h:c,g,kb[t]??Wm,t==="codex"?"openai":void 0))}let u=n.records.filter(g=>s.matchRow(g,o));if(u.length===0){let g=eD(e,n,t);return g.length>0?a({kind:"wrong-provider",declared:e,otherProviders:g}):a({kind:"unknown",declared:e})}let d=new Map;for(let g of u){let h=ds(g),y=d.get(h);y?y.push(g):d.set(h,[g])}let m=kb[t]??Wm,p=null,f=null;for(let g of d.values()){let h=Pb(g,m);(f===null||oD(h[0],f[0],m)<0)&&(p=g,f=h)}return a(Bm(p,ds(p[0]),m,t==="codex"?"openai":void 0))}function Fb(t,e,n,r){return Db(t,e,n,r).state}function $b(t,e,n,r){let{state:s,viaAlias:i,pinRoute:o}=Db(t,e,n,r);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(u=>u.route===o)??a.find(u=>u.route.toLowerCase()===o.toLowerCase());if(c!==void 0&&Ul(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Ul)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function jb(t,e){let n=Eo[e];if(!n)return null;let r=new Set;for(let s of t.records)n.coversRecord(s)&&r.add(ds(s));return r.size}function oD(t,e,n){let r=jl(t.source)-jl(e.source);if(r!==0)return r;let s=t.provider!==null&&n.includes(t.provider)?0:1,i=e.provider!==null&&n.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var Ib,xb,Ab,Cb,Nb,Ob,VP,zP,YP,QP,Lb,Eo,kb,Wm,qm=L(()=>{"use strict";Ib=ps({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),xb=ps({vendorPrefixes:["openai"],family:/(^|\/)(gpt-|o\d|chatgpt|ft:gpt)|openai\//,firstPartyProviders:["openai"],nonChatName:/(^|[-/])(tts|transcribe(?:-\w+)?|realtime(?:-\w+)?|search(?:-\w+)*|image(?:-\w+)?|audio(?:-\w+)?|whisper(?:-\w+)?|dall-e(?:-\w+)?|embedding|moderation)(-|$)/}),Ab=ps({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),Cb=ps({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Nb=ps({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),Ob=ps({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),VP=/\s*\(([^()]+)\)\s*$/;zP={"gemini 3.8 flash":"gemini-3.8-flash","gemini 3.7 flash":"gemini-3.7-flash","gemini 3.6 flash":"gemini-3.6-flash","gemini 3.1 pro":"gemini/gemini-3.1-pro-preview","claude sonnet 4.6":"claude-sonnet-4-6"},YP=["gemini","google","vertex_ai-language-models","anthropic"],QP={normalize(t){let{model:e}=KP(t),n=zP[e.toLowerCase()];return n===void 0?[]:[ms(n)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let n=Rb(t);return e.some(r=>n.has(r))}},Lb=ps({vendorPrefixes:["deepseek"],family:/deepseek/,firstPartyProviders:["deepseek"]}),Eo={claude:Ib,codex:xb,gemini:Ab,agy:QP,kimi:Cb,qwen:Nb,hermes:Ob,deepseek:Lb},kb={claude:Ib.firstPartyProviders,codex:xb.firstPartyProviders,gemini:Ab.firstPartyProviders,agy:YP,kimi:Cb.firstPartyProviders,qwen:Nb.firstPartyProviders,hermes:Ob.firstPartyProviders,deepseek:Lb.firstPartyProviders};Wm=[]});import{randomUUID as aD}from"node:crypto";function Hl(t){return{startedAt:new Date().toISOString(),attempt_key:aD(),provider:t.provider,model_requested:t.modelRequested,cwd:t.cwd,native_session_id:t.sessionId||null}}function ni(t,e){return e?"cancelled":/\bstall(?:ed|ing)?\b/i.test(t)?"stalled":"error"}async function To(t,e,n=async()=>({catalog:null,aliases:null,source:"unavailable",generatedAt:null}),r){let s={...t,ended_at:new Date().toISOString(),turn_outcome:e.status,native_session_id:e.sessionId||t.native_session_id||null};try{let i=["claude","codex","muse","dsh"].includes(t.provider)||Al.includes(t.provider)&&e.usage?.source==="wire"?e.usage:r&&Al.includes(t.provider)?await ob(t,e.sessionId||String(t.native_session_id??""),String(s.ended_at),r):void 0;if(e.status!=="cancelled"&&(i?.outcome==="cancelled"||i?.outcome==="error")&&(s.turn_outcome=i.outcome),!i||i.source===null)return s.usage_source=null,s.usage_reason=t.provider==="ClaudeMock"?"mock_estimate":s.turn_outcome!=="ok"?"turn_not_completed":["copilot","hermes"].includes(t.provider)?"session_totals_only":"native_record_missing",s.cost_reason="usage_unavailable",s;if(Object.assign(s,{usage_source:i.source,usage_reason:i.reason,tok_input_uncached:Hn(i.inputUncached),tok_cache_read:Hn(i.cacheRead),tok_cache_write:Hn(i.cacheWrite),tok_output:Hn(i.output),tok_reasoning:Hn(i.reasoning),model_reported:i.modelReported,provider_cost_usd:lD(i.providerCostUsd)}),i.invalidCounters||hn([i.inputUncached,i.cacheRead,i.cacheWrite,i.output,i.reasoning]))return s.usage_reason="counter_not_exposed",s.cost_reason="usage_unavailable",s;if(i.mixedModels)return s.cost_reason="mixed_models",s.model_reported=null,s;let o=i.modelReported||t.model_requested;if(!o)return s.cost_reason="model_unknown",s;let a,l=await Promise.race([n(),new Promise(f=>{a=setTimeout(()=>f(null),1e3)})]).finally(()=>{a&&clearTimeout(a)});if(!l||!l.catalog)return s.cost_reason="price_data_unavailable",s;let c=$b(t.provider,o,l.catalog,l.aliases);if(!c.offer)return s.cost_reason=c.state.kind==="unresolved"?"model_unresolved":c.state.kind==="unknown"||c.state.kind==="wrong-provider"?"model_unknown":"model_unpriced",s;let u=l.catalog.records.find(f=>(f.record_id??f.source+":"+f.source_model_id)===c.offer.route),d=c.offer.pricing,m={input:Hn(i.inputUncached)??0,output:Hn(i.output)??0,cachedInput:Hn(i.cacheRead)??0,cacheWrite:Hn(i.cacheWrite)??0,...i.cacheWrite5m==null?{}:{cacheWrite5m:i.cacheWrite5m},...i.cacheWrite1h==null?{}:{cacheWrite1h:i.cacheWrite1h}},p=Hm(m,d);return Object.assign(s,{price_record_id:u?.record_id??null,price_snapshot_sha256:l.sha256??null,rate_input_1m:p.inputPer1m,rate_output_1m:p.outputPer1m,rate_cache_read_1m:p.cacheReadPer1m,rate_cache_write_1m:p.cacheWritePer1m}),s.cost_reason=Sb(m,d)===null?"rate_missing":null,s}catch{return{...s,usage_reason:"recorder_failed",cost_reason:"usage_unavailable"}}}function fs(t,e,n){try{let r=Object.entries(n).filter(([s])=>Object.hasOwn(Cl,s));if(!r.length)return;t.prepare(`UPDATE team_chat_log SET ${r.map(([s])=>`${s}=?`).join(",")} WHERE id=? AND ended_at IS NULL`).run(...r.map(([,s])=>s??null),e)}catch(r){for(let i of["usage_source","model_reported","tok_input_uncached","tok_cache_read","tok_cache_write","tok_output","tok_reasoning","price_record_id","price_snapshot_sha256","rate_input_1m","rate_output_1m","rate_cache_read_1m","rate_cache_write_1m","provider_cost_usd"])n[i]=null;n.usage_reason="recorder_failed",n.cost_reason="usage_unavailable";let s=r?.code??"";if(/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/.test(s))return;try{t.prepare("UPDATE team_chat_log SET attempt_key=COALESCE(attempt_key,?),provider=COALESCE(provider,?),native_session_id=COALESCE(native_session_id,?),cwd=COALESCE(cwd,?),model_requested=COALESCE(model_requested,?),ended_at=COALESCE(ended_at,?),turn_outcome=COALESCE(turn_outcome,?),usage_reason='recorder_failed',cost_reason='usage_unavailable' WHERE id=? AND ended_at IS NULL").run(n.attempt_key??null,n.provider??null,n.native_session_id??null,n.cwd??null,n.model_requested??null,n.ended_at??null,n.turn_outcome??null,e)}catch{}}}var Hn,lD,So=L(()=>{"use strict";ab();vo();Dm();wo();qm();Hn=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,lD=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null});var Ub,Hb=L(()=>{"use strict";Ub=`
|
|
520
520
|
CREATE TABLE IF NOT EXISTS price_snapshot (
|
|
521
521
|
sha256 TEXT PRIMARY KEY,
|
|
522
522
|
generated_at TEXT,
|
|
@@ -1691,7 +1691,7 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1691
1691
|
AND status = 'running'
|
|
1692
1692
|
AND launch_source = 'terminal'
|
|
1693
1693
|
ORDER BY started_at DESC, id DESC
|
|
1694
|
-
LIMIT 1`,e,n)[0]??null}function PD(t){return t.holder_pid!==null&&(t.holder_host===null||t.holder_host===ri())?ct(t.holder_pid):DD(t)}function DD(t){let e=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(e)?Date.now()-e<=Rr():!1}function Vl(t,e){return t.holder_pid===null?t.started_at<e:!ct(t.holder_pid)}function Rr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return cw;let n=Number(e);return!Number.isFinite(n)||n<=0?cw:n}function FD(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return uw;let n=Number(e);return!Number.isFinite(n)||n<=0?uw:n}var cw,uw,Xm,
|
|
1694
|
+
LIMIT 1`,e,n)[0]??null}function PD(t){return t.holder_pid!==null&&(t.holder_host===null||t.holder_host===ri())?ct(t.holder_pid):DD(t)}function DD(t){let e=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(e)?Date.now()-e<=Rr():!1}function Vl(t,e){return t.holder_pid===null?t.started_at<e:!ct(t.holder_pid)}function Rr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return cw;let n=Number(e);return!Number.isFinite(n)||n<=0?cw:n}function FD(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return uw;let n=Number(e);return!Number.isFinite(n)||n<=0?uw:n}var cw,uw,Xm,yn=L(()=>{"use strict";Tr();cw=8*60*60*1e3,uw=12e4,Xm=3e4});import{randomUUID as $D}from"node:crypto";import{hostname as jD}from"node:os";function Ir(t,e){return{teamfile:t,alias:e}}function dw(t,e,n={}){return{teamfile:t,alias:e,...n.provider===void 0||n.provider===null?{}:{provider:n.provider},...n.sessionId===void 0||n.sessionId===null?{}:{session_id:n.sessionId}}}function Gm(t,e){return t===null?null:Ir(t,e??"")}function Bn(t){return`msg_tcl_${t}`}function ys(t){return`inv_${t}`}function ii(t,e,n){return t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias,
|
|
1695
1695
|
holder_pid, holder_host, started_at, terminal_lock_id,
|
|
1696
1696
|
terminal_invocation_id, currently_handling_message_id,
|
|
1697
1697
|
currently_handling_since, last_seq
|
|
@@ -1751,7 +1751,7 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1751
1751
|
terminal_invocation_host = NULL,
|
|
1752
1752
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1753
1753
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1754
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,r.receiver_teamfile,r.receiver_alias,n,r.last_seq);oi(s.changes,"terminal INVOCATION_FINISH")}var UD,zl=L(()=>{"use strict";Bl();
|
|
1754
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,r.receiver_teamfile,r.receiver_alias,n,r.last_seq);oi(s.changes,"terminal INVOCATION_FINISH")}var UD,zl=L(()=>{"use strict";Bl();yn();Tr();UD=60*60*1e3});function vw(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function Ym(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function bw(t,e){let n=ys(e.id),r=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;wt(t,{stream_id:n,event_type:JD,observedLastSeq:0,ts:e.started_at,payload:{invocation_id:n,kind:e.kind,origin:e.origin,launch_source:e.launch_source,from_identity:e.from_identity,target:r,root_teamfile:e.root_teamfile,scope_teamfile:e.scope_teamfile,cwd:e.cwd,command:e.command,request_payload:e.request_payload,request_message_id:e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,legacy:{table:"tracked_invocation",id:e.id}}},i=>{t.prepare(`INSERT INTO invocation_state
|
|
1755
1755
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1756
1756
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1757
1757
|
status, started_at, last_heartbeat_at, last_seq)
|
|
@@ -1759,7 +1759,7 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1759
1759
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1760
1760
|
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,n,r.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${n}`);Ym(e)&&_w(t,s,n)}),!0)}function ww(t,e,n,r){let s=ys(e.id),i=vw(t,s);return i===null?!1:(wt(t,{stream_id:s,event_type:KD,observedLastSeq:i.last_seq,ts:r,payload:{invocation_id:s,notified_by:n,notified_at:r,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(t.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(n,r,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function Ew(t,e,n){let r=ys(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(n,r),Ym(e)&&yw(t,r,n)}function Tw(t,e,n){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(n,ys(e))}function Sw(t,e,n){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(n,ys(e))}var JD,VD,KD,kw=L(()=>{"use strict";Bl();zl();JD="INVOCATION_START",VD="INVOCATION_FINISH",KD="INVOCATION_NOTIFY_CLAIM"});var zD,YD,xK,Rw,Iw,xw,Aw=L(()=>{"use strict";zD="other",YD=["not_enough_information","dont_know","other_work"],xK=new Set([zD,...YD]),Rw="@abort",Iw="invalid_decision",xw="workflow_escalation"});import{randomUUID as Cw}from"node:crypto";import{existsSync as Mw,mkdirSync as QD,renameSync as ZD,rmdirSync as e0}from"node:fs";import{hostname as Zm}from"node:os";function V(){return new Date().toISOString()}function t0(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!Mw(t))return e;let n;try{n=new Bs(t,{readonly:!0})}catch{return e}try{let r=[];try{r=n.prepare("SELECT teamfile_path, name, raw_text, raw_sha256, registered_at, last_seeded_at FROM root_team").all()}catch{}let s=[];try{s=n.prepare("SELECT key, value FROM lmctl_config").all()}catch{}return{rootTeams:r,config:s}}finally{n.close()}}function n0(t){if(t===":memory:"||!Mw(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let n of["","-wal","-shm"]){let r=`${t}${n}`;try{ZD(r,`${e}${n}`)}catch{}}return e}function Nw(t,e){let n=e instanceof Error?e.message:String(e);try{let r=t0(t),s=n0(t),i=new Ql(Xl({dbPath:t}));for(let o of r.rootTeams)i.upsertRootTeam(o);for(let{key:o,value:a}of r.config)i.setConfig(o,a);return process.stderr.write(`lmctl: couldn't migrate ${t} to schema v${Er} (${n}); started a fresh database instead. Preserved ${r.rootTeams.length} team registration(s) and ${r.config.length} config value(s).`+(s!==null?` Old database backed up at ${s}.
|
|
1761
1761
|
`:`
|
|
1762
|
-
`)),i}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`${t}: unusable (${n}), and recovery into a fresh database also failed (${s}). Check that the containing directory is writable, or move the file aside manually and retry.`)}}function Qm(t,e){let n;try{return n=Xl({dbPath:t,allowSchemaSkew:e}),{dal:new Ql(n)}}catch(r){if(r instanceof hs)throw r;let s;if(n!==void 0)try{s=n.pragma("user_version",{simple:!0})}catch{}try{n?.close()}catch{}return{cause:r,dbVersion:s}}}function o0(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function a0(t){if(t===":memory:")return!0;try{return QD(`${t}${Pw}`),!0}catch{return!1}}function l0(t){if(t!==":memory:")try{e0(`${t}${Pw}`)}catch{}}function
|
|
1762
|
+
`)),i}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`${t}: unusable (${n}), and recovery into a fresh database also failed (${s}). Check that the containing directory is writable, or move the file aside manually and retry.`)}}function Qm(t,e){let n;try{return n=Xl({dbPath:t,allowSchemaSkew:e}),{dal:new Ql(n)}}catch(r){if(r instanceof hs)throw r;let s;if(n!==void 0)try{s=n.pragma("user_version",{simple:!0})}catch{}try{n?.close()}catch{}return{cause:r,dbVersion:s}}}function o0(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function a0(t){if(t===":memory:")return!0;try{return QD(`${t}${Pw}`),!0}catch{return!1}}function l0(t){if(t!==":memory:")try{e0(`${t}${Pw}`)}catch{}}function nt(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1";if(t.recover===!1){let s=Qm(t.path,e);if(s.dal)return s.dal;throw s.cause}let n={};for(let s=0;s<r0;s+=1)if(n=Qm(t.path,e),n.dal!==void 0)return n.dal;let r=n.cause?.code;if(typeof r=="string"&&/^SQLITE_(BUSY|LOCKED)/.test(r))throw new Error(t.path+": database is busy; retry this command after the other writer finishes.",{cause:n.cause});if(n.dbVersion!==void 0&&n.dbVersion>Er){let s=n.cause instanceof Error?n.cause.message:String(n.cause);throw new hs(t.path,n.dbVersion,Er,s)}for(let s=0;s<s0;s+=1){if(a0(t.path))try{return Nw(t.path,n.cause)}finally{l0(t.path)}o0(i0);let i=Qm(t.path,e);if(i.dal!==void 0)return i.dal}return Nw(t.path,n.cause)}function Ow(t,e,n){let r=Lw(e);if(r.length===0)return;let s=new Set,i=[],o=l=>{if(l===t)return r;let c=n(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return Lw(c.definition)},a=l=>{let c=i.indexOf(l);if(c>=0)throw new Error(`cycle detected: ${[...i.slice(c),l].join(" -> ")}`);if(!s.has(l)){i.push(l);try{for(let u of o(l))a(u)}finally{i.pop()}s.add(l)}};a(t)}function Lw(t){let e=c0(t),n=e===null?null:u0(e,"states");if(n===null)return[];let r=[];for(let s of Object.values(n))Zl(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&r.push(s.workflow_name);return r}function c0(t){try{let e=JSON.parse(t);return Zl(e)?e:null}catch{return null}}function u0(t,e){let n=t[e];return Zl(n)?n:null}function Zl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function d0(t){try{let e=JSON.parse(t);return!Zl(e)||typeof e.lock_id!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}function m0(t,e){return t===null?!0:t.holder_host===Zm()?!ct(t.holder_pid):t.last_heartbeat<e}function p0(t){return{getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
1763
1763
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
1764
1764
|
VALUES (?, ?, ?, ?, ?)
|
|
1765
1765
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -2173,22 +2173,22 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
2173
2173
|
AND ended_at >= ?
|
|
2174
2174
|
ORDER BY started_at ASC, id ASC
|
|
2175
2175
|
`).all(...e,n)}finishTrackedInvocation(e,n){return this.db.transaction(()=>{let r=n.ended_at??V();if(this.stmts.finishTrackedInvocation.run(n.status,r,n.exit_code??null,n.signal??null,Kt(n.result_summary),Kt(n.error),n.team_chat_log_id??null,Kt(n.meta),Kt(n.config_warnings),r,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Yl(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??V();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(r.status,s,r.exit_code??null,r.signal??null,Kt(r.result_summary),Kt(r.error),r.team_chat_log_id??null,Kt(r.meta),Kt(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 Yl(this.db,o),o})()}heartbeatTrackedInvocation(e,n=V()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(n,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return Ew(this.db,s,n),s})()}updateTrackedInvocationRequestPayload(e,n){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(n,e).changes!==1?null:(Tw(this.db,e,n),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,n){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(n,e).changes!==1?null:(Sw(this.db,e,Bn(n)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,n,r){return this.db.transaction(()=>{let s=V();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Kt(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 Yl(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||Kl(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:V()})}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=V()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(n,r,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return ww(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=V()){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:fw(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&&Ao(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&&Ao(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
|
|
2176
|
-
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&&Ao(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&&(Ao(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,n){let r=this.stmts.getRuntimeState.get(Ro,xo(e,n),Io);return r===void 0?null:iw(r.data)}setTerminalLock(e){this.db.transaction(()=>{let r=this.getTerminalLock(e.teamfile,e.alias);r!==null&&r.lock_id!==e.lock_id&&zm(this.db,r,!0),this.stmts.upsertRuntimeState.run(Ro,xo(e.teamfile,e.alias),Io,JSON.stringify(e),e.last_heartbeat),r?.lock_id!==e.lock_id&&gw(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(Ro,xo(e,n),Io,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(Ro,xo(e,n),Io);return i.changes===1&&zm(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:d0(s.data)}tryAcquireRuntimeProcessLock(e,n,r,s,i=V()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,n,r);if(o!==null&&!m0(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Cw(),holder_pid:process.pid,holder_host:Zm(),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,V(),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,V())}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,V());return this.stmts.getStep.get(n.lastInsertRowid)}finishStep(e,n,r){return this.stmts.finishStep.run(n??null,r??null,V(),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??V(),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,V());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,V()).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,V()),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,V());return this.stmts.getAttention.get(n.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(V(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let n=V();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??V());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,V())}resumeEscalation(e,n){return this.resumeEscalationTxn(e,n,V())}}});import{homedir as g0}from"node:os";import{join as Dw}from"node:path";function _0(t=process.env){let e=t.LMCTL_HOME;return e!==void 0&&e.length>0?e:Dw(t.HOME||g0(),h0)}function Fw(t=process.env){return Dw(_0(t),y0)}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:Fw(e)}function $w(t,e=process.env){return e.LMCTL_DB!==void 0&&e.LMCTL_DB.length>0&&e.LMCTL_DB!==Fw(e)?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}var h0,y0,ec=L(()=>{"use strict";h0=".lmctl",y0="state.db"});import{isAbsolute as v0,resolve as jw,join as Uw}from"node:path";function yn(t,e){let n=ep.get(t);if(!n||t.closed)throw Error("Context is closed");return n.resources.add(e),()=>n.resources.delete(e)}function Et(t){let e=ep.get(t);if(!e)throw Error("Unknown context");return e.dal()}function xr(t){let e=Hw.get(t);if(!e)throw Error("Context state is unavailable");return e}function li(t){return t!==null&&typeof t=="object"&&Bw.has(t)}function Ww(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(g=>!n.includes(g)))return H("invalid_argument","Unknown context option");if(!e.env||typeof e.env!="object"||Array.isArray(e.env)||typeof e.cwd!="string"||!v0(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(g=>g!==void 0&&typeof g!="string"))return H("invalid_argument","Environment values must be strings or undefined");for(let g of["onProgress","onWarning","clock"])if(e[g]!==void 0&&typeof e[g]!="function")return H("invalid_argument",g+" 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=jw(e.cwd),i=r.LMCTL_HOME||(r.HOME?Uw(r.HOME,".lmctl"):void 0);if(!(e.dbPath||r.LMCTL_DB||(i?Uw(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=g=>{if(l){try{l.close()}catch(h){g.push(G(h))}l=void 0}},f=Object.freeze({status:"ok",error:null,pid:e.pid,signal:d.signal,env:r,cwd:s,dbPath:jw(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 g;return c=new Promise(h=>{g=h}),a=!0,d.abort(),(async()=>{let h=[],y=0;for(let b of[...m])try{await b.close(),y++,m.delete(b)}catch(_){h.push(G(_))}h.length||p(h),g({released:y,errors:h})})(),c},finalizeSync(g){if(u)return u;a=!0;let h=[],y={released:0,errors:h};u=y,c??=Promise.resolve(y);for(let b of[...m])try{b.finalizeSync(g),y.released++,m.delete(b)}catch(_){h.push(G(_))}return d.abort(g),h.length||p(h),y}});return ep.set(f,{resources:m,dal(){if(e.dal)return e.dal;if(l)return l;if(a)throw Error("Context is closed");return l??=tt({path:f.dbPath})}}),Bw.add(f),Hw.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 ep,Hw,Bw,zt=L(()=>{"use strict";nn();ec();et();ep=new WeakMap;Hw=new WeakMap;Bw=new WeakSet});function qw(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","model2","model3"].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 Xw=L(()=>{"use strict"});function tc(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 tp=L(()=>{"use strict"});import{readFileSync as b0}from"node:fs";import{homedir as w0}from"node:os";import{join as Gw,resolve as E0}from"node:path";function ci(t=process.env,e){let n=t.LMCTL_HOME||(t.HOME===void 0?process.env.LMCTL_HOME:void 0);return e!==void 0?E0(e):Gw(n||Gw(t.HOME||w0(),".lmctl"),"init.toml")}function T0(t,e,n,r,s){return e==="missing"?"Missing "+t:e==="read"?"Cannot read "+t+": "+n:"Invalid "+t+":"+r+":"+s+": "+n}function rc(t,e="<init.toml>"){let{document:n}=np(t,e),r={};for(let i of nc){let o=n[i];if(o===void 0)continue;if(!o||typeof o!="object"||Array.isArray(o)||o instanceof Date)throw new Pt(e,"schema","["+i+"] must be a table with provider, model1, model2 and model3");let a={};for(let l of Jw){let c=o[l];if(typeof c!="string"||!c.trim())throw new Pt(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=nc.find(o=>!r[o]);if(i)throw new Pt(e,"schema","["+i+"] is not in "+e+"; this needs the example slots ["+nc.join("], [")+"] -- add ["+i+"] with provider, model1, model2 and model3");return{provider1:r.Provider1,provider2:r.Provider2,provider3:r.Provider3}}}),s}function np(t,e="<init.toml>"){let n;try{n=js(t.startsWith("\uFEFF")?t.slice(1):t,{integersAsBigInt:"asNeeded",useLegacyDate:!0})}catch(r){let s=r;throw new Pt(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 Vw(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(b0(t))}catch(n){let r=n;throw new Pt(t,r.code==="ENOENT"?"missing":"read",r.message)}return e}function rp(t=ci()){return np(Vw(t),t)}function sc(t=ci()){return rc(Vw(t),t)}var nc,Jw,Pt,ic=L(()=>{"use strict";rl();nc=["Provider1","Provider2","Provider3"],Jw=["provider","model1","model2","model3"];Pt=class extends Error{constructor(n,r,s,i=1,o=1){let a=T0(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 Kw=L(()=>{"use strict";rl();ic()});var zw=L(()=>{"use strict"});var Yw=L(()=>{"use strict"});var Qw=L(()=>{"use strict";ud();tp();ic();ic();Kw();zw();Yw()});import{resolve as S0,join as Zw}from"node:path";function sp(t,e={}){try{if(!li(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=>!(at.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?Zw(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=S0(t.cwd,n??Zw(r,"init.toml"));return de({path:ci({...t.env,HOME:t.env.HOME??t.cwd},s)})}catch(n){return H("invalid_argument","Invalid profile arguments: "+G(n))}}function k0(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","model2","model3"]){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 de(tc(e))}catch(e){return H("invalid_argument","Invalid profile: "+G(e))}}function R0(t,e={}){let n=sp(t,e);if(n.status==="error")return n;try{let r=sc(n.path);return de({profile:{path:r.path,raw:r.raw,config:r.config},values:{...tc(r.config),Directory:t.cwd,NonInteractive:!t.interactive}})}catch(r){return r instanceof Pt?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 I0(t,e={}){let n=sp(t,e);if(n.status==="error")return n;try{let r=rp(n.path),{properties:s,flat:i}=qw(r.document);return de({path:r.path,properties:s,flat:i})}catch(r){return r instanceof Pt?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 eE=L(()=>{"use strict";Xw();mn();Qw();tp();zt();et()});function Wn(t){return t!=="gemini"}function oc(t){if(!Wn(t))throw new Error(Ar)}var Ar,ui=L(()=>{"use strict";Ar="Standalone Gemini CLI support is disabled; use provider=agy with an Agy-supported Gemini model."});function tE(t){if(t.length===0||!t.startsWith("---"))throw new _n("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
2177
|
-
`);if(e[0]!=="---")throw new
|
|
2178
|
-
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=tE(i)}catch(l){if(l instanceof
|
|
2176
|
+
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&&Ao(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&&(Ao(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,n){let r=this.stmts.getRuntimeState.get(Ro,xo(e,n),Io);return r===void 0?null:iw(r.data)}setTerminalLock(e){this.db.transaction(()=>{let r=this.getTerminalLock(e.teamfile,e.alias);r!==null&&r.lock_id!==e.lock_id&&zm(this.db,r,!0),this.stmts.upsertRuntimeState.run(Ro,xo(e.teamfile,e.alias),Io,JSON.stringify(e),e.last_heartbeat),r?.lock_id!==e.lock_id&&gw(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(Ro,xo(e,n),Io,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(Ro,xo(e,n),Io);return i.changes===1&&zm(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:d0(s.data)}tryAcquireRuntimeProcessLock(e,n,r,s,i=V()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,n,r);if(o!==null&&!m0(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Cw(),holder_pid:process.pid,holder_host:Zm(),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,V(),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,V())}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,V());return this.stmts.getStep.get(n.lastInsertRowid)}finishStep(e,n,r){return this.stmts.finishStep.run(n??null,r??null,V(),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??V(),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,V());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,V()).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,V()),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,V());return this.stmts.getAttention.get(n.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(V(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let n=V();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??V());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,V())}resumeEscalation(e,n){return this.resumeEscalationTxn(e,n,V())}}});import{homedir as g0}from"node:os";import{join as Dw}from"node:path";function _0(t=process.env){let e=t.LMCTL_HOME;return e!==void 0&&e.length>0?e:Dw(t.HOME||g0(),h0)}function Fw(t=process.env){return Dw(_0(t),y0)}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:Fw(e)}function $w(t,e=process.env){return e.LMCTL_DB!==void 0&&e.LMCTL_DB.length>0&&e.LMCTL_DB!==Fw(e)?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}var h0,y0,ec=L(()=>{"use strict";h0=".lmctl",y0="state.db"});import{isAbsolute as v0,resolve as jw,join as Uw}from"node:path";function _n(t,e){let n=ep.get(t);if(!n||t.closed)throw Error("Context is closed");return n.resources.add(e),()=>n.resources.delete(e)}function Et(t){let e=ep.get(t);if(!e)throw Error("Unknown context");return e.dal()}function xr(t){let e=Hw.get(t);if(!e)throw Error("Context state is unavailable");return e}function li(t){return t!==null&&typeof t=="object"&&Bw.has(t)}function Ww(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(g=>!n.includes(g)))return H("invalid_argument","Unknown context option");if(!e.env||typeof e.env!="object"||Array.isArray(e.env)||typeof e.cwd!="string"||!v0(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(g=>g!==void 0&&typeof g!="string"))return H("invalid_argument","Environment values must be strings or undefined");for(let g of["onProgress","onWarning","clock"])if(e[g]!==void 0&&typeof e[g]!="function")return H("invalid_argument",g+" 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=jw(e.cwd),i=r.LMCTL_HOME||(r.HOME?Uw(r.HOME,".lmctl"):void 0);if(!(e.dbPath||r.LMCTL_DB||(i?Uw(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=g=>{if(l){try{l.close()}catch(h){g.push(G(h))}l=void 0}},f=Object.freeze({status:"ok",error:null,pid:e.pid,signal:d.signal,env:r,cwd:s,dbPath:jw(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 g;return c=new Promise(h=>{g=h}),a=!0,d.abort(),(async()=>{let h=[],y=0;for(let b of[...m])try{await b.close(),y++,m.delete(b)}catch(_){h.push(G(_))}h.length||p(h),g({released:y,errors:h})})(),c},finalizeSync(g){if(u)return u;a=!0;let h=[],y={released:0,errors:h};u=y,c??=Promise.resolve(y);for(let b of[...m])try{b.finalizeSync(g),y.released++,m.delete(b)}catch(_){h.push(G(_))}return d.abort(g),h.length||p(h),y}});return ep.set(f,{resources:m,dal(){if(e.dal)return e.dal;if(l)return l;if(a)throw Error("Context is closed");return l??=nt({path:f.dbPath})}}),Bw.add(f),Hw.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 ep,Hw,Bw,zt=L(()=>{"use strict";nn();ec();tt();ep=new WeakMap;Hw=new WeakMap;Bw=new WeakSet});function qw(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","model2","model3"].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 Xw=L(()=>{"use strict"});function tc(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 tp=L(()=>{"use strict"});import{readFileSync as b0}from"node:fs";import{homedir as w0}from"node:os";import{join as Gw,resolve as E0}from"node:path";function ci(t=process.env,e){let n=t.LMCTL_HOME||(t.HOME===void 0?process.env.LMCTL_HOME:void 0);return e!==void 0?E0(e):Gw(n||Gw(t.HOME||w0(),".lmctl"),"init.toml")}function T0(t,e,n,r,s){return e==="missing"?"Missing "+t:e==="read"?"Cannot read "+t+": "+n:"Invalid "+t+":"+r+":"+s+": "+n}function rc(t,e="<init.toml>"){let{document:n}=np(t,e),r={};for(let i of nc){let o=n[i];if(o===void 0)continue;if(!o||typeof o!="object"||Array.isArray(o)||o instanceof Date)throw new Pt(e,"schema","["+i+"] must be a table with provider, model1, model2 and model3");let a={};for(let l of Jw){let c=o[l];if(typeof c!="string"||!c.trim())throw new Pt(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=nc.find(o=>!r[o]);if(i)throw new Pt(e,"schema","["+i+"] is not in "+e+"; this needs the example slots ["+nc.join("], [")+"] -- add ["+i+"] with provider, model1, model2 and model3");return{provider1:r.Provider1,provider2:r.Provider2,provider3:r.Provider3}}}),s}function np(t,e="<init.toml>"){let n;try{n=js(t.startsWith("\uFEFF")?t.slice(1):t,{integersAsBigInt:"asNeeded",useLegacyDate:!0})}catch(r){let s=r;throw new Pt(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 Vw(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(b0(t))}catch(n){let r=n;throw new Pt(t,r.code==="ENOENT"?"missing":"read",r.message)}return e}function rp(t=ci()){return np(Vw(t),t)}function sc(t=ci()){return rc(Vw(t),t)}var nc,Jw,Pt,ic=L(()=>{"use strict";rl();nc=["Provider1","Provider2","Provider3"],Jw=["provider","model1","model2","model3"];Pt=class extends Error{constructor(n,r,s,i=1,o=1){let a=T0(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 Kw=L(()=>{"use strict";rl();ic()});var zw=L(()=>{"use strict"});var Yw=L(()=>{"use strict"});var Qw=L(()=>{"use strict";ud();tp();ic();ic();Kw();zw();Yw()});import{resolve as S0,join as Zw}from"node:path";function sp(t,e={}){try{if(!li(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=>!(at.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?Zw(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=S0(t.cwd,n??Zw(r,"init.toml"));return de({path:ci({...t.env,HOME:t.env.HOME??t.cwd},s)})}catch(n){return H("invalid_argument","Invalid profile arguments: "+G(n))}}function k0(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","model2","model3"]){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 de(tc(e))}catch(e){return H("invalid_argument","Invalid profile: "+G(e))}}function R0(t,e={}){let n=sp(t,e);if(n.status==="error")return n;try{let r=sc(n.path);return de({profile:{path:r.path,raw:r.raw,config:r.config},values:{...tc(r.config),Directory:t.cwd,NonInteractive:!t.interactive}})}catch(r){return r instanceof Pt?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 I0(t,e={}){let n=sp(t,e);if(n.status==="error")return n;try{let r=rp(n.path),{properties:s,flat:i}=qw(r.document);return de({path:r.path,properties:s,flat:i})}catch(r){return r instanceof Pt?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 eE=L(()=>{"use strict";Xw();pn();Qw();tp();zt();tt()});function Wn(t){return t!=="gemini"}function oc(t){if(!Wn(t))throw new Error(Ar)}var Ar,ui=L(()=>{"use strict";Ar="Standalone Gemini CLI support is disabled; use provider=agy with an Agy-supported Gemini model."});function tE(t){if(t.length===0||!t.startsWith("---"))throw new vn("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
2177
|
+
`);if(e[0]!=="---")throw new vn("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 vn(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!x0.has(c))throw new vn(`unknown frontmatter key "${c}" \u2014 allowed keys: ${ac.join(", ")}`);n[c]=u}if(r===-1)throw new vn("frontmatter not closed (missing trailing `---` on its own line)");for(let o of ac)if(n[o]===void 0)throw new vn(`missing required frontmatter key "${o}" \u2014 required: ${ac.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 ac,x0,vn,nE=L(()=>{"use strict";ac=["title","description","members"],x0=new Set(ac),vn=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});function rE(t){return ip.has(t)}var ip,op=L(()=>{"use strict";ip=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","miniplayer","muse","ClaudeMock"])});import{readFileSync as A0,writeFileSync as Fz,renameSync as $z,existsSync as iE}from"node:fs";import{basename as C0,resolve as di,dirname as ap}from"node:path";function N0(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 O0(t){return/^\s*_MEMBER_\s+\S/.test(t)}function L0(t){return/^\s*_SESSION_\s+\S/.test(t)}function M0(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function Co(t){return/\.(?:lmctl|lmc)$/i.test(t)}function No(t){return C0(t).replace(/\.(?:lmctl|lmc)$/i,"")}function Dt(t){let e=A0(t,"utf-8"),n=ap(di(t)),r=cp(e,No(t),{baseDir:n,sourcePath:di(t)});for(let s of r.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=di(n,s.sessiondir));return r}function cp(t,e,n={}){let r=[],s=[];n.sourcePath,n.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
2178
|
+
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=tE(i)}catch(l){if(l instanceof vn)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
2179
2179
|
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(L0(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(M0(c)||!O0(c))continue;let d=N0(c);for(let p of Object.keys(d))if(!sE.includes(p))throw new Error(`line ${u}: unknown key "${p}" on _MEMBER_ line: ${c.trim()}
|
|
2180
|
-
allowed keys: ${sE.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!d.alias){s.push(`line ${u}: member line missing required alias: ${c.trim()}`);continue}let m={alias:d.alias,provider:d.provider||"",extra:{}};d.sessionid&&(m.session=d.sessionid),Object.prototype.hasOwnProperty.call(d,"sessiondir")&&(m.sessiondir=d.sessiondir),d.teamfile&&(m.teamfile=d.teamfile),d.model&&(m.model=d.model),d.effort&&(m.effort=d.effort),r.push(m)}return{name:e,members:r,rawText:t,parseErrors:s,frontmatter:o}}function up(t,e){let n=[];for(let i of t.parseErrors)n.push({field:"session",message:i});let r=t.members.filter(i=>i.alias.toLowerCase()===lp.toLowerCase());r.length>1&&n.push({field:lp,message:`${r.length} alias=Lead found (max 1)`});let s=new Set;for(let i of t.members){let o=i.alias.toLowerCase();if(s.has(o)&&n.push({field:i.alias,message:`Duplicate alias "${i.alias}" (case-insensitive)`}),s.add(o),i.teamfile){let a=e?di(e,i.teamfile):di(i.teamfile);if(!iE(a))n.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Dt(a),c=lc(l);c?c.session||n.push({field:i.alias,message:`Team at ${i.teamfile} lead has no session ID. Run: lmctl seed`}):n.push({field:i.alias,message:`Team at ${i.teamfile} has no lead session`})}}else ip.has(i.provider)?Wn(i.provider)||n.push({field:i.alias,message:Ar}):n.push({field:i.alias,message:`Invalid provider "${i.provider}"`});i.sessiondir!==void 0&&i.sessiondir===""&&n.push({field:i.alias,message:"sessiondir is empty"})}return n}function lc(t){return t.members.find(e=>e.alias.toLowerCase()===lp.toLowerCase())}function dp(t,e,n,r={}){let s=r.requireSession??!0;if(!t.teamfile)throw new Error(`Member "${t.alias}" is not a team reference`);let i=di(e,t.teamfile),o=n??new Set;if(o.has(i))throw new Error(`Circular team reference: ${t.alias} \u2192 ${i} (already visited: ${[...o].join(" \u2192 ")})`);if(o.add(i),!iE(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Dt(i),l=lc(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return dp(l,ap(i),o,r);if(s&&!l.session)throw new Error(`Team at ${i} lead has no session ID. Run: lmctl seed`);return{provider:l.provider,session:l.session??"",sessiondir:l.sessiondir||ap(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function cc(t,e){return t.members.find(n=>n.alias===e)??t.members.find(n=>n.alias.toLowerCase()===e.toLowerCase())}var lp,sE,
|
|
2181
|
-
`)}){let r=Tt(t,$0(e)?e:void 0);if(oE(r)){let i=aE(r,"utf8"),o=dc(i,r);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(r)===null&&U0(o)&&B0(e,r,o,i,n),o}let s=e?.getRootTeam(r)??null;throw s!==null?new Error(`teamfile missing on disk: ${r} (registered ${s.registered_at}; the file was renamed or deleted \u2014 seed the team at its new path)`):new Error(`teamfile not found: ${t}`)}function $0(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function j0(t,e,n){let r=n.getRootTeam(t)??n.getRootTeam(e);return r===null?null:r.teamfile_path}function U0(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=mp)}function pp(t,e,n){let r=Tt(e),s=n.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=mp);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=Tt(i.teamfile_path),o===r)continue;a=aE(o,"utf8")}catch(c){if(H0(c))continue;throw c}let l=dc(a,o);for(let c of s){let u=l.members.find(d=>d.teamfile===void 0&&d.session===c.session&&(d.session?.length??0)>=mp);if(u!==void 0)throw new uc(`sessionid ownership conflict: ${r}:${c.alias} and ${o}:${u.alias} both use sessionid "${c.session}"`)}}}function H0(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function B0(t,e,n,r,s){try{pp(t,e,n)}catch(o){if(!(o instanceof uc))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:n.name,raw_text:r,raw_sha256:P0("sha256").update(r).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var mp,uc,_s=L(()=>{"use strict";
|
|
2180
|
+
allowed keys: ${sE.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!d.alias){s.push(`line ${u}: member line missing required alias: ${c.trim()}`);continue}let m={alias:d.alias,provider:d.provider||"",extra:{}};d.sessionid&&(m.session=d.sessionid),Object.prototype.hasOwnProperty.call(d,"sessiondir")&&(m.sessiondir=d.sessiondir),d.teamfile&&(m.teamfile=d.teamfile),d.model&&(m.model=d.model),d.effort&&(m.effort=d.effort),r.push(m)}return{name:e,members:r,rawText:t,parseErrors:s,frontmatter:o}}function up(t,e){let n=[];for(let i of t.parseErrors)n.push({field:"session",message:i});let r=t.members.filter(i=>i.alias.toLowerCase()===lp.toLowerCase());r.length>1&&n.push({field:lp,message:`${r.length} alias=Lead found (max 1)`});let s=new Set;for(let i of t.members){let o=i.alias.toLowerCase();if(s.has(o)&&n.push({field:i.alias,message:`Duplicate alias "${i.alias}" (case-insensitive)`}),s.add(o),i.teamfile){let a=e?di(e,i.teamfile):di(i.teamfile);if(!iE(a))n.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Dt(a),c=lc(l);c?c.session||n.push({field:i.alias,message:`Team at ${i.teamfile} lead has no session ID. Run: lmctl seed`}):n.push({field:i.alias,message:`Team at ${i.teamfile} has no lead session`})}}else ip.has(i.provider)?Wn(i.provider)||n.push({field:i.alias,message:Ar}):n.push({field:i.alias,message:`Invalid provider "${i.provider}"`});i.sessiondir!==void 0&&i.sessiondir===""&&n.push({field:i.alias,message:"sessiondir is empty"})}return n}function lc(t){return t.members.find(e=>e.alias.toLowerCase()===lp.toLowerCase())}function dp(t,e,n,r={}){let s=r.requireSession??!0;if(!t.teamfile)throw new Error(`Member "${t.alias}" is not a team reference`);let i=di(e,t.teamfile),o=n??new Set;if(o.has(i))throw new Error(`Circular team reference: ${t.alias} \u2192 ${i} (already visited: ${[...o].join(" \u2192 ")})`);if(o.add(i),!iE(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Dt(i),l=lc(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return dp(l,ap(i),o,r);if(s&&!l.session)throw new Error(`Team at ${i} lead has no session ID. Run: lmctl seed`);return{provider:l.provider,session:l.session??"",sessiondir:l.sessiondir||ap(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function cc(t,e){return t.members.find(n=>n.alias===e)??t.members.find(n=>n.alias.toLowerCase()===e.toLowerCase())}var lp,sE,bn=L(()=>{"use strict";ui();nE();op();lp="Lead";sE=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as P0}from"node:crypto";import{existsSync as oE,readFileSync as aE,realpathSync as D0}from"node:fs";import{dirname as F0,resolve as lE}from"node:path";function Tt(t,e){let n=lE(t);if(oE(n))return D0(n);if(e!==void 0){let r=j0(t,n,e);if(r!==null)return r}return n}function dc(t,e){let n=F0(e),r=cp(t,No(e),{baseDir:n});for(let s of r.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=lE(n,s.sessiondir));return r}function mi(t,e,n=r=>{process.stderr.write(`warning: ${r}
|
|
2181
|
+
`)}){let r=Tt(t,$0(e)?e:void 0);if(oE(r)){let i=aE(r,"utf8"),o=dc(i,r);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(r)===null&&U0(o)&&B0(e,r,o,i,n),o}let s=e?.getRootTeam(r)??null;throw s!==null?new Error(`teamfile missing on disk: ${r} (registered ${s.registered_at}; the file was renamed or deleted \u2014 seed the team at its new path)`):new Error(`teamfile not found: ${t}`)}function $0(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function j0(t,e,n){let r=n.getRootTeam(t)??n.getRootTeam(e);return r===null?null:r.teamfile_path}function U0(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=mp)}function pp(t,e,n){let r=Tt(e),s=n.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=mp);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=Tt(i.teamfile_path),o===r)continue;a=aE(o,"utf8")}catch(c){if(H0(c))continue;throw c}let l=dc(a,o);for(let c of s){let u=l.members.find(d=>d.teamfile===void 0&&d.session===c.session&&(d.session?.length??0)>=mp);if(u!==void 0)throw new uc(`sessionid ownership conflict: ${r}:${c.alias} and ${o}:${u.alias} both use sessionid "${c.session}"`)}}}function H0(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function B0(t,e,n,r,s){try{pp(t,e,n)}catch(o){if(!(o instanceof uc))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:n.name,raw_text:r,raw_sha256:P0("sha256").update(r).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var mp,uc,_s=L(()=>{"use strict";bn();mp=5,uc=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{randomUUID as W0}from"node:crypto";import{closeSync as q0,openSync as X0,readFileSync as uE,statSync as G0,unlinkSync as fp,writeFileSync as J0}from"node:fs";function dE(t,e){return`${t}.seed-${e.toLowerCase()}.lock`}function mE(t){let e;try{e=JSON.parse(uE(t,"utf8"))}catch(r){return r.code==="ENOENT"?!1:cE(t)}let n=typeof e=="object"&&e!==null&&"pid"in e?e.pid:void 0;if(typeof n!="number"||!Number.isInteger(n)||n<=0)return cE(t);try{return process.kill(n,0),!0}catch(r){return r.code!=="ESRCH"}}function cE(t){try{return Date.now()-G0(t).mtimeMs<3e5}catch{return!1}}function gp(t,e){return mE(dE(t,e))}function pE(t,e){let n=dE(t,e),r=JSON.stringify({pid:process.pid,token:W0()});for(let s=0;s<2;s+=1)try{let i=X0(n,"wx");try{J0(i,r)}catch(o){throw fp(n),o}finally{q0(i)}return()=>{try{uE(n,"utf8")===r&&fp(n)}catch(o){if(o.code!=="ENOENT")throw o}}}catch(i){if(i.code!=="EEXIST")throw i;if(mE(n))throw new Error(`${e}: seed already in progress; wait for it to finish`);try{fp(n)}catch(o){if(o.code!=="ENOENT")throw o}}throw new Error(`${e}: could not acquire seed marker`)}var hp=L(()=>{"use strict"});import{existsSync as V0}from"node:fs";import{dirname as fE}from"node:path";function _p(t){return yp.test(t)}function vp(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),n=t.slice(0,e),r=t.slice(e+1);return!Co(n)||!yp.test(r)?null:{teamfile:n,alias:r}}function Ft(t,e,n){if(!Co(t))throw new Me(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl or .lmc extension).`);if(!_p(e))throw new Me(`lmctl: "${e}" is not a valid alias (must match ${yp.source}).`);let r=Tt(t,n);if(n===void 0&&!V0(r))throw new Me(`lmctl: teamfile not found: ${t}`,"not_found");let s;try{s=mi(r,n)}catch(o){throw new Me(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new Me(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=cc(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new Me(`lmctl: alias "${e}" not found in ${t}.
|
|
2182
2182
|
Known aliases: ${o}`,"not_found")}if(i.teamfile!==void 0){let o=dp(i,fE(r));return{teamfile:r,alias:i.alias,provider:o.provider,sessionid:o.session,sessiondir:o.sessiondir,isLead:!0,...o.model??i.model?{model:o.model??i.model}:{},...o.effort??i.effort?{effort:o.effort??i.effort}:{}}}if(gp(r,i.alias))throw new Me(`lmctl: alias "${i.alias}" is being seeded. Wait for the seed to finish, then retry this prompt.`);if(i.session===void 0)throw s.members.some(o=>gp(r,o.alias))?new Me(`lmctl: alias "${i.alias}" has no session ID yet, and a seed is currently in progress for this team. Wait for the seed to finish, then retry this prompt.`):new Me(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
2183
|
-
Run: lmctl seed ${t}`);return{teamfile:r,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??fE(r),isLead:lc(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}var Me,yp,qn=L(()=>{"use strict";
|
|
2183
|
+
Run: lmctl seed ${t}`);return{teamfile:r,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??fE(r),isLead:lc(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}var Me,yp,qn=L(()=>{"use strict";bn();bn();_s();hp();Me=class extends Error{constructor(e,n){super(e),this.name="ChatTargetError",n&&Object.defineProperty(this,"kind",{value:n})}},yp=/^[A-Za-z][A-Za-z0-9_-]*$/});var Ep=DC(ut=>{"use strict";function pi(t){if(!Array.isArray(t))throw new TypeError("Each row and headers must be an array of cells");return Array.from(t,e=>{let n=e==null?"":String(e);if(/[\x00-\x1f\x7f-\x9f]/u.test(n))throw new TypeError("Cells must be single-line text without terminal control characters");return n})}function hE(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left", "right", or "decimal" per column');return t.map(e=>{if(e!=="left"&&e!=="right"&&e!=="decimal")throw new TypeError('align entries must be "left", "right", or "decimal"');return e})}function Xn(t){let e=0;for(let n of t){let r=n.codePointAt(0);if(!(r>=768&&r<=879||r>=6832&&r<=6911||r>=7616&&r<=7679||r>=8400&&r<=8447||r>=65024&&r<=65039||r>=65056&&r<=65071||r===8203||r>=917760&&r<=917999)){if(r>=4352&&r<=4447||r>=11904&&r<=12350||r>=12353&&r<=13311||r>=13312&&r<=19903||r>=19968&&r<=40959||r>=40960&&r<=42191||r>=44032&&r<=55203||r>=63744&&r<=64255||r>=65072&&r<=65135||r>=65280&&r<=65376||r>=65504&&r<=65510||r>=9728&&r<=10175||r>=126976&&r<=129791||r>=131072&&r<=262141){e+=2;continue}e+=1}}return e}function bp(t,e,n){let r=" ".repeat(Math.max(0,e-Xn(t)));return n?r+t:t+r}function yE(t){if(Array.isArray(t))return{rows:t};if(t!==null&&typeof t=="object"&&Array.isArray(t.rows))return t;throw new TypeError("each grid must be a rows array or { rows, headers }")}function K0(t){if(t===void 0)return"\u2026";if(typeof t!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(t))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return t}function z0(t,e,n="\u2026"){if(Xn(t)<=e)return t;let r=Xn(n)>e?"\u2026":n,s=Xn(r);if(e<=s)return r;let i="",o=0;for(let a of t){let l=Xn(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${r}`}function Y0(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError("max must be an array of per-column width caps");return t.map(e=>{if(e!=null){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new TypeError("max entries must be positive integers, null, or undefined");return e}})}function _E(t){let e=/^(?:[+-]?\$?|\$[+-]?)(?:\d+|\d{1,3}(?:,\d{3})+|(?=\.))(?:\.(\d+))?$/.exec(t);return!e||!/\d/.test(t)?null:{places:e[1]?.length??0}}function Q0(t){if(t!==void 0){if(!Array.isArray(t)||t.some(e=>!Number.isInteger(e)||e<0))throw new TypeError("decimalPlaces must be an array of nonnegative integers");return t}}function vE(t){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let e=[];for(let n of t){let r=yE(n);r.headers!==void 0&&pi(r.headers);for(let s of r.rows.map(pi))s.forEach((i,o)=>{e[o]=Math.max(e[o]??0,_E(i)?.places??0)})}return e}ut.measureDecimalPlaces=vE;function bE(t,e,n){let r=Q0(n)??[],s=e.includes("decimal")?vE(t):[];return Array.from({length:Math.max(r.length,s.length)},(i,o)=>Math.max(r[o]??0,s[o]??0))}function wE(t,e){let n=_E(t);if(!n)return null;let r=n.places?n.places+1:0,s=e?e+1:0;return t+" ".repeat(Math.max(0,s-r))}function EE(t,{max:e,align:n,decimalPlaces:r}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let s=Y0(e),i=hE(n),o=bE(t,i,r),a=[],l=(c,u)=>{a[c]=Math.max(a[c]??0,u)};for(let c of t){let u=yE(c);u.headers!==void 0&&pi(u.headers).forEach((d,m)=>{l(m,Xn(d))});for(let d of u.rows.map(pi))d.forEach((m,p)=>{let f=i[p]==="decimal"?wE(m,o[p]??0)??m:m;l(p,Xn(f))})}return a.map((c,u)=>{let d=s[u];return d===void 0?c:Math.min(c,d)})}ut.measureColumns=EE;function Z0(t){if(t===void 0)return"";if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return" ".repeat(t);if(typeof t=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(t))return t;throw new TypeError("margin must be a number of spaces or a single-line string")}function TE(t,{widths:e,headers:n,align:r,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l,decimalPlaces:c}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let u=Z0(o),d=hE(r),m=K0(l),p=bE([t],d,c),f=e??EE([{rows:t,headers:n}],{max:a,align:d,decimalPlaces:p}),g=t.map(pi);n!==void 0&&g.unshift(pi(n));let h=g.map((y,b)=>{let _=y.length-1;for(;_>=0&&y[_]==="";)_--;return y.slice(0,_+1).map((v,E)=>{let I=f[E]||0,T=s&&I>0&&(E!==_||i)?z0(v,I,m):v;if(d[E]==="decimal"){let k=n!==void 0&&b===0?null:wE(v,p[E]??0),N=bp(k!==null&&Xn(k)<=I?k:T,I,!0);return E===_&&k!==null?N.trimEnd():N}return d[E]==="right"?bp(T,I,!0):E===_?T:bp(T,I,!1)}).join(" ")}).join(`
|
|
2184
2184
|
`);return h===""||u===""?h:`${u}${h.split(`
|
|
2185
2185
|
`).join(`
|
|
2186
2186
|
${u}`)}`}ut.renderGrid=TE;function SE(t,{headers:e,align:n,truncate:r,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l}={}){return TE(t,{headers:e,align:n,truncate:r,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l})}function eF(t,{headers:e,align:n,truncate:r,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l,stream:c=process.stdout}={}){let u=SE(t,{headers:e,align:n,truncate:r,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l});u&&c.write(`${u}
|
|
2187
|
-
`)}ut.formatTable=SE;ut.printTable=eF;function gE(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function tF(t,{now:e=Date.now()}={}){let n=gE(e);if(!Number.isFinite(n))throw new TypeError("now must be a valid timestamp");let r=gE(t);if(!Number.isFinite(r))return"unknown";let s=r-n,i=Math.floor(Math.abs(s)/1e3);if(i===0)return"now";for(let[o,a]of[["w",604800],["d",86400],["h",3600],["m",60],["s",1]])if(i>=a)return`${Math.floor(i/a)}${o}${s<0?" ago":""}`}ut.formatRelativeTime=tF;function nF(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=t<0?"-":"",n=Math.abs(t);if(n<1e3)return String(t);let r=Math.round(n/1e3);return r<1e3?`${e}${r}K`:`${e}${(n/1e6).toFixed(1)}M`}ut.formatCount=nF;var wp=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function rF(t,{maxUnit:e="w",style:n="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let r=wp.findIndex(([a])=>a===e);if(r===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(n!=="spaced"&&n!=="compact")throw new TypeError('style must be "spaced" or "compact"');let s=Math.floor(Math.max(0,t)/1e3);if(n==="compact"){let a=wp.slice(r).filter(([d])=>d!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,u=!1;for(let[d,m]of a){let p=Math.floor(c/m);if(c-=p*m,p>0&&!u){let f=d==="d"||d==="w"?`${p}${d}`:`${
|
|
2188
|
-
`?"\\n":n===" "?"\\t":n==="\r"?"\\r":`\\x${n.codePointAt(0).toString(16).padStart(2,"0")}`)}ut.escapeCell=lF});function rn(t){let e=t.env?.LMCTL_DB;return e!==void 0&&e.length>0?e:ai(void 0,{...process.env,...t.env})}async function he(t,e){if(t.dal!==void 0)return e(t.dal);let n=
|
|
2187
|
+
`)}ut.formatTable=SE;ut.printTable=eF;function gE(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function tF(t,{now:e=Date.now()}={}){let n=gE(e);if(!Number.isFinite(n))throw new TypeError("now must be a valid timestamp");let r=gE(t);if(!Number.isFinite(r))return"unknown";let s=r-n,i=Math.floor(Math.abs(s)/1e3);if(i===0)return"now";for(let[o,a]of[["w",604800],["d",86400],["h",3600],["m",60],["s",1]])if(i>=a)return`${Math.floor(i/a)}${o}${s<0?" ago":""}`}ut.formatRelativeTime=tF;function nF(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=t<0?"-":"",n=Math.abs(t);if(n<1e3)return String(t);let r=Math.round(n/1e3);return r<1e3?`${e}${r}K`:`${e}${(n/1e6).toFixed(1)}M`}ut.formatCount=nF;var wp=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function rF(t,{maxUnit:e="w",style:n="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let r=wp.findIndex(([a])=>a===e);if(r===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(n!=="spaced"&&n!=="compact")throw new TypeError('style must be "spaced" or "compact"');let s=Math.floor(Math.max(0,t)/1e3);if(n==="compact"){let a=wp.slice(r).filter(([d])=>d!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,u=!1;for(let[d,m]of a){let p=Math.floor(c/m);if(c-=p*m,p>0&&!u){let f=d==="d"||d==="w"?`${p}${d}`:`${wn(p)}${d}`;l.push({text:f,zero:!1}),u=!0}else u&&l.push({text:`${wn(p)}${d}`,zero:p===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(d=>d.text).join("")}let i=s,o=[];for(let[a,l]of wp.slice(r))if(i>=l||a==="s"&&o.length===0){let c=Math.floor(i/l);if(i-=c*l,o.push(`${c}${a}`),o.length===2)break}return o.join(" ")}ut.formatDuration=rF;function kE(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function wn(t){return String(t).padStart(2,"0")}function RE(t){let e=kE(t);return Number.isNaN(e.getTime())?"unknown":`${wn(e.getHours())}:${wn(e.getMinutes())}:${wn(e.getSeconds())}`}ut.formatClock=RE;function sF(t){let e=kE(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${wn(e.getMonth()+1)}-${wn(e.getDate())}`} ${RE(e)}`}ut.formatLocalTimestamp=sF;function iF(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}ut.formatPercent=iF;function oF(t,{width:e=10,fill:n="#",empty:r=" ",unknown:s="?"}={}){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new TypeError("width must be a positive integer");for(let[o,a]of[["fill",n],["empty",r],["unknown",s]])if(typeof a!="string"||[...a].length!==1||/[\x00-\x1f\x7f-\x9f]/u.test(a)||Xn(a)!==1)throw new TypeError(`${o} must be a single character with terminal display width 1`);if(typeof t!="number"||!Number.isFinite(t))return s.repeat(e);let i=Math.min(e,Math.max(0,Math.round(t*e)));return`${n.repeat(i)}${r.repeat(e-i)}`}ut.formatBar=oF;function aF(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=Math.floor(Math.max(0,t)/1e3),n=Math.floor(e/86400);e-=n*86400;let r=Math.floor(e/3600);e-=r*3600;let s=Math.floor(e/60);e-=s*60;let i=`${wn(r)}:${wn(s)}:${wn(e)}`;return n>0?`${n}d ${i}`:i}ut.formatTimer=aF;function lF(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,n=>n===`
|
|
2188
|
+
`?"\\n":n===" "?"\\t":n==="\r"?"\\r":`\\x${n.codePointAt(0).toString(16).padStart(2,"0")}`)}ut.escapeCell=lF});function rn(t){let e=t.env?.LMCTL_DB;return e!==void 0&&e.length>0?e:ai(void 0,{...process.env,...t.env})}async function he(t,e){if(t.dal!==void 0)return e(t.dal);let n=nt({path:rn(t)});try{return await e(n)}finally{n.close()}}function IE(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
2189
2189
|
`)}function Cr(t,e){return t.stderr.write(`error: ${e}
|
|
2190
2190
|
`),1}function xE(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 AE(t,e){let n=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${n}
|
|
2191
|
-
`),2}function mc(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var cF,Nr=L(()=>{"use strict";nn();cF=py(Ep(),1);ec()});import{openSync as uF,closeSync as dF,fstatSync as mF,readSync as pF,constants as CE}from"node:fs";import{dirname as fF,join as pc}from"node:path";import{createHash as gF}from"node:crypto";function kp(t){if(!cs(t.catalog)||!us(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=ME(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(!NE(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&&!NE(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 OE(t){let e=uF(t,CE.O_RDONLY|CE.O_NONBLOCK);try{let n=mF(e);if(!n.isFile()||n.size>hF)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=pF(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{dF(e)}}function yF(t,e=pc(fF(t),"aliases.json")){let n=OE(t),r=OE(e),s;try{s=LE(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=LE(r),o={catalog:s,aliases:i,source:"pinned",generatedAt:s?.generated_at||null,sha256:gF("sha256").update(n).update(r).digest("hex")};return kp(o),o}function Sp(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 kp(i),i})():null}finally{t.pragma("busy_timeout = "+e)}}function _F(t,e,n={}){kp(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(ME(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 vF(t,e={}){let n=e.now??Date.now(),r={...process.env,...e.env},s=Sp(t),i=Tp.get(t),o=i&&i.hash===s?.sha256?i.at:Date.parse(s?.fetchedAt??"");if(!e.force&&s&&n>=o&&n-o<Fl(r))return{status:"unchanged",snapshot:s};let a=e.load??(()=>r.LMCTL_PRICE_DATA?Promise.resolve(yF(pc(r.LMCTL_PRICE_DATA,"model_list.json"))):$l({cacheDir:r.LMCTL_HOME?pc(r.LMCTL_HOME,"cache","lmprice"):r.HOME?pc(r.HOME,".lmctl","cache","lmprice"):void 0,ttlMs:e.force?0:Fl(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(Tp.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=_F(t,c,{now:n}),d=Sp(t);return Tp.set(t,{hash:d?.sha256??null,at:n}),{status:u,snapshot:d}}async function fc(t,e){try{return(await vF(t,{env:e,budgetMs:900})).snapshot??Oo}catch(n){if(/^SQLITE_(BUSY|LOCKED)(_|$)/.test(String(n?.code)))return Oo;try{return Sp(t)??Oo}catch{return Oo}}}async function Rp(t){if(t.dal)return fc(t.dal.db,t.env);let e;try{return e=tt({path:rn(t),recover:!1}),await fc(e.db,t.env)}catch{return Oo}finally{try{e?.close()}catch{}}}var Oo,ME,NE,hF,LE,Tp,Ip=L(()=>{"use strict";wo();nn();Nr();Oo={catalog:null,aliases:null,source:"unavailable",generatedAt:null,sha256:null},ME=t=>t.record_id??t.source+":"+t.source_model_id,NE=t=>t===null||typeof t=="number"&&Number.isFinite(t)&&t>=0;hF=64*1024*1024;LE=t=>JSON.parse(t.replace(/^\uFEFF/,""));Tp=new WeakMap});function Gn(t){try{return t?.usage}catch{return}}function Lo(t,e,n,r){let s,i,o,a=!1;try{o=Hl(e),s=t.dal??tt({path:rn(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 To(o,l,()=>fc(s.db,t.env),{db:s.db,env:t.env}))}catch{}finally{if(s&&s!==t.dal)try{s.close()}catch{}}}}}}function Mo(t,e,n){let r=t,s,i;s=Gn(r)??Gn(n);try{i=r?.sessionId??n?.sessionId}catch{i=n?.sessionId}return{status:ni(G(t),e.aborted),usage:s,sessionId:i}}var xp=L(()=>{"use strict";nn();Nr();Ip();So();et()});import{spawnSync as Mp}from"node:child_process";import{existsSync as $E,readFileSync as jE}from"node:fs";import{homedir as UE}from"node:os";import{resolve as Op}from"node:path";function fi(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 EF(){let t=Mp("agy",["models"],{encoding:"utf-8",timeout:wF});return{status:t.status,stdout:t.stdout??"",error:t.error}}function TF(t){let e=[];for(let n of t.split(/\r?\n/)){let r=n.trim(),s=r.indexOf(" ");if(s<0)continue;let i=r.slice(s+1).trim();i&&e.push(i)}return e}function SF(t){if(!t&&Ap)return Ap;let e=s=>(t||(Ap=s),s),n;try{n=(t??EF)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?fi("agy models",s):`agy models could not be run: ${String(s)}`})}if(n.error)return e({available:!1,models:[],reason:fi("agy models",n.error)});if(n.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${n.status??"unknown"}`});let r=TF(n.stdout);return r.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:r})}function RF(){let t=Mp("codex",["debug","models"],{encoding:"utf-8",timeout:kF});return{status:t.status,stdout:t.stdout??"",error:t.error}}function IF(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 xF(t){if(!t&&Cp)return Cp;let e=s=>(t||(Cp=s),s),n;try{n=(t??RF)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?fi("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(n.error)return e({available:!1,models:[],reason:fi("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=IF(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 CF(t){let e=Mp("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:AF});return{status:e.status,stdout:e.stdout??"",error:e.error}}function NF(t,e){if(!e&&Np.has(t))return Np.get(t);let n=o=>(e||Np.set(t,o),o),r=t?`opencode models ${t}`:"opencode models",s;try{s=(e??CF)(t)}catch(o){return n({available:!1,models:[],reason:o instanceof Error?fi(r,o):`${r} could not be run: ${String(o)}`})}if(s.error)return n({available:!1,models:[],reason:fi(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 Pp(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=MF(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=NF(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=OF(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: ${Po(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=SF(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: ${Po(i.models)}`):n.push(`[${r.alias}] model="${r.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!r.model||DE.includes(r.model))continue;PE.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in dsh's built-in catalog. Valid pinned models: ${Po(PE)}. 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): ${Po(DE)}. 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===FE&&n.push(`[${r.alias}] model="${FE}" 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=xF(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: ${Po(i.models)}`);continue}r.model&&(HE.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 BE(t,e={}){let n=t.filter(o=>o.model!==void 0&&HE.has(o.provider.trim().toLowerCase()));if(n.length===0)return{warnings:[],errors:[]};let r=e.snapshot??await $l();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=Fb(a,l,r.catalog,r.aliases);if(c.kind==="unknown"){let u=jb(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")&&bF.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 WE(t,e={}){return(await BE(t,e)).warnings}async function qE(t,e={}){return(await BE(t,e)).errors}function OF(t){let e=process.env.KIMI_CODE_HOME||Op(UE(),".kimi-code"),n=t??Op(e,"config.toml");if(!$E(n))return{available:!1,models:[],reason:`${n} not found`};let r;try{r=jE(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=LF(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].sort()}}function LF(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 MF(t){let e=t??Op(UE(),".config","opencode","opencode.json");if(!$E(e))return{available:!0,models:[]};let n;try{n=JSON.parse(jE(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:PF(n)}}function PF(t){if(!Lp(t))return[];let e=gc(t.provider)??gc(t.providers);if(!e)return[];let n=new Set;for(let[r,s]of Object.entries(e)){if(!Lp(s))continue;let i=gc(s.models)??gc(s.model);if(i)for(let o of Object.keys(i))n.add(o.startsWith(`${r}/`)?o:`${r}/${o}`)}return[...n].sort()}function gc(t){return Lp(t)?t:null}function Lp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Po(t){return t.length>0?t.join(", "):"(none)"}var HE,bF,PE,DE,FE,wF,Ap,kF,Cp,AF,Np,XE=L(()=>{"use strict";wo();qm();HE=new Set(Object.keys(Eo).filter(t=>t!=="codex"&&t!=="kimi")),bF=/\d\.(?=\d)/,PE=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],DE=["deepseek-flash","deepseek-pro"],FE="gpt-5.3-codex-spark",wF=15e3;Ap=null;kF=5e3;Cp=null;AF=5e3;Np=new Map});function vs(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var hc=L(()=>{"use strict"});import{randomUUID as DF}from"node:crypto";import{chmodSync as GE,mkdirSync as FF,readdirSync as $F,statSync as jF,unlinkSync as UF,writeFileSync as HF}from"node:fs";import{homedir as BF,tmpdir as WF}from"node:os";import{join as Do}from"node:path";function zF(t){return vs(t.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g,"")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"\uFFFD")}function Fo(t){return zF(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(KF,"$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 YF(){let t=process.env.LMCTL_HOME||(process.env.NODE_ENV==="test"?Do(WF(),`lmctl-test-${process.pid}`,".lmctl"):Do(process.env.HOME||BF(),".lmctl"));return Do(t,"provider-errors")}function QF(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)}
|
|
2191
|
+
`),2}function mc(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var cF,Nr=L(()=>{"use strict";nn();cF=py(Ep(),1);ec()});import{openSync as uF,closeSync as dF,fstatSync as mF,readSync as pF,constants as CE}from"node:fs";import{dirname as fF,join as pc}from"node:path";import{createHash as gF}from"node:crypto";function kp(t){if(!cs(t.catalog)||!us(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=ME(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(!NE(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&&!NE(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 OE(t){let e=uF(t,CE.O_RDONLY|CE.O_NONBLOCK);try{let n=mF(e);if(!n.isFile()||n.size>hF)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=pF(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{dF(e)}}function yF(t,e=pc(fF(t),"aliases.json")){let n=OE(t),r=OE(e),s;try{s=LE(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=LE(r),o={catalog:s,aliases:i,source:"pinned",generatedAt:s?.generated_at||null,sha256:gF("sha256").update(n).update(r).digest("hex")};return kp(o),o}function Sp(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 kp(i),i})():null}finally{t.pragma("busy_timeout = "+e)}}function _F(t,e,n={}){kp(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(ME(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 vF(t,e={}){let n=e.now??Date.now(),r={...process.env,...e.env},s=Sp(t),i=Tp.get(t),o=i&&i.hash===s?.sha256?i.at:Date.parse(s?.fetchedAt??"");if(!e.force&&s&&n>=o&&n-o<Fl(r))return{status:"unchanged",snapshot:s};let a=e.load??(()=>r.LMCTL_PRICE_DATA?Promise.resolve(yF(pc(r.LMCTL_PRICE_DATA,"model_list.json"))):$l({cacheDir:r.LMCTL_HOME?pc(r.LMCTL_HOME,"cache","lmprice"):r.HOME?pc(r.HOME,".lmctl","cache","lmprice"):void 0,ttlMs:e.force?0:Fl(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(Tp.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=_F(t,c,{now:n}),d=Sp(t);return Tp.set(t,{hash:d?.sha256??null,at:n}),{status:u,snapshot:d}}async function fc(t,e){try{return(await vF(t,{env:e,budgetMs:900})).snapshot??Oo}catch(n){if(/^SQLITE_(BUSY|LOCKED)(_|$)/.test(String(n?.code)))return Oo;try{return Sp(t)??Oo}catch{return Oo}}}async function Rp(t){if(t.dal)return fc(t.dal.db,t.env);let e;try{return e=nt({path:rn(t),recover:!1}),await fc(e.db,t.env)}catch{return Oo}finally{try{e?.close()}catch{}}}var Oo,ME,NE,hF,LE,Tp,Ip=L(()=>{"use strict";wo();nn();Nr();Oo={catalog:null,aliases:null,source:"unavailable",generatedAt:null,sha256:null},ME=t=>t.record_id??t.source+":"+t.source_model_id,NE=t=>t===null||typeof t=="number"&&Number.isFinite(t)&&t>=0;hF=64*1024*1024;LE=t=>JSON.parse(t.replace(/^\uFEFF/,""));Tp=new WeakMap});function Gn(t){try{return t?.usage}catch{return}}function Lo(t,e,n,r){let s,i,o,a=!1;try{o=Hl(e),s=t.dal??nt({path:rn(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 To(o,l,()=>fc(s.db,t.env),{db:s.db,env:t.env}))}catch{}finally{if(s&&s!==t.dal)try{s.close()}catch{}}}}}}function Mo(t,e,n){let r=t,s,i;s=Gn(r)??Gn(n);try{i=r?.sessionId??n?.sessionId}catch{i=n?.sessionId}return{status:ni(G(t),e.aborted),usage:s,sessionId:i}}var xp=L(()=>{"use strict";nn();Nr();Ip();So();tt()});import{spawnSync as Mp}from"node:child_process";import{existsSync as $E,readFileSync as jE}from"node:fs";import{homedir as UE}from"node:os";import{resolve as Op}from"node:path";function fi(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 EF(){let t=Mp("agy",["models"],{encoding:"utf-8",timeout:wF});return{status:t.status,stdout:t.stdout??"",error:t.error}}function TF(t){let e=[];for(let n of t.split(/\r?\n/)){let r=n.trim(),s=r.indexOf(" ");if(s<0)continue;let i=r.slice(s+1).trim();i&&e.push(i)}return e}function SF(t){if(!t&&Ap)return Ap;let e=s=>(t||(Ap=s),s),n;try{n=(t??EF)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?fi("agy models",s):`agy models could not be run: ${String(s)}`})}if(n.error)return e({available:!1,models:[],reason:fi("agy models",n.error)});if(n.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${n.status??"unknown"}`});let r=TF(n.stdout);return r.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:r})}function RF(){let t=Mp("codex",["debug","models"],{encoding:"utf-8",timeout:kF});return{status:t.status,stdout:t.stdout??"",error:t.error}}function IF(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 xF(t){if(!t&&Cp)return Cp;let e=s=>(t||(Cp=s),s),n;try{n=(t??RF)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?fi("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(n.error)return e({available:!1,models:[],reason:fi("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=IF(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 CF(t){let e=Mp("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:AF});return{status:e.status,stdout:e.stdout??"",error:e.error}}function NF(t,e){if(!e&&Np.has(t))return Np.get(t);let n=o=>(e||Np.set(t,o),o),r=t?`opencode models ${t}`:"opencode models",s;try{s=(e??CF)(t)}catch(o){return n({available:!1,models:[],reason:o instanceof Error?fi(r,o):`${r} could not be run: ${String(o)}`})}if(s.error)return n({available:!1,models:[],reason:fi(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 Pp(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=MF(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=NF(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=OF(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: ${Po(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=SF(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: ${Po(i.models)}`):n.push(`[${r.alias}] model="${r.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!r.model||DE.includes(r.model))continue;PE.includes(r.model)||n.push(`[${r.alias}] model="${r.model}" is not in dsh's built-in catalog. Valid pinned models: ${Po(PE)}. 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): ${Po(DE)}. 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===FE&&n.push(`[${r.alias}] model="${FE}" 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=xF(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: ${Po(i.models)}`);continue}r.model&&(HE.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 BE(t,e={}){let n=t.filter(o=>o.model!==void 0&&HE.has(o.provider.trim().toLowerCase()));if(n.length===0)return{warnings:[],errors:[]};let r=e.snapshot??await $l();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=Fb(a,l,r.catalog,r.aliases);if(c.kind==="unknown"){let u=jb(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")&&bF.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 WE(t,e={}){return(await BE(t,e)).warnings}async function qE(t,e={}){return(await BE(t,e)).errors}function OF(t){let e=process.env.KIMI_CODE_HOME||Op(UE(),".kimi-code"),n=t??Op(e,"config.toml");if(!$E(n))return{available:!1,models:[],reason:`${n} not found`};let r;try{r=jE(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=LF(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].sort()}}function LF(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 MF(t){let e=t??Op(UE(),".config","opencode","opencode.json");if(!$E(e))return{available:!0,models:[]};let n;try{n=JSON.parse(jE(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:PF(n)}}function PF(t){if(!Lp(t))return[];let e=gc(t.provider)??gc(t.providers);if(!e)return[];let n=new Set;for(let[r,s]of Object.entries(e)){if(!Lp(s))continue;let i=gc(s.models)??gc(s.model);if(i)for(let o of Object.keys(i))n.add(o.startsWith(`${r}/`)?o:`${r}/${o}`)}return[...n].sort()}function gc(t){return Lp(t)?t:null}function Lp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Po(t){return t.length>0?t.join(", "):"(none)"}var HE,bF,PE,DE,FE,wF,Ap,kF,Cp,AF,Np,XE=L(()=>{"use strict";wo();qm();HE=new Set(Object.keys(Eo).filter(t=>t!=="codex"&&t!=="kimi")),bF=/\d\.(?=\d)/,PE=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],DE=["deepseek-flash","deepseek-pro"],FE="gpt-5.3-codex-spark",wF=15e3;Ap=null;kF=5e3;Cp=null;AF=5e3;Np=new Map});function vs(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var hc=L(()=>{"use strict"});import{randomUUID as DF}from"node:crypto";import{chmodSync as GE,mkdirSync as FF,readdirSync as $F,statSync as jF,unlinkSync as UF,writeFileSync as HF}from"node:fs";import{homedir as BF,tmpdir as WF}from"node:os";import{join as Do}from"node:path";function zF(t){return vs(t.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g,"")).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"\uFFFD")}function Fo(t){return zF(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(KF,"$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 YF(){let t=process.env.LMCTL_HOME||(process.env.NODE_ENV==="test"?Do(WF(),`lmctl-test-${process.pid}`,".lmctl"):Do(process.env.HOME||BF(),".lmctl"));return Do(t,"provider-errors")}function QF(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)}
|
|
2192
2192
|
\u2026 ${i} characters of ${n} \u2026
|
|
2193
2193
|
${t.slice(-s)}`}function ZF(t,e){try{let n=$F(t).filter(s=>VF.test(s)).sort().map(s=>{let i=Do(t,s);return{path:i,size:jF(i).size}}),r=n.reduce((s,i)=>s+i.size,0);for(let s=0;s<n.length&&(n.length-s>GF||r>JF);s++){let i=n[s];i.path!==e&&(UF(i.path),r-=i.size)}}catch{}}function e$(t,e){let n=YF(),r=Do(n,`stderr-${Date.now()}-${process.pid}-${DF()}.log`);try{FF(n,{recursive:!0,mode:448}),GE(n,448);let s=`[${new Date().toISOString()}] provider=${e}
|
|
2194
2194
|
${QF(t,XF,"provider output not saved")}
|
|
@@ -2207,10 +2207,10 @@ ${r}`}}}function gi(t,e){return e===""?t:`${t}:${e.includes(`
|
|
|
2207
2207
|
`)){let n=e.trim();if(!n||n.startsWith("#"))continue;if(n.startsWith("["))break;let r=/^debug\s*=\s*(.+)$/.exec(n);if(r){let s=r[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function f$(){try{let t=YE(_c(Fp(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var QE,KE,zE,l$,yc,Se=L(()=>{"use strict";sn();QE=!1,KE=!1,zE=0,l$=5e3;yc=null});import{existsSync as tT,mkdirSync as g$,readFileSync as nT,writeFileSync as ZE}from"node:fs";import{join as $o,resolve as h$}from"node:path";function rT(t){if(t==="allow")return!0;if(t&&typeof t=="object"&&!Array.isArray(t)){let e=Object.entries(t);if(e.length===1&&e[0][0]==="*"&&e[0][1]==="allow")return!0}return!1}function $p(t,e,n={existsSync:tT,readFileSync:nT}){let r=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let i=h$(e,s.sessiondir??e);for(let o of y$(i)){let a=_$(o,n);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(rT(a.permission)||r.push(`[${s.alias}] ${o} sets a non-allow \`permission\`, which opencode merges over lmctl's YOLO (.opencode/opencode.json permission:"allow") \u2014 the member may hang on permission prompts. Set \`permission: "allow"\` in that file (or remove the key).`))}}return r}function y$(t){return[$o(t,".opencode","opencode.jsonc"),$o(t,"opencode.jsonc"),$o(t,"opencode.json")]}function _$(t,e){try{if(!e.existsSync(t))return;let n=e.readFileSync(t,"utf-8"),r=JSON.parse(v$(n));return r===null||typeof r!="object"||Array.isArray(r)?void 0:r}catch{return}}function v$(t){let e="",n=!1,r="",s=!1;for(let i=0;i<t.length;i+=1){let o=t[i],a=t[i+1];if(n){e+=o,s?s=!1:o==="\\"?s=!0:o===r&&(n=!1,r="");continue}if(o==='"'||o==="'"){n=!0,r=o,e+=o;continue}if(o==="/"&&a==="/"){for(;i<t.length&&t[i]!==`
|
|
2208
2208
|
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function sT(t,e={}){let n=$o(t,".opencode"),r=$o(n,"opencode.json");if(!tT(r)){g$(n,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return ZE(r,o+`
|
|
2209
2209
|
`,"utf-8"),!0}let s;try{s=JSON.parse(nT(r,"utf-8"))}catch{return console.log(eT.yellow(` .opencode/opencode.json at ${r} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(eT.yellow(` .opencode/opencode.json at ${r} is not an object \u2014 skipping opencode config install.`)),!1;let i=!1;return s.permission===void 0&&(s.permission="allow",i=!0),rT(s.permission)||X({event:"opencode_yolo_override",provider:"opencode",config_path:r,user_permission:s.permission,message:`opencode.json has a user-set 'permission' value other than 'allow' \u2014 lmctl's YOLO contract is NOT in effect; turns may hang waiting on permission prompts. Set permission: "allow" or remove the key to restore YOLO.`}),i&&ZE(r,JSON.stringify(s,null,2)+`
|
|
2210
|
-
`,"utf-8"),i}var eT,jp=L(()=>{"use strict";Se();eT={yellow:t=>t}});function Uo(t,e){let n;if(e&&typeof e=="object"){let r=e.code;typeof r=="number"&&(n=r)}return new jo(t,n,e)}var Or,xe,Pe,vc,jo,Lr=L(()=>{"use strict";Or=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},xe=class extends Or{},Pe=class extends Or{constructor(n,r,s=null,i){super(n);this.exitCode=r;this.signal=s;this.stderr=i}},vc=class extends Or{line;constructor(e,n,r){super(e,{cause:r}),this.line=n}},jo=class extends Or{rpcCode;rpcData;constructor(e,n,r){super(e),n!==void 0&&(this.rpcCode=n),r!==void 0&&(this.rpcData=r)}}});import*as Hp from"node:child_process";function w$(t){if(typeof Hp.spawnSync=="function")try{Hp.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function iT(t){return t.exitCode!==null||t.signalCode!==null}function Up(t,e){return iT(t)?Promise.resolve(!0):new Promise(n=>{let r=!1,s=()=>{r||(r=!0,clearTimeout(i),n(!0))},i=setTimeout(()=>{r||(r=!0,t.removeListener("exit",s),n(!1))},e);t.once("exit",s)})}async function ye(t,e={}){let n=Date.now(),r=e.stdinEnd!==!1,s=e.softDelayMs??5e3,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??w$;if(iT(t))return{signal:"natural",elapsedMs:Date.now()-n};if(r&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Up(t,s))return{signal:"stdin",elapsedMs:Date.now()-n};if(o==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await Up(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-n};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Up(t,b$)?{signal:"SIGKILL",elapsedMs:Date.now()-n}:{signal:"abandoned",elapsedMs:Date.now()-n}}var b$,bs=L(()=>{"use strict";b$=1e3});async function wc(t,e,n){if(typeof t=="boolean")return t;let r,s;try{return await Promise.race([t,new Promise(i=>{r=setTimeout(()=>i(Bp),e),r.unref?.(),n!==void 0&&(s=()=>i(Bp),n.addEventListener("abort",s,{once:!0}))})])}finally{r!==void 0&&clearTimeout(r),s!==void 0&&n?.removeEventListener("abort",s)}}function
|
|
2210
|
+
`,"utf-8"),i}var eT,jp=L(()=>{"use strict";Se();eT={yellow:t=>t}});function Uo(t,e){let n;if(e&&typeof e=="object"){let r=e.code;typeof r=="number"&&(n=r)}return new jo(t,n,e)}var Or,xe,Pe,vc,jo,Lr=L(()=>{"use strict";Or=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},xe=class extends Or{},Pe=class extends Or{constructor(n,r,s=null,i){super(n);this.exitCode=r;this.signal=s;this.stderr=i}},vc=class extends Or{line;constructor(e,n,r){super(e,{cause:r}),this.line=n}},jo=class extends Or{rpcCode;rpcData;constructor(e,n,r){super(e),n!==void 0&&(this.rpcCode=n),r!==void 0&&(this.rpcData=r)}}});import*as Hp from"node:child_process";function w$(t){if(typeof Hp.spawnSync=="function")try{Hp.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function iT(t){return t.exitCode!==null||t.signalCode!==null}function Up(t,e){return iT(t)?Promise.resolve(!0):new Promise(n=>{let r=!1,s=()=>{r||(r=!0,clearTimeout(i),n(!0))},i=setTimeout(()=>{r||(r=!0,t.removeListener("exit",s),n(!1))},e);t.once("exit",s)})}async function ye(t,e={}){let n=Date.now(),r=e.stdinEnd!==!1,s=e.softDelayMs??5e3,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??w$;if(iT(t))return{signal:"natural",elapsedMs:Date.now()-n};if(r&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Up(t,s))return{signal:"stdin",elapsedMs:Date.now()-n};if(o==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await Up(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-n};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Up(t,b$)?{signal:"SIGKILL",elapsedMs:Date.now()-n}:{signal:"abandoned",elapsedMs:Date.now()-n}}var b$,bs=L(()=>{"use strict";b$=1e3});async function wc(t,e,n){if(typeof t=="boolean")return t;let r,s;try{return await Promise.race([t,new Promise(i=>{r=setTimeout(()=>i(Bp),e),r.unref?.(),n!==void 0&&(s=()=>i(Bp),n.addEventListener("abort",s,{once:!0}))})])}finally{r!==void 0&&clearTimeout(r),s!==void 0&&n?.removeEventListener("abort",s)}}function En(t,e){if(t===void 0){e.closeStdin();return}let n=!1,r=i=>{if(!n){n=!0;try{t.onRelease?.({elapsedMs:Date.now()-i.startedMs,held:i.held,reason:i.reason})}catch{}}e.closeStdin()},s=Date.now();R$(t,e,s,r).catch(()=>{r({startedMs:s,held:!1,reason:"check-error"})})}async function R$(t,e,n,r){let s=t.pollMs??E$,i=t.maxHoldMs??bc,o=t.settleMs??T$,a=t.backgroundGraceMs??S$,l=!1,c=null,u=d=>r({startedMs:n,held:l,reason:d});for(;;){if(e.isAborted())return u("aborted");if(e.hasChildExited())return u("child-exited");let d=i-(Date.now()-n);if(d<=0)return u("max-hold");let m;try{m=await wc(t.hasOutstandingWork(),d,e.signal)}catch{return u("check-error")}if(m===Bp)return u(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(m)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-n<a){let g=a-(Date.now()-n);await new Promise(h=>setTimeout(h,Math.max(0,Math.min(s,k$,g))).unref?.());continue}if(!l||o<=0)return u("cleared");c===null&&(c=Date.now(),Je(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let f=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-f>=o)return u("cleared")}if(l||(l=!0,t.onHold?.(),Je(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-n>=i)return X({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-n}),u("max-hold");let p=Math.max(0,Math.min(s,i-(Date.now()-n)));await new Promise(f=>setTimeout(f,p).unref?.())}}var E$,bc,T$,S$,k$,Bp,Ho=L(()=>{"use strict";Se();E$=2e3,bc=8*60*60*1e3,T$=5e3,S$=1e3,k$=50,Bp=Symbol("check-timed-out")});function oT(t){Ce()&&dt({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function Mr(t,e){let n=x$[t];if(n)return n[e]??n.yolo}function C$(t,e){if(e.length===0)return!0;for(let n=0;n+e.length<=t.length;n++){let r=!0;for(let s=0;s<e.length;s++)if(t[n+s]!==e[s]){r=!1;break}if(r)return!0}return!1}function qe(t,e,n="yolo"){if(A$.has(t)){oT(`YOLO ${t} [mode=${n}]: ${t==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${n==="plan"?"read-only":"danger-full-access"})`:t==="opencode"?".opencode/opencode.json (permission=allow)":t==="kimi"?`ACP session/set_config_option (configId=mode, value=${n==="plan"?"plan":"auto"})`:t==="dsh"?"DSH_PERMISSION_MODE=danger-full-access env var on the sidecar spawn \u2014 no argv flag":t==="hermes"?"HERMES_YOLO_MODE=1 shell gate + ACP session/set_mode (modeId=dont_ask) edit gate":t==="pi"?"no tool-permission prompts exist in pi by design \u2014 nothing to bypass":t==="muse"?"MSP approval mode plus fixed host sandbox/write/shell posture":t==="miniplayer"?"native tools always granted; no permission mode":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let r=n==="plan"?Mr(t,"plan"):I$[t];if(!r){let s=`unknown provider "${t}" \u2014 YOLO contract not configured. Add an entry to YOLO_FLAGS in src/providers/yolo-contract.ts before spawning this provider.`;throw X({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new xe(s)}if(!C$(e,r)){let s=r.join(" "),i=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(o=>JSON.stringify(o)).join(", ")}]`;throw X({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:n,args:e.join(" "),message:i}),new xe(i)}oT(`YOLO ${t} [mode=${n}]: argv flag '${r.join(" ")}'`)}var I$,x$,A$,Tn=L(()=>{"use strict";Lr();Se();I$={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},x$={claude:{yolo:["--dangerously-skip-permissions"],plan:["--permission-mode","plan"]},qwen:{yolo:["--approval-mode","yolo"],plan:["--approval-mode","plan"]},gemini:{yolo:["-y"],plan:["--approval-mode","plan"]},copilot:{yolo:["--yolo"],plan:["--yolo"]},agy:{yolo:["--dangerously-skip-permissions"],plan:["--dangerously-skip-permissions"]},lmplayer:{yolo:["--dangerously-skip-permissions"],plan:["--dangerously-skip-permissions"]}};A$=new Set(["codex","opencode","kimi","dsh","hermes","pi","miniplayer","muse"])});import{existsSync as N$}from"node:fs";function aT(t){let e=t.CLAUDE_CODE_EXECPATH;if(e===void 0||e.length===0)return t;let n=process.platform!=="win32"&&e.toLowerCase().endsWith(".exe"),r=!n&&!N$(e);if(!n&&!r)return t;X({event:"claude_execpath_sanitized",reason:n?"wrong_platform_exe":"missing_file",value:e,platform:process.platform});let s={...t};return delete s.CLAUDE_CODE_EXECPATH,s}function hi(t,e){let n={...t??process.env,PWD:e};return delete n.OLDPWD,n}function L$(t,e){return e===void 0||e.length===0?t:{...t??process.env,[Wp]:e}}function je(t,e,n,r="chat"){return{...L$(hi(t,e),n),[O$]:r}}var Wp,O$,on=L(()=>{"use strict";Se();Wp="LMCTL_SELF_SESSIONID",O$="LMCTL_LAUNCH_SOURCE"});function Ec(t){let e=[...t.matchAll(M$)];if(e.length>0){let n=e[e.length-1],r=(n.index??0)+n[0].length;return lT(t.slice(r).trimStart())}return lT(j$(t.replace(P$,"")))}function j$(t){let e=D$.exec(t);if(e===null)return t;let n=t.slice(e[0].length),r=[...n.matchAll(F$)];if(r.length<2)return t;let s=r[0],i=(s.index??0)+s[0].length;return n.slice(i).trimStart()}function lT(t){let e=[...t.matchAll($$)];if(e.length===0)return t;let n=e[e.length-1],r=(n.index??0)+n[0].length;return t.slice(r).trimStart()}function Vn(t,e=""){let n=t.result;return typeof n?.sessionId=="string"&&n.sessionId.length>0?n.sessionId:e}function uT(t){let e=t.result;return typeof e?.stopReason=="string"?e.stopReason:""}function Tc(t={}){let e="",n="",r="",s=!1,i=!1,o=!1,a=t.isolateResult??(t.tool==="gemini"?Ec:void 0),l=()=>({result:a?a(n):n,sessionId:e,stopReason:r,sawActivity:o});return{setSessionId(c){e=c},beginTurn(){n="",r="",s=!1,i=!0,o=!1},completeTurn(c){return r=uT(c),s=!0,i=!1,l()},cancelTurn(){n="",r="",i=!1},processMessage(c){if(c.method!=="session/update")return!1;let d=c.params?.update,m=d?.sessionUpdate;if(typeof m!="string"||(i&&U$.has(m)&&(o=!0),m!=="agent_message_chunk"))return!1;let p=d?.content,f=typeof p?.text=="string"?p.text:"";return f&&i&&(n+=f,t.onDelta?.(f)),!0},finalize(){return s?l():null}}}var cT,M$,P$,D$,F$,$$,U$,Bo=L(()=>{"use strict";cT="(?:png|jpe?g|webp|heic|pdf)",M$=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${cT}\\s*`,"gi"),P$=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${cT}\\s*`,"i"),D$=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,F$=/^STANCE:\s+\S+\s*$/gim,$$=/\[Thought:\s*true\]\s*/gi;U$=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"])});import{createInterface as H$}from"node:readline";function Pr(t,e){let n=e.protocol??"acp",r=H$({input:t.stdout}),s=new Map,i=(a,l={},c)=>new Promise((u,d)=>{let m=B$++;s.set(m,{resolve:u,reject:d,onResponse:c});let p=JSON.stringify({jsonrpc:"2.0",id:m,method:a,params:l});dt({event:`${n}_send`,direction:"SEND",provider:e.provider,method:a,id:m,params:l}),t.stdin?.write(`${p}
|
|
2211
2211
|
`)}),o=(a,l={})=>{t.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:a,params:l})}
|
|
2212
2212
|
`)};return r.on("line",a=>{let l=d=>{if(!e.onProtocolError)return;let m=a.slice(0,512);X({event:`${n}_protocol_error`,provider:e.provider,reason:d,raw_preview:m,truncated:a.length>512}),e.onProtocolError(new Error(`${n.toUpperCase()} ${d}: ${JSON.stringify(m)}${a.length>512?" (truncated)":""}`))},c;try{c=JSON.parse(a)}catch{l("returned malformed JSON");return}if(!c||typeof c!="object"||Array.isArray(c)){l("returned an invalid message");return}if(dt({event:`${n}_recv`,direction:"RECV",provider:e.provider,id:typeof c.id=="number"?c.id:void 0,method:typeof c.method=="string"?c.method:void 0,preview:JSON.stringify(c).slice(0,300)}),e.onEvent?.(c),typeof c.method!="string"&&typeof c.id=="number"&&s.has(c.id)){let d=s.get(c.id);s.delete(c.id);try{d.onResponse?.(c)}catch(m){d.reject(m instanceof Error?m:new Error(String(m)));return}if(c.error){let m=c.error,p=typeof m?.message=="string"&&m.message.length>0?m.message:JSON.stringify(c.error);d.reject(Uo(`${n.toUpperCase()} RPC error: ${p}`,m))}else d.resolve(c);return}let u=c.method;if(!u){l("returned an uncorrelated response");return}if(typeof c.id=="number"||typeof c.id=="string"){X({event:`${n}_unhandled_request`,provider:e.provider,method:u,id:c.id,params:c.params});let d=JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32601,message:`Method not found: ${u} (lmctl does not implement server-side ${n.toUpperCase()} methods)`}});dt({event:`${n}_send`,direction:"SEND",provider:e.provider,replyTo:c.id,error:"method not found"}),t.stdin?.write(`${d}
|
|
2213
|
-
`);return}e.onNotification?.(c)}),{sendRpc:i,sendNotification:o,close(a=new xe(`${n.toUpperCase()} RPC channel closed`)){r.close();for(let l of s.values())l.reject(a);s.clear()}}}var B$,qp=L(()=>{"use strict";Se();Lr();B$=1});var Xp=L(()=>{"use strict";qp()});var Sc,dT=L(()=>{"use strict";Sc={name:"miniplayer",binary:"miniplayer",baseArgs:["acp"],argv:t=>{if(t.permissionMode==="plan")throw new Error("miniplayer has no plan mode; its native tools always have full permissions");return["acp",...t.model?["-m",t.model]:[]]}}});import{readFileSync as W$,readdirSync as mT}from"node:fs";import{join as kc}from"node:path";function pT(t,e){let n=e.GEMINI_DIR??process.env.GEMINI_DIR??kc(ie,".gemini"),r=kc(n,"tmp"),s;try{s=mT(r)}catch{throw new Error(`gemini bundle: cannot read the gemini session store at ${r} \u2014 cannot verify session "${t}"`)}let i=`"sessionId": "${t}"`,o=`"sessionId":"${t}"`;for(let a of s){let l=kc(r,a,"chats"),c;try{c=mT(l)}catch{continue}for(let u of c){if(!u.endsWith(".json"))continue;let d;try{d=W$(kc(l,u),"utf8").slice(0,8192)}catch{continue}if(d.includes(i)||d.includes(o))return}}throw new Error(`gemini bundle: no session "${t}" in the gemini chats store (${r}) \u2014 the session must exist on disk before a bundle can resume it`)}var Wo,fT=L(()=>{"use strict";Bo();We();
|
|
2213
|
+
`);return}e.onNotification?.(c)}),{sendRpc:i,sendNotification:o,close(a=new xe(`${n.toUpperCase()} RPC channel closed`)){r.close();for(let l of s.values())l.reject(a);s.clear()}}}var B$,qp=L(()=>{"use strict";Se();Lr();B$=1});var Xp=L(()=>{"use strict";qp()});var Sc,dT=L(()=>{"use strict";Sc={name:"miniplayer",binary:"miniplayer",baseArgs:["acp"],argv:t=>{if(t.permissionMode==="plan")throw new Error("miniplayer has no plan mode; its native tools always have full permissions");return["acp",...t.model?["-m",t.model]:[]]}}});import{readFileSync as W$,readdirSync as mT}from"node:fs";import{join as kc}from"node:path";function pT(t,e){let n=e.GEMINI_DIR??process.env.GEMINI_DIR??kc(ie,".gemini"),r=kc(n,"tmp"),s;try{s=mT(r)}catch{throw new Error(`gemini bundle: cannot read the gemini session store at ${r} \u2014 cannot verify session "${t}"`)}let i=`"sessionId": "${t}"`,o=`"sessionId":"${t}"`;for(let a of s){let l=kc(r,a,"chats"),c;try{c=mT(l)}catch{continue}for(let u of c){if(!u.endsWith(".json"))continue;let d;try{d=W$(kc(l,u),"utf8").slice(0,8192)}catch{continue}if(d.includes(i)||d.includes(o))return}}throw new Error(`gemini bundle: no session "${t}" in the gemini chats store (${r}) \u2014 the session must exist on disk before a bundle can resume it`)}var Wo,fT=L(()=>{"use strict";Bo();We();Tn();Wo={name:"gemini",binary:"gemini",baseArgs:["--acp","-y","--skip-trust"],argv(t){let e=[...Wo.baseArgs];if(t.permissionMode==="plan"){let n=Mr("gemini","plan"),r=Mr("gemini","yolo");e=e.filter(s=>!(r??[]).includes(s)),n&&e.push(...n)}return t.model&&e.push("--model",t.model),e},isolateResult:Ec,sessionIdentity:{verifyLoadedSession:t=>{pT(t.requestedSessionId,t.env)},recheckSession:t=>{pT(t.requestedSessionId,t.env)}}}});import{existsSync as q$,readFileSync as X$}from"node:fs";import{join as Gp}from"node:path";function gT(t,e){let n=e.COPILOT_HOME??process.env.COPILOT_HOME??Gp(ie,".copilot"),r=Gp(n,"session-state",t),s=Gp(r,"workspace.yaml");if(!q$(s))throw new Error(`copilot bundle: no session "${t}" in the copilot session store (${r}) \u2014 the session must exist on disk before a bundle can resume it`);let i;try{i=X$(s,"utf8").slice(0,4096)}catch(a){throw new Error(`copilot bundle: cannot read ${s} \u2014 cannot verify session "${t}": `+(a instanceof Error?a.message:String(a)))}let o=/^id:\s*(\S+)\s*$/m.exec(i);if(o===null||o[1]!==t)throw new Error(`copilot bundle: session store entry ${s} belongs to ${o?.[1]??"no recorded id"}, not "${t}"`)}var qo,hT=L(()=>{"use strict";Se();We();qo={name:"copilot",binary:"copilot",baseArgs:["--acp","--yolo"],argv(t){return t.permissionMode==="plan"&&(process.stderr.write(`[acp] copilot has no plan-mode flag in --acp mode; --permission-mode plan is not honored (running yolo). See src/providers/yolo-contract.ts.
|
|
2214
2214
|
`),X({event:"acp_plan_mode_unsupported",provider:"copilot",requested_mode:"plan",effective_mode:"yolo"})),t.model&&(process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${t.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
2215
2215
|
`),X({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...qo.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{gT(t.requestedSessionId,t.env)},recheckSession:t=>{gT(t.requestedSessionId,t.env)}}}});import{existsSync as Vp,readdirSync as G$,statSync as yT}from"node:fs";import{join as Dr}from"node:path";import{createRequire as J$}from"node:module";function Kp(){return Jp===null&&(Jp=J$(import.meta.url)("node:sqlite").DatabaseSync),Jp}function _T(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalCacheWriteInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function vT(t,e){if(!e)return;t.observed=!0;let n=e.input??0,r=e.output??0,s=e.reasoning??0,i=e.cache?.read??0,o=e.cache?.write??0;if(t.totalInputTokens+=n,t.totalCachedInputTokens+=i,t.totalCacheWriteInputTokens+=o,t.totalOutputTokens+=r,t.totalReasoningOutputTokens+=s,n+r+s+i+o>0){let a=n+i+o;t.lastInputTokens=a,t.lastTokenUsage={inputTokens:n,cachedInputTokens:i,cacheWriteInputTokens:o,outputTokens:r,reasoningOutputTokens:s,totalTokens:a+r+s}}}function bT(t){return t.observed?{totalInputTokens:t.totalInputTokens,totalCachedInputTokens:t.totalCachedInputTokens,totalCacheWriteInputTokens:t.totalCacheWriteInputTokens,totalOutputTokens:t.totalOutputTokens,totalReasoningOutputTokens:t.totalReasoningOutputTokens,lastInputTokens:t.lastInputTokens,lastTokenUsage:t.lastTokenUsage}:{}}function wT(){let t=process.env.XDG_DATA_HOME||Dr(ie,".local","share"),e=process.env.XDG_CONFIG_HOME||Dr(ie,".config");return[Dr(t,"opencode","opencode.db"),Dr(e,"opencode","opencode.db")]}function V$(){return zp(process.env,ie)}function zp(t,e){if(t.OPENCODE_DB)return[t.OPENCODE_DB];let n=t.XDG_DATA_HOME||Dr(e,".local","share"),r=Dr(n,"lmplayer"),s=Dr(r,"opencode-local.db"),i=[s];try{let o=G$(r).filter(a=>/^opencode.*\.db$/u.test(a)).map(a=>Dr(r,a)).filter(a=>a!==s).sort((a,l)=>{try{return yT(l).mtimeMs-yT(a).mtimeMs}catch{return 0}});i.push(...o)}catch{}return i}function K$(t){return t==="lmplayer"?V$():wT()}function Yp(t,e){let n=e?.dbPath!==void 0?[e.dbPath]:wT();for(let r of n){if(!Vp(r))continue;let s=new(Kp())(r,{open:!0,readOnly:!0});try{s.exec("PRAGMA busy_timeout = 5000");let i=s.prepare("SELECT directory FROM session WHERE id = ?").get(t);if(i!==void 0)return{directory:typeof i.directory=="string"?i.directory:""}}finally{s.close()}}return null}var Jp,yi,Xo=L(()=>{"use strict";We();Se();Jp=null;yi=class{name;startCommand;dbPaths;busyTimeoutMs;constructor(e){this.name=e?.providerName??"opencode",this.startCommand=e?.startCommand??this.name,this.busyTimeoutMs=e?.busyTimeoutMs??5e3,e?.dbPaths?this.dbPaths=[...e.dbPaths]:e?.dbPath?this.dbPaths=[e.dbPath]:this.dbPaths=K$(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>Vp(e))}openDb(e){if(!Vp(e))return null;let n=new(Kp())(e,{open:!0,readOnly:!0});return n.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),n}async discoverSessions(){let e=[];for(let n of this.existingDbPaths()){let r=this.openDb(n);if(r)try{let s=new Map,i=r.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=r.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
2216
2216
|
s.time_created, s.time_updated
|
|
@@ -2234,27 +2234,27 @@ One possible cause: the provider process failed before a complete ACP response w
|
|
|
2234
2234
|
${Ae(e,{provider:t.tool,...t.fullOutput===void 0?{}:{fullOutput:t.fullOutput}})}
|
|
2235
2235
|
|
|
2236
2236
|
${n}`:n}function oj(t,e){return Ko(t)?.filterExpectedStderr?.(e)??e}function AT(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 CT(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&&Je(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 NT(t,e,n){let r=je(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(qe(e.tool,i,o),e.cwd&&!sj(e.cwd))throw X({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new xe(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:r}}async function OT(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
|
|
2237
|
-
`),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=Vn(m),s.setSessionId(a),{sessionId:a,sessionResponse:m}}let u=Vn(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=Vn(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=Vn(c,r.sessionId);l=c,s.setSessionId(a)}else{let c=await e("session/new",{cwd:r.cwd,mcpServers:[]});a=Vn(c),l=c,s.setSessionId(a)}return{sessionId:a,sessionResponse:l}}function LT(t,e){let n=Ko(e.tool);if(!n)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{xT(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:k=>{o.push(k)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=NT(n,e,a))}catch(k){return s(k instanceof Error?k:new Error(String(k)))}let d=IT(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),p=!1,f=!1,g=0,h=!1,y=!1;if(e.signal){if(e.signal.aborted)return p=!0,X({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ye(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,X({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),ye(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let b=e.sessionId||"",_=Tc({tool:e.tool,onDelta:e.onDelta,...n.isolateResult?{isolateResult:n.isolateResult}:{}});_.setSessionId(b);let v=Pr(d,{provider:e.tool,onEvent:k=>{g=Date.now(),AT(k)&&(y=!0),e.onEvent?.(k)},onNotification:k=>{g=Date.now(),_.processMessage(k)}}),{sendRpc:E,sendNotification:I}=v,T="";d.stderr?.on("data",k=>{T+=k.toString()}),d.on("error",k=>{v.close(k),X({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:k.message,elapsed_ms:Date.now()-m}),s(new xe(`Failed to spawn ${n.binary} ${n.baseArgs.join(" ")}: ${k.message}`,{cause:k}))}),d.on("exit",(k,N)=>{if(f=!0,v.close(new Pe(`ACP process ${N?`terminated by ${N}`:`exited with code ${String(k)}`}`,k,N)),p)return;let C=_.finalize();if(C!==null)n.onExitFinalization?.({...a,sessionId:C.sessionId,result:C.result,stopReason:C.stopReason,exitCode:k}),r({result:C.result,sessionId:C.sessionId,durationMs:Date.now()-m,stopReason:C.stopReason,exitCode:k,sawActivity:C.sawActivity,...o.length>0?{warnings:o}:{}});else{let O=oj(e.tool,T),w=ij({tool:e.tool,exitCode:k,signal:N,stderr:O,fullOutput:T});X({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:k,signal:N,stderr_summary:w,elapsed_ms:Date.now()-m}),s(new Pe(w,k,N,T))}}),(async()=>{try{let k=await OT({sendRpc:E,sendNotification:I,opts:e,outputProcessor:_});b=k.sessionId,e.onSessionId?.(b);let N=k.sessionResponse;await CT(n,a,{sessionId:b,response:N},E),_.beginTurn(),h=!0,Je(`acp: prompt sent (${t.length} chars)`);let C;if(await E("session/prompt",{sessionId:b,prompt:[{type:"text",text:t}]},O=>{O.error?_.cancelTurn():C=_.completeTurn(O)}),!C)throw new Error("ACP prompt completed without a result boundary");h=!1,Je(`acp: result received (${C.result.length} chars, stopReason=${C.stopReason})`),wn(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>f,isTurnInFlight:()=>h,lastEventAtMs:()=>g,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>y})}catch(k){ye(d).catch(()=>{}),s(k instanceof Error?k:new Error(String(k)))}})()})}async function MT(t){let e=Ko(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&xT(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}=NT(e,t,i),c=IT(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,g="";c.stderr?.on("data",N=>{g+=N.toString()});let h,y,b=Tc({tool:t.tool,onDelta:N=>h?.(N),...e.isolateResult?{isolateResult:e.isolateResult}:{}});b.setSessionId(p);let _=Pr(c,{provider:t.tool,onEvent:N=>{d.lastEventAtMs=Date.now(),AT(N)&&(d.backgroundJobLaunched=!0),y?.(N)},onNotification:N=>{d.lastEventAtMs=Date.now(),b.processMessage(N)}}),v=()=>new Pe(`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,g),E=[],I=()=>d.exited?Promise.resolve():new Promise(N=>{E.push(N)}),T=null;c.on("error",N=>{f=new xe(`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,C)=>{if(d.exited=!0,d.exitCode=N,d.signal=C,_.close(new Pe(`ACP process ${C?`terminated by ${C}`:`exited with code ${String(N)}`}`,N,C)),!d.telemetryFired){d.telemetryFired=!0;let O=b.finalize();O!==null&&e.onExitFinalization?.({...i,sessionId:O.sessionId,result:O.result,stopReason:O.stopReason,exitCode:N})}if(T!==null){let O=T;T=null,O(v())}for(let O of E.splice(0))O()});try{let N=await OT({sendRpc:_.sendRpc,sendNotification:_.sendNotification,opts:t,outputProcessor:b,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async C=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:C,cwd:t.cwd,env:l})});p=N.sessionId,t.onSessionId?.(p),await CT(e,i,{sessionId:N.sessionId,response:N.sessionResponse},_.sendRpc)}catch(N){let C=f??(N instanceof Error?N:new Error(String(N)));throw ye(c).catch(()=>{}),C}let k=N=>new Promise(C=>{setTimeout(C,N).unref?.()});return{tool:t.tool,get sessionId(){return p},get completedTurns(){return d.completedTurns},async sendTurn(N,C={}){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(C.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(C.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,h=C.onDelta,y=C.onEvent;let O=Date.now();try{b.beginTurn(),Je(`acp: bundle prompt sent (${N.length} chars)`);let w,S=!1;if(await new Promise((x,A)=>{T=A;let M,P=()=>{S=!0,m=Promise.resolve().then(()=>M).catch(()=>{}),b.cancelTurn(),_.sendNotification("session/cancel",{sessionId:p}),A(new Error("Aborted"))},U=C.signal;U?.addEventListener("abort",P,{once:!0}),M=_.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:N}]},F=>{S||(F.error?b.cancelTurn():w=b.completeTurn(F),h=void 0,y=void 0)}),M.then(F=>{U?.removeEventListener("abort",P),x(F)},F=>{U?.removeEventListener("abort",P),A(F instanceof Error?F:new Error(String(F)))})}),T=null,!w)throw new Error("ACP prompt completed without a result boundary");d.turnInFlight=!1,d.completedTurns+=1,Je(`acp: bundle result received (${w.result.length} chars, stopReason=${w.stopReason})`);let R=s&&r.length>0?[...r]:void 0;return s=!1,{result:w.result,sessionId:w.sessionId,stopReason:w.stopReason,durationMs:Date.now()-O,sawActivity:w.sawActivity,...R!==void 0?{warnings:R}:{}}}catch(w){throw T=null,b.cancelTurn(),d.turnInFlight=!1,d.exited?v():w}finally{h=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(C=>{wn(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),C()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let N=t.closeTimeoutMs??2e3;await Promise.race([I(),k(N)]),d.exited||await ye(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,N),killDelayMs:Math.min(1e3,N)}).catch(()=>{})})()),d.closing}}}var rf=L(()=>{"use strict";Se();Lr();bs();Ho();En();Se();on();sn();Bo();Xp();RT();nf();Zp();Bo()});function Ic(t,e,n){return Wn(t)&&e.tools[t]?.agent===void 0&&n.includes(t)}async function Kn(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 _i(`session identity mismatch: expected "${n}", got "${t.sessionId}"`);let i=await t.sendTurn(r,s);if(i.sessionId!==n)throw Object.assign(new _i(`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 xc(t,e){oc(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 g=()=>f.abort();p.signal?.addEventListener("abort",g,{once:!0});try{let h=i?await Kn(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:h.usage,sessionId:h.sessionId});if(n&&h.sessionId!==e.sessionId)throw c=!0,Object.assign(new _i(`session identity mismatch: expected "${e.sessionId}", got "${h.sessionId}"`),{usage:h.usage,sessionId:h.sessionId});return h.status!=="empty"&&h.status!=="stalled"&&l++,h}catch(h){throw f.signal.aborted&&i&&t.protocol?.persistentCancellation==="session"&&(c=!0),h instanceof _i&&(c=!0,await i?.close()),h}finally{p.signal?.removeEventListener("abort",g),u=void 0}},close(){return d||(c=!0,u?.abort(),d=i?i.close():Promise.resolve()),d}}}var _i,vi=L(()=>{"use strict";ui();_i=class extends Error{}});import{realpathSync as aj}from"node:fs";import{resolve as lj}from"node:path";function sf(t){let e=lj(t);try{return aj(e)}catch{return e}}var PT=L(()=>{"use strict"});import{platform as DT}from"node:os";function zn(t){let e=new zo;for(let n of t)e.registerAdapter(n);return e}var zo,of=L(()=>{"use strict";PT();zo=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=sf(e.workspace);i=i.filter(a=>sf(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=DT()==="darwin"||DT()==="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 uf(){return new lf}function df(t){let e=!1;for(let n of t.split(`
|
|
2237
|
+
`),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=Vn(m),s.setSessionId(a),{sessionId:a,sessionResponse:m}}let u=Vn(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=Vn(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=Vn(c,r.sessionId);l=c,s.setSessionId(a)}else{let c=await e("session/new",{cwd:r.cwd,mcpServers:[]});a=Vn(c),l=c,s.setSessionId(a)}return{sessionId:a,sessionResponse:l}}function LT(t,e){let n=Ko(e.tool);if(!n)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{xT(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:k=>{o.push(k)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=NT(n,e,a))}catch(k){return s(k instanceof Error?k:new Error(String(k)))}let d=IT(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),p=!1,f=!1,g=0,h=!1,y=!1;if(e.signal){if(e.signal.aborted)return p=!0,X({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ye(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,X({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),ye(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let b=e.sessionId||"",_=Tc({tool:e.tool,onDelta:e.onDelta,...n.isolateResult?{isolateResult:n.isolateResult}:{}});_.setSessionId(b);let v=Pr(d,{provider:e.tool,onEvent:k=>{g=Date.now(),AT(k)&&(y=!0),e.onEvent?.(k)},onNotification:k=>{g=Date.now(),_.processMessage(k)}}),{sendRpc:E,sendNotification:I}=v,T="";d.stderr?.on("data",k=>{T+=k.toString()}),d.on("error",k=>{v.close(k),X({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:k.message,elapsed_ms:Date.now()-m}),s(new xe(`Failed to spawn ${n.binary} ${n.baseArgs.join(" ")}: ${k.message}`,{cause:k}))}),d.on("exit",(k,N)=>{if(f=!0,v.close(new Pe(`ACP process ${N?`terminated by ${N}`:`exited with code ${String(k)}`}`,k,N)),p)return;let C=_.finalize();if(C!==null)n.onExitFinalization?.({...a,sessionId:C.sessionId,result:C.result,stopReason:C.stopReason,exitCode:k}),r({result:C.result,sessionId:C.sessionId,durationMs:Date.now()-m,stopReason:C.stopReason,exitCode:k,sawActivity:C.sawActivity,...o.length>0?{warnings:o}:{}});else{let O=oj(e.tool,T),w=ij({tool:e.tool,exitCode:k,signal:N,stderr:O,fullOutput:T});X({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:k,signal:N,stderr_summary:w,elapsed_ms:Date.now()-m}),s(new Pe(w,k,N,T))}}),(async()=>{try{let k=await OT({sendRpc:E,sendNotification:I,opts:e,outputProcessor:_});b=k.sessionId,e.onSessionId?.(b);let N=k.sessionResponse;await CT(n,a,{sessionId:b,response:N},E),_.beginTurn(),h=!0,Je(`acp: prompt sent (${t.length} chars)`);let C;if(await E("session/prompt",{sessionId:b,prompt:[{type:"text",text:t}]},O=>{O.error?_.cancelTurn():C=_.completeTurn(O)}),!C)throw new Error("ACP prompt completed without a result boundary");h=!1,Je(`acp: result received (${C.result.length} chars, stopReason=${C.stopReason})`),En(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>f,isTurnInFlight:()=>h,lastEventAtMs:()=>g,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>y})}catch(k){ye(d).catch(()=>{}),s(k instanceof Error?k:new Error(String(k)))}})()})}async function MT(t){let e=Ko(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&xT(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}=NT(e,t,i),c=IT(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,g="";c.stderr?.on("data",N=>{g+=N.toString()});let h,y,b=Tc({tool:t.tool,onDelta:N=>h?.(N),...e.isolateResult?{isolateResult:e.isolateResult}:{}});b.setSessionId(p);let _=Pr(c,{provider:t.tool,onEvent:N=>{d.lastEventAtMs=Date.now(),AT(N)&&(d.backgroundJobLaunched=!0),y?.(N)},onNotification:N=>{d.lastEventAtMs=Date.now(),b.processMessage(N)}}),v=()=>new Pe(`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,g),E=[],I=()=>d.exited?Promise.resolve():new Promise(N=>{E.push(N)}),T=null;c.on("error",N=>{f=new xe(`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,C)=>{if(d.exited=!0,d.exitCode=N,d.signal=C,_.close(new Pe(`ACP process ${C?`terminated by ${C}`:`exited with code ${String(N)}`}`,N,C)),!d.telemetryFired){d.telemetryFired=!0;let O=b.finalize();O!==null&&e.onExitFinalization?.({...i,sessionId:O.sessionId,result:O.result,stopReason:O.stopReason,exitCode:N})}if(T!==null){let O=T;T=null,O(v())}for(let O of E.splice(0))O()});try{let N=await OT({sendRpc:_.sendRpc,sendNotification:_.sendNotification,opts:t,outputProcessor:b,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async C=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:C,cwd:t.cwd,env:l})});p=N.sessionId,t.onSessionId?.(p),await CT(e,i,{sessionId:N.sessionId,response:N.sessionResponse},_.sendRpc)}catch(N){let C=f??(N instanceof Error?N:new Error(String(N)));throw ye(c).catch(()=>{}),C}let k=N=>new Promise(C=>{setTimeout(C,N).unref?.()});return{tool:t.tool,get sessionId(){return p},get completedTurns(){return d.completedTurns},async sendTurn(N,C={}){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(C.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(C.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,h=C.onDelta,y=C.onEvent;let O=Date.now();try{b.beginTurn(),Je(`acp: bundle prompt sent (${N.length} chars)`);let w,S=!1;if(await new Promise((x,A)=>{T=A;let M,P=()=>{S=!0,m=Promise.resolve().then(()=>M).catch(()=>{}),b.cancelTurn(),_.sendNotification("session/cancel",{sessionId:p}),A(new Error("Aborted"))},U=C.signal;U?.addEventListener("abort",P,{once:!0}),M=_.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:N}]},F=>{S||(F.error?b.cancelTurn():w=b.completeTurn(F),h=void 0,y=void 0)}),M.then(F=>{U?.removeEventListener("abort",P),x(F)},F=>{U?.removeEventListener("abort",P),A(F instanceof Error?F:new Error(String(F)))})}),T=null,!w)throw new Error("ACP prompt completed without a result boundary");d.turnInFlight=!1,d.completedTurns+=1,Je(`acp: bundle result received (${w.result.length} chars, stopReason=${w.stopReason})`);let R=s&&r.length>0?[...r]:void 0;return s=!1,{result:w.result,sessionId:w.sessionId,stopReason:w.stopReason,durationMs:Date.now()-O,sawActivity:w.sawActivity,...R!==void 0?{warnings:R}:{}}}catch(w){throw T=null,b.cancelTurn(),d.turnInFlight=!1,d.exited?v():w}finally{h=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(C=>{En(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),C()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let N=t.closeTimeoutMs??2e3;await Promise.race([I(),k(N)]),d.exited||await ye(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,N),killDelayMs:Math.min(1e3,N)}).catch(()=>{})})()),d.closing}}}var rf=L(()=>{"use strict";Se();Lr();bs();Ho();Tn();Se();on();sn();Bo();Xp();RT();nf();Zp();Bo()});function Ic(t,e,n){return Wn(t)&&e.tools[t]?.agent===void 0&&n.includes(t)}async function Kn(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 _i(`session identity mismatch: expected "${n}", got "${t.sessionId}"`);let i=await t.sendTurn(r,s);if(i.sessionId!==n)throw Object.assign(new _i(`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 xc(t,e){oc(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 g=()=>f.abort();p.signal?.addEventListener("abort",g,{once:!0});try{let h=i?await Kn(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:h.usage,sessionId:h.sessionId});if(n&&h.sessionId!==e.sessionId)throw c=!0,Object.assign(new _i(`session identity mismatch: expected "${e.sessionId}", got "${h.sessionId}"`),{usage:h.usage,sessionId:h.sessionId});return h.status!=="empty"&&h.status!=="stalled"&&l++,h}catch(h){throw f.signal.aborted&&i&&t.protocol?.persistentCancellation==="session"&&(c=!0),h instanceof _i&&(c=!0,await i?.close()),h}finally{p.signal?.removeEventListener("abort",g),u=void 0}},close(){return d||(c=!0,u?.abort(),d=i?i.close():Promise.resolve()),d}}}var _i,vi=L(()=>{"use strict";ui();_i=class extends Error{}});import{realpathSync as aj}from"node:fs";import{resolve as lj}from"node:path";function sf(t){let e=lj(t);try{return aj(e)}catch{return e}}var PT=L(()=>{"use strict"});import{platform as DT}from"node:os";function zn(t){let e=new zo;for(let n of t)e.registerAdapter(n);return e}var zo,of=L(()=>{"use strict";PT();zo=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=sf(e.workspace);i=i.filter(a=>sf(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=DT()==="darwin"||DT()==="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 uf(){return new lf}function df(t){let e=!1;for(let n of t.split(`
|
|
2238
2238
|
`)){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 mf(t){let e=t.trimEnd().split(`
|
|
2239
2239
|
`).at(-1)?.trimStart()??"";if(!e.startsWith("{"))return!1;try{return JSON.parse(e),!1}catch{return!0}}function FT(t){let e,n=!1,r=!1,s;for(let i of t.split(`
|
|
2240
|
-
`)){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=mt(a.input_tokens),c=mt(a.cached_input_tokens);s={source:"wire",inputUncached:l===null||c===null||c>l?null:l-c,cacheRead:c,cacheWrite:0,output:mt(a.output_tokens),reasoning:mt(a.reasoning_output_tokens),modelReported:typeof o.model=="string"?o.model:null,providerCostUsd:null,reason:null,invalidCounters:
|
|
2241
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let m=d.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=m}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?n.providers?.[s.provider]??{}:n.global??{};if(i.min!==void 0){let m=$T(i.min);m!==null&&(d.min=m)}if(i.max!==void 0){let m=$T(i.max);m!==null&&(d.max=m)}s.provider?(n.providers||(n.providers={}),n.providers[s.provider]=d):n.global=d}i={}}for(let d of r){let m=d.trim();if(!m||m.startsWith("#"))continue;let p=hj(m);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let g=".profile.",h=p.indexOf(g);h!==-1?s={kind:"tool",tool:p.slice(5,h),profile:p.slice(h+g.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let f=gj(m);f&&s.kind!=="none"?i[f.key]=f.value:f&&!o&&(a[f.key]=f.value)}l();let c={tools:e};(n.global||n.providers)&&(c.compact=n);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function vj(t,e,n){if(!n)return"";let r=t.tools[e]??ff[e],s=r?.profiles?.[n]?.flags??ff[e]?.profiles?.[n]?.flags;if(s!==void 0)return s.trim();if(r?.profile_flag)return r.profile_flag.replace(/\{\{profile\}\}/g,n).trim();throw new Error(`Profile "${n}" is not configured for tool "${e}"`)}function jT(t,e){return!!t.tools[e]}function UT(t,e,n,r,s){let i=t.tools[e]??ff[e],o;if(i?.agent){let l=Ac(r);o=i.agent.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,l)}else{let l=pj[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,r));if(l.mode==="stdin"){let u=c.map(Ac).join(" ");o=`printf '%s\\n' ${Ac(r)} | ${u}`}else o=c.map(Ac).join(" ")}let a=vj(t,e,s);return a&&(o+=" "+a),o}var ff,pj,Yo=L(()=>{"use strict";ff={muse:{start:"muse",resume:"muse resume {{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},claude:{start:"claude",resume:"claude --resume {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},codex:{start:"codex",resume:"codex resume {{session_id}} --dangerously-bypass-approvals-and-sandbox",profiles:{default:{description:"Default profile",flags:""}}},opencode:{start:"opencode",resume:"opencode --session {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}},gemini:{start:"gemini",resume:"gemini --resume {{session_id}} -y",profiles:{default:{description:"Default profile",flags:""}}},copilot:{start:"copilot",resume:"copilot --resume={{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},qwen:{start:"qwen",resume:"qwen --resume {{session_id}} --approval-mode yolo",profiles:{default:{description:"Default profile",flags:""}}},agy:{start:"agy",resume:"agy --conversation {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},kimi:{start:"kimi --auto",resume:"kimi --session {{session_id}} --auto",profiles:{default:{description:"Default profile",flags:""}}},hermes:{start:"hermes",resume:"hermes --yolo --resume {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}}},pj={claude:{mode:"argv",argv:["claude","-p","{{prompt}}","--resume","{{session_id}}"]},codex:{mode:"argv",argv:["codex","exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","resume","{{session_id}}","{{prompt}}"]},opencode:{mode:"argv",argv:["opencode","run","--session","{{session_id}}","{{prompt}}"]},gemini:{mode:"argv",argv:["gemini","-p","{{prompt}}","--resume","{{session_id}}"]},copilot:{mode:"argv",argv:["gh","copilot","--","--resume={{session_id}}","-p","{{prompt}}","-s","--allow-all-tools"]},qwen:{mode:"argv",argv:["qwen","-p","{{prompt}}","--resume","{{session_id}}","--approval-mode","yolo"]},agy:{mode:"argv",argv:["agy","--conversation","{{session_id}}","-p","{{prompt}}","--dangerously-skip-permissions","--print-timeout","8h"]},kimi:{mode:"argv",argv:["kimi","-p","{{prompt}}","--session","{{session_id}}","--output-format","stream-json"]},hermes:{mode:"argv",argv:["hermes","--yolo","-z","{{prompt}}","--resume","{{session_id}}"]}}});function HT(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let n=Number(e);return!Number.isFinite(n)||n<=0?6e5:n}var BT=L(()=>{"use strict"});function Nc(t){let e=t?.prompt??
|
|
2240
|
+
`)){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=mt(a.input_tokens),c=mt(a.cached_input_tokens);s={source:"wire",inputUncached:l===null||c===null||c>l?null:l-c,cacheRead:c,cacheWrite:0,output:mt(a.output_tokens),reasoning:mt(a.reasoning_output_tokens),modelReported:typeof o.model=="string"?o.model:null,providerCostUsd:null,reason:null,invalidCounters:hn([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(mf(t)||df(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 mt,cj,af,lf,cf,pf=L(()=>{"use strict";vo();mt=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,cj=(t,e)=>t===null||e===null?null:mt(t+e),af=(t,e)=>JSON.stringify([t,e]),lf=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(af(e,n))}turn(e,n=""){return new cf(this,e,n)}};cf=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(af(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(af(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(I=>E[I]??null),c=a.total&&["inputTokens","cachedInputTokens","outputTokens"].every(E=>mt(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=mt(e.emittedAtMs)??u,m=mt(e.ordinal)??mt(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 g=a.last,h=mt(g.inputTokens),y=mt(g.cachedInputTokens),_={source:"wire",inputUncached:h===null||y===null||y>h?null:h-y,cacheRead:y,cacheWrite:mt(g.cacheWriteInputTokens??0),output:mt(g.outputTokens),reasoning:mt(g.reasoningOutputTokens),modelReported:null,providerCostUsd:null,reason:null,invalidCounters:hn([g.inputTokens,g.cachedInputTokens,g.cacheWriteInputTokens,g.outputTokens,g.reasoningOutputTokens])||h!==null&&y!==null&&y>h};[_.inputUncached,_.cacheRead,_.cacheWrite,_.output].includes(null)&&(_.reason="counter_not_exposed");let v=r.model??g.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 I=this.value[E],T=_[E];I!==null&&T!==null&&mt(I+T)===null&&(this.value.invalidCounters=!0,this.value.reason="counter_not_exposed"),this.value[E]=cj(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 uj,writeFileSync as O5,mkdirSync as L5}from"node:fs";import{join as dj,dirname as P5}from"node:path";import{homedir as mj}from"node:os";function fj(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function gj(t){let e=t.indexOf("=");if(e===-1)return null;let n=t.slice(0,e).trim(),r=fj(t.slice(e+1).trim());return n?{key:n,value:r}:null}function hj(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Ac(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function yj(){return dj(mj(),".lmctl","config.toml")}function Es(t){let e=t??yj(),n;try{n=uj(e,"utf-8")}catch{return{tools:{}}}return _j(n)}function $T(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 _j(t){let e={},n={},r=t.split(`
|
|
2241
|
+
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let m=d.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=m}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?n.providers?.[s.provider]??{}:n.global??{};if(i.min!==void 0){let m=$T(i.min);m!==null&&(d.min=m)}if(i.max!==void 0){let m=$T(i.max);m!==null&&(d.max=m)}s.provider?(n.providers||(n.providers={}),n.providers[s.provider]=d):n.global=d}i={}}for(let d of r){let m=d.trim();if(!m||m.startsWith("#"))continue;let p=hj(m);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let g=".profile.",h=p.indexOf(g);h!==-1?s={kind:"tool",tool:p.slice(5,h),profile:p.slice(h+g.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let f=gj(m);f&&s.kind!=="none"?i[f.key]=f.value:f&&!o&&(a[f.key]=f.value)}l();let c={tools:e};(n.global||n.providers)&&(c.compact=n);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function vj(t,e,n){if(!n)return"";let r=t.tools[e]??ff[e],s=r?.profiles?.[n]?.flags??ff[e]?.profiles?.[n]?.flags;if(s!==void 0)return s.trim();if(r?.profile_flag)return r.profile_flag.replace(/\{\{profile\}\}/g,n).trim();throw new Error(`Profile "${n}" is not configured for tool "${e}"`)}function jT(t,e){return!!t.tools[e]}function UT(t,e,n,r,s){let i=t.tools[e]??ff[e],o;if(i?.agent){let l=Ac(r);o=i.agent.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,l)}else{let l=pj[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,n).replace(/\{\{prompt\}\}/g,r));if(l.mode==="stdin"){let u=c.map(Ac).join(" ");o=`printf '%s\\n' ${Ac(r)} | ${u}`}else o=c.map(Ac).join(" ")}let a=vj(t,e,s);return a&&(o+=" "+a),o}var ff,pj,Yo=L(()=>{"use strict";ff={muse:{start:"muse",resume:"muse resume {{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},claude:{start:"claude",resume:"claude --resume {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},codex:{start:"codex",resume:"codex resume {{session_id}} --dangerously-bypass-approvals-and-sandbox",profiles:{default:{description:"Default profile",flags:""}}},opencode:{start:"opencode",resume:"opencode --session {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}},gemini:{start:"gemini",resume:"gemini --resume {{session_id}} -y",profiles:{default:{description:"Default profile",flags:""}}},copilot:{start:"copilot",resume:"copilot --resume={{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},qwen:{start:"qwen",resume:"qwen --resume {{session_id}} --approval-mode yolo",profiles:{default:{description:"Default profile",flags:""}}},agy:{start:"agy",resume:"agy --conversation {{session_id}} --dangerously-skip-permissions",profiles:{default:{description:"Default profile",flags:""}}},kimi:{start:"kimi --auto",resume:"kimi --session {{session_id}} --auto",profiles:{default:{description:"Default profile",flags:""}}},hermes:{start:"hermes",resume:"hermes --yolo --resume {{session_id}}",profiles:{default:{description:"Default profile",flags:""}}}},pj={claude:{mode:"argv",argv:["claude","-p","{{prompt}}","--resume","{{session_id}}"]},codex:{mode:"argv",argv:["codex","exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","resume","{{session_id}}","{{prompt}}"]},opencode:{mode:"argv",argv:["opencode","run","--session","{{session_id}}","{{prompt}}"]},gemini:{mode:"argv",argv:["gemini","-p","{{prompt}}","--resume","{{session_id}}"]},copilot:{mode:"argv",argv:["gh","copilot","--","--resume={{session_id}}","-p","{{prompt}}","-s","--allow-all-tools"]},qwen:{mode:"argv",argv:["qwen","-p","{{prompt}}","--resume","{{session_id}}","--approval-mode","yolo"]},agy:{mode:"argv",argv:["agy","--conversation","{{session_id}}","-p","{{prompt}}","--dangerously-skip-permissions","--print-timeout","8h"]},kimi:{mode:"argv",argv:["kimi","-p","{{prompt}}","--session","{{session_id}}","--output-format","stream-json"]},hermes:{mode:"argv",argv:["hermes","--yolo","-z","{{prompt}}","--resume","{{session_id}}"]}}});function HT(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let n=Number(e);return!Number.isFinite(n)||n<=0?6e5:n}var BT=L(()=>{"use strict"});function Nc(t){let e=t?.prompt??ce;if(t?.teamfile!==void 0){let n=t.teamfileContent??"";e=`${ce}${wj}${t.teamfile}:
|
|
2242
2242
|
${n}${Ej}${JSON.stringify(t.teamfile)}${Tj}`}return t?.flightToken&&(e=`${t.flightToken.startsWith("[lmctl-seed:")?t.flightToken:`[lmctl-seed:${t.flightToken}]`}
|
|
2243
|
-
${e}`),e}var bj,
|
|
2243
|
+
${e}`),e}var bj,ce,Cc,wj,Ej,Tj,ze=L(()=>{"use strict";bj="ACK: waiting for explicit lmctl task.",ce=`lmctl seed initial connection only. Create or pin this provider session, then stop. Do not inspect files, run commands, infer a task, delegate, or edit. Reply exactly: ${bj}`,Cc=`send this exact lmctl seed instruction: "${ce}"`,wj=`
|
|
2244
2244
|
|
|
2245
2245
|
Teamfile `,Ej=`
|
|
2246
2246
|
|
|
2247
|
-
After this seed finishes, use \`lmctl prompt `,Tj=' <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 WT}from"node:child_process";import{mkdirSync as Sj}from"node:fs";var Ts,_e,rt=L(()=>{"use strict";pf();Yo();BT();
|
|
2248
|
-
`: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=vs(o).trim(),d=vs(i).trim(),m=u||d;r({success:!1,...n?.signal?.aborted?{errorCode:"ABORT_ERR"}:{},error:m?Ae(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:Cc,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&&jT(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:h=>{l=h,r.onUsage?.(h)},onSessionId:h=>{h&&(c=h),r.onSessionId?.(h)},onDelta:h=>{a+=h,d(),r.onDelta?.(h)},onProgress:h=>{h.kind!=="api_retry"&&d(),r.onProgress?.(h)}},f=this.transportFn(n,p).then(h=>(m(),{...h,status:h.status??"ok"})).catch(h=>{throw m(),o==="external"?Object.assign(new Ts("Turn cancelled","external"),{usage:h.usage??l,sessionId:c}):h}),g=new Promise(h=>{u=h});return Promise.race([f,g])}runOneShotAgent(e,n,r){let s=UT(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:HT(n.env),c=WT(s,{shell:!0,cwd:n.cwd,env:je(n.env,n.cwd,n.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m,p,f=!1,g=null,h=null,y=()=>{clearTimeout(m),m=setTimeout(()=>{!mf(_)&&!df(_)&&E(g,h)},100)},b=l>0?setTimeout(()=>{d=!0,c.kill(),this.name==="codex"&&E(null)},l):void 0,_="",v="";if(c.stdout?.on("data",I=>{let T=I.toString();_+=T,n.onDelta?.(T),f&&!u&&y()}),c.stderr?.on("data",I=>{v+=I.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=(I,T=null)=>{if(u)return;u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),this.name==="codex"&&(c.stdout?.destroy(),c.stderr?.destroy());let k=Date.now()-i,N=this.name==="codex"?FT(_):{};N.usage&&n.onUsage?.(N.usage),N.sessionId&&n.onSessionId?.(N.sessionId);let C=O=>Object.assign(O,{usage:N.usage,sessionId:N.sessionId??n.sessionId});if(this.name==="codex"&&n.signal?.aborted)a(C(new Ts("Turn cancelled","external")));else if(d)a(C(new Error(`Agent command timed out after ${l}ms`)));else if(I===0||I===null&&T===null)o({text:_.trim(),sessionId:N.sessionId??n.sessionId,durationMs:k,...N.usage?{usage:N.usage}:{}});else{let O=v.trim();a(C(new Pe(O?Ae(O,{provider:this.name}):T?`Agent command terminated by ${T}`:`Agent command exited with code ${I}`,I,T,v)))}};this.name==="codex"?(c.on("close",(I,T)=>E(I,T)),c.on("exit",(I,T)=>{u||(f=!0,g=I,h=T,y(),p=setTimeout(()=>E(I,T),5e3))})):c.on("exit",(I,T)=>E(I,T)),c.on("error",I=>{u||(u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),a(I))})})}}});function XT(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&&Ue(i+o)===null&&(e.invalidCounters=!0),e[s]=i===null||o===null?null:Ue(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 Ue,Fr,qT,Oc,bi,Lc=L(()=>{"use strict";vo();Ue=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,Fr=t=>typeof t=="string"&&t.length>0&&t!=="<synthetic>"?t:null,qT=()=>({source:"wire",inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:null});Oc=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=Fr(r?.first?.id),i=Fr(r?.last?.id),o=Fr(r?.stream?.id),a=Fr(r?.stream?.kind),l=s&&i&&o&&a?JSON.stringify([this.session,a,o,s,i]):Fr(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=Ue(e.promptTokens),d=Ue(c.outputTokens),m=Ue(c.cacheReadTokens),p=Ue(c.cacheWriteTokens),f=u===0,g=m??(f?0:null),h=p??(f?0:null),y=u!==null&&g!==null&&h!==null&&g+h<=u?u-g-h:null,b=(g??0)>0||(h??0)>0,_={...qT(),inputUncached:y,cacheRead:g,cacheWrite:h,output:d,reasoning:Ue(c.reasoningTokens),modelReported:Fr(e.modelId),invalidCounters:gn([e.promptTokens,e.totalTokens,c.inputTokens,c.cachedTokens,c.cacheReadTokens,c.cacheWriteTokens,c.outputTokens,c.reasoningTokens])||b||y===null||d===null||Ue(e.totalTokens)!==null&&u!==null&&d!==null&&e.totalTokens!==u+d||Ue(c.reasoningTokens)!==null&&d!==null&&c.reasoningTokens>d};return this.parts.push(_),!0}usage(){return XT(this.parts)}},bi=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=>Ue(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=>Ue(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=Ue(c.turn)!==null&&Ue(c.step)!==null?["step",c.turn,c.step]:Fr(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,{...qT(),inputUncached:Ue(m.inputTokens),cacheRead:Ue(m.cacheReadTokens),output:Ue(m.outputTokens),reasoning:Ue(m.reasoningTokens),modelReported:Fr(d.message?.source?.model),invalidCounters:o||[m.inputTokens,m.cacheReadTokens,m.outputTokens].some(p=>Ue(p)===null)||gn([m.inputTokens,m.cacheReadTokens,m.outputTokens,m.reasoningTokens])||Ue(m.reasoningTokens)!==null&&Ue(m.outputTokens)!==null&&m.reasoningTokens>m.outputTokens})}}lastUsage(){let e=[...this.parts.values()].at(-1);return e?{...e}:void 0}usage(){let e=XT([...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 kj}from"node:child_process";import{randomBytes as Rj}from"node:crypto";import{realpath as Mc}from"node:fs/promises";function Qo(){let t=Rj(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 Pc(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]:[]];qe("muse",n,t.permissionMode??"yolo");let r=kj(t.progPath??"muse",n,{cwd:t.cwd,env:je(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=VE(),g=Date.now(),h=t.sessionId;r.stderr.setEncoding("utf8"),r.stderr.on("data",w=>{f.append(w)});let y=(w,S,R)=>{if(s===w){if(s=void 0,w.id&&o.add(w.id),S){let x=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(S,{usage:x?{...x,outcome:w.outcome}:void 0,sessionId:h})}else R&&(R.usage=w.usage.usage());w.cleanup(),w.drained(),w.settled||(w.settled=!0,S?w.reject(S):(p++,w.resolve(R)))}},b=w=>{a||(a=w,s&&y(s,a),v.close(a),!m&&!c&&ye(r,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{}))},_=(w,S)=>{let R=S.params;if(!R||R.sessionId!==h)return;let x=S.method;if(x==="view/gap"||x==="session/closed"){b(new Error(`Muse ${x}: the conversation cannot continue without reopening`));return}if(x==="turn/unqueued"&&R.turnId===w.id){w.outcome="cancelled",y(w,new Ts("Muse queued turn cancelled","external"));return}x==="turn/started"&&R.turnId===w.id&&(w.queued=!1);let A=R.item,M=R.turnId??A?.turnId;if(M&&M!==w.id||x==="session/tokenUsage"&&(w.settled||R.turnId!==w.id||!w.usage.event(R,w.id)))return;w.opts.onEvent?.(S);let P={kind:"other",raw:S};if(["item/started","item/updated","item/completed"].includes(x)&&A?.turnId===w.id&&typeof A.itemId=="string"){let F=w.items.get(A.itemId);if(F&&typeof A.revision=="number"&&A.revision<=F.revision)return;w.items.set(A.itemId,{...A}),(A.kind==="toolCall"||A.kind==="userShell")&&x!=="item/updated"?P={kind:x==="item/completed"?"tool_result":"tool_use",id:A.itemId,tool:A.tool??A.kind,summary:A.failureReason??A.fallbackText,...x==="item/completed"?{status:A.status==="completed"?"ok":"error"}:{},...A.durationMs!==void 0?{elapsedMs:A.durationMs}:{},raw:S}:A.kind==="reasoning"?P={kind:"thinking",raw:S}:A.kind==="agentMessage"&&(P={kind:"text",raw:S})}else if(x==="item/delta"&&typeof R.itemId=="string"&&typeof R.delta=="string"){let F=w.items.get(R.itemId);if(!F)return;F.kind==="agentMessage"&&(R.field===void 0||R.field==="text")?(F.text=(F.text??"")+R.delta,w.cancelled||w.opts.onDelta?.(R.delta),P={kind:"text",raw:S}):F.kind==="reasoning"&&(P={kind:"thinking",raw:S})}if(w.cancelled||w.opts.onProgress?.(P),x!=="turn/completed"||R.turnId!==w.id)return;if(!["completed","failed","cancelled"].includes(R.terminal)){b(new Error(`Muse returned an unknown turn terminal: ${String(R.terminal)}`));return}if(w.cancelled||R.terminal==="cancelled"){w.outcome="cancelled",y(w,new Ts("Muse turn cancelled",w.cancelled?"external":"provider"));return}if(R.terminal!=="completed"){w.outcome="error",y(w,new Error(R.error?.message??R.reason??`Muse turn ended with ${String(R.terminal)}`));return}let U=[...w.items.values()].filter(F=>F.kind==="agentMessage");y(w,void 0,{text:U.map(F=>typeof F.text=="string"?F.text:"").join(`
|
|
2249
|
-
`),sessionId:h,durationMs:typeof R.durationMs=="number"?R.durationMs:Date.now()-w.started,stopReason:R.terminal,...U.some(F=>F.truncated)?{warnings:["Muse reported a truncated response; inspect the native transcript for complete content"]}:{}})},v=Pr(r,{provider:"muse",protocol:"msp",onProtocolError:b,onNotification:w=>{if(g=Date.now(),w.method==="view/gap"||w.method==="session/closed"){w.params?.sessionId===h&&!c&&b(new Error(`Muse ${w.method}: session must be reopened`));return}let S=s;S&&(S.id?_(S,w):S.events.push(w))}}),E=async(w,S,R=Qo())=>(await v.sendRpc(w,{...S,commandId:R})).result,I=w=>{!w.id||w.interruptSent||s!==w||(w.interruptSent=!0,E("turn/interrupt",{sessionId:h,turnId:w.id}).catch(S=>{s===w&&b(S instanceof Error?S:new Error(String(S)))}))},T=w=>{!w.id||w.unqueueSent||s!==w||(w.unqueueSent=!0,E("turn/unqueue",{sessionId:h,turnId:w.id}).catch(S=>{let R=S instanceof Error?S.message:String(S);/already started|not queued|launch boundary|turn is running/i.test(R)?(w.queued=!1,I(w)):s===w&&b(S instanceof Error?S:new Error(R))}))},k=w=>{w.queued?T(w):I(w)};r.on("error",w=>b(new Error(`Unable to start Muse: ${w.message}`)));let N=()=>{c||m||a||d||(d=!0,ye(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,S)=>{m=!0,c?v.close(new Error("Muse session closed")):b(new Error(gi(`Muse exited (${S??w}) after ${p} completed prompt(s)`,f.text().trim()?Ae(f.text(),{provider:"muse"}):""))),s&&y(s,new Error("Muse session closed"))});let C=()=>{if(l)return l;c=!0;let w=!!s;return s&&(s.cancelled=!0,k(s)),l=(async()=>{m||(await new Promise(S=>
|
|
2247
|
+
After this seed finishes, use \`lmctl prompt `,Tj=' <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 WT}from"node:child_process";import{mkdirSync as Sj}from"node:fs";var Ts,_e,rt=L(()=>{"use strict";pf();Yo();BT();ze();on();hc();sn();Lr();Ts=class t extends Error{cancelReason;constructor(e,n){super(e),this.name="TurnAbortError",this.cancelReason=n,Object.setPrototypeOf(this,t.prototype)}},_e=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===ce?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"}):(Sj(e,{recursive:!0}),new Promise(r=>{let s;try{try{n?.onDispatch?.()}catch{}s=WT(this.binary,this.seedArgsFor(n),{cwd:e,env:hi(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}
|
|
2248
|
+
`: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=vs(o).trim(),d=vs(i).trim(),m=u||d;r({success:!1,...n?.signal?.aborted?{errorCode:"ABORT_ERR"}:{},error:m?Ae(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:Cc,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&&jT(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:h=>{l=h,r.onUsage?.(h)},onSessionId:h=>{h&&(c=h),r.onSessionId?.(h)},onDelta:h=>{a+=h,d(),r.onDelta?.(h)},onProgress:h=>{h.kind!=="api_retry"&&d(),r.onProgress?.(h)}},f=this.transportFn(n,p).then(h=>(m(),{...h,status:h.status??"ok"})).catch(h=>{throw m(),o==="external"?Object.assign(new Ts("Turn cancelled","external"),{usage:h.usage??l,sessionId:c}):h}),g=new Promise(h=>{u=h});return Promise.race([f,g])}runOneShotAgent(e,n,r){let s=UT(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:HT(n.env),c=WT(s,{shell:!0,cwd:n.cwd,env:je(n.env,n.cwd,n.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m,p,f=!1,g=null,h=null,y=()=>{clearTimeout(m),m=setTimeout(()=>{!mf(_)&&!df(_)&&E(g,h)},100)},b=l>0?setTimeout(()=>{d=!0,c.kill(),this.name==="codex"&&E(null)},l):void 0,_="",v="";if(c.stdout?.on("data",I=>{let T=I.toString();_+=T,n.onDelta?.(T),f&&!u&&y()}),c.stderr?.on("data",I=>{v+=I.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=(I,T=null)=>{if(u)return;u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),this.name==="codex"&&(c.stdout?.destroy(),c.stderr?.destroy());let k=Date.now()-i,N=this.name==="codex"?FT(_):{};N.usage&&n.onUsage?.(N.usage),N.sessionId&&n.onSessionId?.(N.sessionId);let C=O=>Object.assign(O,{usage:N.usage,sessionId:N.sessionId??n.sessionId});if(this.name==="codex"&&n.signal?.aborted)a(C(new Ts("Turn cancelled","external")));else if(d)a(C(new Error(`Agent command timed out after ${l}ms`)));else if(I===0||I===null&&T===null)o({text:_.trim(),sessionId:N.sessionId??n.sessionId,durationMs:k,...N.usage?{usage:N.usage}:{}});else{let O=v.trim();a(C(new Pe(O?Ae(O,{provider:this.name}):T?`Agent command terminated by ${T}`:`Agent command exited with code ${I}`,I,T,v)))}};this.name==="codex"?(c.on("close",(I,T)=>E(I,T)),c.on("exit",(I,T)=>{u||(f=!0,g=I,h=T,y(),p=setTimeout(()=>E(I,T),5e3))})):c.on("exit",(I,T)=>E(I,T)),c.on("error",I=>{u||(u=!0,clearTimeout(b),clearTimeout(m),clearTimeout(p),a(I))})})}}});function XT(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&&Ue(i+o)===null&&(e.invalidCounters=!0),e[s]=i===null||o===null?null:Ue(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 Ue,Fr,qT,Oc,bi,Lc=L(()=>{"use strict";vo();Ue=t=>typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null,Fr=t=>typeof t=="string"&&t.length>0&&t!=="<synthetic>"?t:null,qT=()=>({source:"wire",inputUncached:null,cacheRead:null,cacheWrite:null,output:null,reasoning:null,modelReported:null,providerCostUsd:null,reason:null});Oc=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=Fr(r?.first?.id),i=Fr(r?.last?.id),o=Fr(r?.stream?.id),a=Fr(r?.stream?.kind),l=s&&i&&o&&a?JSON.stringify([this.session,a,o,s,i]):Fr(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=Ue(e.promptTokens),d=Ue(c.outputTokens),m=Ue(c.cacheReadTokens),p=Ue(c.cacheWriteTokens),f=u===0,g=m??(f?0:null),h=p??(f?0:null),y=u!==null&&g!==null&&h!==null&&g+h<=u?u-g-h:null,b=(g??0)>0||(h??0)>0,_={...qT(),inputUncached:y,cacheRead:g,cacheWrite:h,output:d,reasoning:Ue(c.reasoningTokens),modelReported:Fr(e.modelId),invalidCounters:hn([e.promptTokens,e.totalTokens,c.inputTokens,c.cachedTokens,c.cacheReadTokens,c.cacheWriteTokens,c.outputTokens,c.reasoningTokens])||b||y===null||d===null||Ue(e.totalTokens)!==null&&u!==null&&d!==null&&e.totalTokens!==u+d||Ue(c.reasoningTokens)!==null&&d!==null&&c.reasoningTokens>d};return this.parts.push(_),!0}usage(){return XT(this.parts)}},bi=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=>Ue(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=>Ue(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=Ue(c.turn)!==null&&Ue(c.step)!==null?["step",c.turn,c.step]:Fr(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,{...qT(),inputUncached:Ue(m.inputTokens),cacheRead:Ue(m.cacheReadTokens),output:Ue(m.outputTokens),reasoning:Ue(m.reasoningTokens),modelReported:Fr(d.message?.source?.model),invalidCounters:o||[m.inputTokens,m.cacheReadTokens,m.outputTokens].some(p=>Ue(p)===null)||hn([m.inputTokens,m.cacheReadTokens,m.outputTokens,m.reasoningTokens])||Ue(m.reasoningTokens)!==null&&Ue(m.outputTokens)!==null&&m.reasoningTokens>m.outputTokens})}}lastUsage(){let e=[...this.parts.values()].at(-1);return e?{...e}:void 0}usage(){let e=XT([...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 kj}from"node:child_process";import{randomBytes as Rj}from"node:crypto";import{realpath as Mc}from"node:fs/promises";function Qo(){let t=Rj(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 Pc(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]:[]];qe("muse",n,t.permissionMode??"yolo");let r=kj(t.progPath??"muse",n,{cwd:t.cwd,env:je(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=VE(),g=Date.now(),h=t.sessionId;r.stderr.setEncoding("utf8"),r.stderr.on("data",w=>{f.append(w)});let y=(w,S,R)=>{if(s===w){if(s=void 0,w.id&&o.add(w.id),S){let x=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(S,{usage:x?{...x,outcome:w.outcome}:void 0,sessionId:h})}else R&&(R.usage=w.usage.usage());w.cleanup(),w.drained(),w.settled||(w.settled=!0,S?w.reject(S):(p++,w.resolve(R)))}},b=w=>{a||(a=w,s&&y(s,a),v.close(a),!m&&!c&&ye(r,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{}))},_=(w,S)=>{let R=S.params;if(!R||R.sessionId!==h)return;let x=S.method;if(x==="view/gap"||x==="session/closed"){b(new Error(`Muse ${x}: the conversation cannot continue without reopening`));return}if(x==="turn/unqueued"&&R.turnId===w.id){w.outcome="cancelled",y(w,new Ts("Muse queued turn cancelled","external"));return}x==="turn/started"&&R.turnId===w.id&&(w.queued=!1);let A=R.item,M=R.turnId??A?.turnId;if(M&&M!==w.id||x==="session/tokenUsage"&&(w.settled||R.turnId!==w.id||!w.usage.event(R,w.id)))return;w.opts.onEvent?.(S);let P={kind:"other",raw:S};if(["item/started","item/updated","item/completed"].includes(x)&&A?.turnId===w.id&&typeof A.itemId=="string"){let F=w.items.get(A.itemId);if(F&&typeof A.revision=="number"&&A.revision<=F.revision)return;w.items.set(A.itemId,{...A}),(A.kind==="toolCall"||A.kind==="userShell")&&x!=="item/updated"?P={kind:x==="item/completed"?"tool_result":"tool_use",id:A.itemId,tool:A.tool??A.kind,summary:A.failureReason??A.fallbackText,...x==="item/completed"?{status:A.status==="completed"?"ok":"error"}:{},...A.durationMs!==void 0?{elapsedMs:A.durationMs}:{},raw:S}:A.kind==="reasoning"?P={kind:"thinking",raw:S}:A.kind==="agentMessage"&&(P={kind:"text",raw:S})}else if(x==="item/delta"&&typeof R.itemId=="string"&&typeof R.delta=="string"){let F=w.items.get(R.itemId);if(!F)return;F.kind==="agentMessage"&&(R.field===void 0||R.field==="text")?(F.text=(F.text??"")+R.delta,w.cancelled||w.opts.onDelta?.(R.delta),P={kind:"text",raw:S}):F.kind==="reasoning"&&(P={kind:"thinking",raw:S})}if(w.cancelled||w.opts.onProgress?.(P),x!=="turn/completed"||R.turnId!==w.id)return;if(!["completed","failed","cancelled"].includes(R.terminal)){b(new Error(`Muse returned an unknown turn terminal: ${String(R.terminal)}`));return}if(w.cancelled||R.terminal==="cancelled"){w.outcome="cancelled",y(w,new Ts("Muse turn cancelled",w.cancelled?"external":"provider"));return}if(R.terminal!=="completed"){w.outcome="error",y(w,new Error(R.error?.message??R.reason??`Muse turn ended with ${String(R.terminal)}`));return}let U=[...w.items.values()].filter(F=>F.kind==="agentMessage");y(w,void 0,{text:U.map(F=>typeof F.text=="string"?F.text:"").join(`
|
|
2249
|
+
`),sessionId:h,durationMs:typeof R.durationMs=="number"?R.durationMs:Date.now()-w.started,stopReason:R.terminal,...U.some(F=>F.truncated)?{warnings:["Muse reported a truncated response; inspect the native transcript for complete content"]}:{}})},v=Pr(r,{provider:"muse",protocol:"msp",onProtocolError:b,onNotification:w=>{if(g=Date.now(),w.method==="view/gap"||w.method==="session/closed"){w.params?.sessionId===h&&!c&&b(new Error(`Muse ${w.method}: session must be reopened`));return}let S=s;S&&(S.id?_(S,w):S.events.push(w))}}),E=async(w,S,R=Qo())=>(await v.sendRpc(w,{...S,commandId:R})).result,I=w=>{!w.id||w.interruptSent||s!==w||(w.interruptSent=!0,E("turn/interrupt",{sessionId:h,turnId:w.id}).catch(S=>{s===w&&b(S instanceof Error?S:new Error(String(S)))}))},T=w=>{!w.id||w.unqueueSent||s!==w||(w.unqueueSent=!0,E("turn/unqueue",{sessionId:h,turnId:w.id}).catch(S=>{let R=S instanceof Error?S.message:String(S);/already started|not queued|launch boundary|turn is running/i.test(R)?(w.queued=!1,I(w)):s===w&&b(S instanceof Error?S:new Error(R))}))},k=w=>{w.queued?T(w):I(w)};r.on("error",w=>b(new Error(`Unable to start Muse: ${w.message}`)));let N=()=>{c||m||a||d||(d=!0,ye(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,S)=>{m=!0,c?v.close(new Error("Muse session closed")):b(new Error(gi(`Muse exited (${S??w}) after ${p} completed prompt(s)`,f.text().trim()?Ae(f.text(),{provider:"muse"}):""))),s&&y(s,new Error("Muse session closed"))});let C=()=>{if(l)return l;c=!0;let w=!!s;return s&&(s.cancelled=!0,k(s)),l=(async()=>{m||(await new Promise(S=>En(u?t.holdOpen:void 0,{isAborted:()=>w,hasChildExited:()=>m,isTurnInFlight:()=>!!s,lastEventAtMs:()=>g,closeStdin:()=>{r.stdin.end(),S()},label:"muse"})),await ye(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},O=()=>{b(new Error("Aborted")),C()};t.signal?.addEventListener("abort",O,{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 Mc(w.museHome)!==await Mc(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 S=e?"denyUnmatched":"allowAll",x=(t.create?await E("session/start",{sessionId:h,workspaceRoot:t.cwd,approvalMode:S,...t.model?{modelId:t.model}:{}}):await E("session/resume",{sessionId:h,excludeItems:!0}))?.session;if(x?.sessionId!==h)throw new Error(`Muse did not return requested session "${h}"`);if(typeof x.workspaceRoot!="string"||await Mc(x.workspaceRoot)!==await Mc(t.cwd))throw new Error("Muse session belongs to a different working directory");if(x.activeTurnId||x.status!=="idle")throw new Error(`Muse session is not idle (${String(x.status)})`);if((await E("session/setApprovalMode",{sessionId:h,mode:S}))?.effectiveMode?.mode!==S)throw new Error("Muse did not apply the requested approval mode");if(!t.create&&t.model&&x.modelId!==t.model&&(await E("session/setModel",{sessionId:h,model:{modelId:t.model,...x.providerId?{providerId:x.providerId}:{}}}))?.status!=="accepted")throw new Error("Muse did not accept the requested model");u=!0}catch(w){throw await C(),a??w}finally{t.signal?.removeEventListener("abort",O)}return{provider:"muse",sessionId:h,get completedTurns(){return p},close:C,async sendTurn(w,S={}){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(S.signal?.aborted)throw new Error("Aborted");return new Promise((R,x)=>{let A,M=new Promise(F=>{A=F}),P={usage:new Oc(h,i),commandId:Qo(),events:[],items:new Map,opts:S,started:Date.now(),cancelled:!1,interruptSent:!1,unqueueSent:!1,queued:!1,settled:!1,resolve:R,reject:x,drain:M,drained:A,cleanup:()=>{}};s=P;let U=()=>{P.cancelled=!0,P.settled=!0,x(Object.assign(new Error("Aborted"),{usage:P.usage.usage(),sessionId:h})),k(P)};P.cleanup=()=>S.signal?.removeEventListener("abort",U),S.signal?.addEventListener("abort",U,{once:!0}),E("turn/start",{sessionId:h,input:[{type:"text",text:w}],...t.effort?{reasoningEffort:t.effort}:{}},P.commandId).then(F=>{if(s===P){if(F?.commandId!==P.commandId||F.status!=="accepted"||!["started","queued"].includes(F.disposition)||typeof F.turnId!="string"||F.turnId.length===0||o.has(F.turnId)){b(new Error("Muse did not admit a fresh turn; refusing ambiguous dispatch"));return}P.id=F.turnId,P.queued=F.disposition==="queued",P.cancelled&&k(P);for(let ee of P.events)s===P&&_(P,ee);P.events=[]}},F=>{s===P&&y(P,F instanceof Error?F:new Error(String(F)))})})}}}var GT=L(()=>{"use strict";Lc();rt();qp();bs();on();Ho();Tn();sn()});import{join as gf}from"node:path";import{mkdir as Ij}from"node:fs/promises";function hf(t={}){let e=pl(t.museDataHome),n=s=>({...s??process.env,XDG_DATA_HOME:e}),r=async(s,i)=>{if(i.bundleSession)return Kn(i.bundleSession,"muse",i.sessionId,s,i);let o=i.sessionId||Qo(),a=await Pc({...i,sessionId:o,create:i.sessionId==="",env:n(i.env),expectedHome:gf(e,"muse")});try{return await a.sendTurn(s,i)}finally{await a.close()}};return new class extends _e{constructor(){super({provider:new ml({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 Pc({...s,env:n(s.env),expectedHome:gf(e,"muse")})}async seed(s,i){await Ij(s,{recursive:!0});let o=Qo(),a,l;try{a=await Pc({sessionId:o,cwd:s,create:!0,env:n(i?.env),signal:i?.signal,expectedHome:gf(e,"muse"),model:i?.model,effort:i?.effort}),i?.signal?.throwIfAborted();try{i?.onDispatch?.()}catch{}let c=await a.sendTurn(i?.prompt??ce,{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 yf=L(()=>{"use strict";rt();lm();GT();vi();ze()});function VT(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(`
|
|
2250
2250
|
|
|
2251
2251
|
--- additional response (turn ${n+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
2252
2252
|
|
|
2253
|
-
`+t[n]);return e.join("")}function Dc(t={}){let e=[],n="",r=!1,s=t.usageState,i,o=new Set,a=t.resultIds??s?.resultIds??new Set,l=u=>typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null,c=(u,d)=>u===null||d===null?null:u+d;return{processLine(u){if(!u.trim())return;let d;try{d=JSON.parse(u)}catch{return}let m=vf(d,n||s?.sessionId||t.sessionId||"");if(m&&a.has(m))return;m&&a.add(m),t.onEvent?.(d);let p=d.type;if(p==="system"&&d.subtype==="init"&&(n=d.session_id||n,s&&(JT(s,n),typeof d.model=="string"&&(s.model=d.model))),p==="assistant"){let f=d.message;typeof f?.model=="string"&&f.model!=="<synthetic>"&&o.add(f.model);let g=f?.content;if(Array.isArray(g))for(let h of g)h.type==="text"&&h.text&&t.onText?.(h.text)}if(p==="result"&&(r=!0,e.push(d),s)){JT(s,typeof d.session_id=="string"?d.session_id:n);let f=d.usage,g=d.total_cost_usd,h=typeof g=="number"&&Number.isFinite(g)&&g>=0,y=s.cost,b=h&&y!==null&&g>=y?g-y:null;if(s.cost=h?g:null,f&&typeof f=="object"){let _=f.cache_creation,v=l(f.cache_creation_input_tokens),E=Um({cacheWrite5m:_?.ephemeral_5m_input_tokens,cacheWrite1h:_?.ephemeral_1h_input_tokens},v),I=f.output_tokens_details,T={source:"wire",inputUncached:l(f.input_tokens),cacheRead:l(f.cache_read_input_tokens),cacheWrite:l(f.cache_creation_input_tokens),output:l(f.output_tokens),reasoning:l(I?.thinking_tokens),modelReported:null,providerCostUsd:b,reason:b===null?"cumulative_only":null,cacheWrite5m:E?.five??null,cacheWrite1h:E?.one??null,invalidCounters:
|
|
2253
|
+
`+t[n]);return e.join("")}function Dc(t={}){let e=[],n="",r=!1,s=t.usageState,i,o=new Set,a=t.resultIds??s?.resultIds??new Set,l=u=>typeof u=="number"&&Number.isSafeInteger(u)&&u>=0?u:null,c=(u,d)=>u===null||d===null?null:u+d;return{processLine(u){if(!u.trim())return;let d;try{d=JSON.parse(u)}catch{return}let m=vf(d,n||s?.sessionId||t.sessionId||"");if(m&&a.has(m))return;m&&a.add(m),t.onEvent?.(d);let p=d.type;if(p==="system"&&d.subtype==="init"&&(n=d.session_id||n,s&&(JT(s,n),typeof d.model=="string"&&(s.model=d.model))),p==="assistant"){let f=d.message;typeof f?.model=="string"&&f.model!=="<synthetic>"&&o.add(f.model);let g=f?.content;if(Array.isArray(g))for(let h of g)h.type==="text"&&h.text&&t.onText?.(h.text)}if(p==="result"&&(r=!0,e.push(d),s)){JT(s,typeof d.session_id=="string"?d.session_id:n);let f=d.usage,g=d.total_cost_usd,h=typeof g=="number"&&Number.isFinite(g)&&g>=0,y=s.cost,b=h&&y!==null&&g>=y?g-y:null;if(s.cost=h?g:null,f&&typeof f=="object"){let _=f.cache_creation,v=l(f.cache_creation_input_tokens),E=Um({cacheWrite5m:_?.ephemeral_5m_input_tokens,cacheWrite1h:_?.ephemeral_1h_input_tokens},v),I=f.output_tokens_details,T={source:"wire",inputUncached:l(f.input_tokens),cacheRead:l(f.cache_read_input_tokens),cacheWrite:l(f.cache_creation_input_tokens),output:l(f.output_tokens),reasoning:l(I?.thinking_tokens),modelReported:null,providerCostUsd:b,reason:b===null?"cumulative_only":null,cacheWrite5m:E?.five??null,cacheWrite1h:E?.one??null,invalidCounters:hn([f.input_tokens,f.cache_read_input_tokens,f.cache_creation_input_tokens,f.output_tokens,I?.thinking_tokens])};if([T.inputUncached,T.cacheRead,T.cacheWrite,T.output].includes(null)&&(T.reason="counter_not_exposed"),!i)i=T;else{for(let k of["inputUncached","cacheRead","cacheWrite","output","reasoning","cacheWrite5m","cacheWrite1h","providerCostUsd"])i[k]=c(i[k]??null,T[k]??null);i.reason=i.reason||T.reason,i.invalidCounters||=T.invalidCounters}}}},usage(){if(i)return{...i,modelReported:o.size>1?null:[...o][0]??s?.model??null,mixedModels:o.size>1}},sawResult(){return r},finalize(){if(!r)return null;let u=KT(e),d=VT(u.resultTexts);return{result:d,usage:this.usage(),sessionId:u.sessionId||n||t.sessionId||"",durationMs:u.durationMs,numTurns:u.numTurns,isError:u.isError&&d.trim().length===0,errorMessage:u.errorMessage}}}}function KT(t){let e=[],n=0,r=0,s="",i=!1,o;for(let a of t){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(n+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(r=c);let u=a.session_id;if(typeof u=="string"&&u&&(s=u),a.is_error===!0){i=!0;let d=a.errors,m=Array.isArray(d)?d.filter(f=>typeof f=="string").join("; "):void 0,p=typeof a.subtype=="string"?a.subtype:"unknown";o=m&&m.length>0?m:`result subtype=${p} (no error detail provided)`}}return{resultTexts:e,durationMs:n,numTurns:r,sessionId:s,isError:i,errorMessage:o}}function _f(t){return{cost:t?null:0,model:null,sessionId:null,resultIds:new Set}}function JT(t,e){e&&(t.sessionId!==null&&t.sessionId!==e&&(t.cost=null,t.model=null),t.sessionId=e)}function vf(t,e=""){return t.type==="result"&&typeof t.uuid=="string"&&t.uuid.length>0?JSON.stringify([typeof t.session_id=="string"?t.session_id:e,t.uuid]):null}var bf=L(()=>{"use strict";vo();wo()});import{spawn as YT}from"node:child_process";import{existsSync as QT}from"node:fs";import{join as Fc}from"node:path";import{readdir as xj}from"node:fs/promises";function ZT(){let t=process.env.LMCTL_RESULT_GRACE_TIMEOUT_MS;if(t===void 0||t.trim().length===0)return 72e5;let e=Number(t);return Number.isFinite(e)&&e>0?e:72e5}function eS(){let t=process.env.LMCTL_TOOL_USE_GRACE_TIMEOUT_MS;if(t===void 0||t.trim().length===0)return 27e5;let e=Number(t);return Number.isFinite(e)&&e>0?e:27e5}function tS(t){let n=t.message?.content;return Array.isArray(n)?n.some(r=>r?.type==="tool_use"):!1}function Cj(t){let e=t.stderr.trim(),n=t.signal?`terminated by ${t.signal}`:`exited with code ${t.exitCode}`,r=`lmctl: ${t.tool} ${n} before returning a final result event.
|
|
2254
2254
|
One possible cause: the provider stream ended before a complete response was delivered; for Claude Code this can appear as "API Error: Stream idle timeout - partial response received".`;return e?`Original provider error:
|
|
2255
2255
|
${Ae(e,{provider:t.tool})}
|
|
2256
2256
|
|
|
2257
|
-
${r}`:r}function nS(t){let e=t.tool||"claude",n=t.binaryPath||Aj[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=Mr(e,s)??Nj[e]??["--dangerously-skip-permissions"];if(r.push(...i),qe(e,r,s),t.cwd&&!QT(t.cwd))throw X({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new xe(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=je(t.env,t.cwd,t.sessionId);return{tool:e,binary:n,args:r,spawnEnv:e==="claude"?aT(o):o}}function rS(t,e){return new Promise((n,r)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=nS(e))}catch(q){return r(q instanceof Error?q:new Error(String(q)))}let c=YT(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",q=>{Je(`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"}),ye(c).catch(()=>{}),r(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,X({event:"transport_abort",provider:i}),ye(c).catch(()=>{}),r(Object.assign(new Error("Aborted"),{usage:M.usage()}))},{once:!0})}let d="",m=!1,p=!1,f=0,g=!1,h="",y="",b,_,v=null,E=null,I=!1,T=!1,k=ZT(),N=eS();function C(){b!==void 0&&(clearTimeout(b),b=void 0)}function O(){_!==void 0&&(clearTimeout(_),_=void 0)}let w=null;function S(){return m||u||M.sawResult()}function R(q){return q==="text_done"?k:N}async function x(q){if(q==="text_done"?b=void 0:_=void 0,S()||v!==null)return;w??=Date.now();let Y=R(q);if(e.holdOpen){let ae=(e.holdOpen.maxHoldMs??bc)-(Date.now()-w),Xe=ae>0?await wc(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),ae,e.signal):!1;if(S()||(q==="text_done"?b!==void 0:_!==void 0))return;if(Xe===!0){X({event:"transport_stall_grace_deferred",provider:i,grace_kind:q,grace_ms:Y,reason:"outstanding_dispatched_work"}),A(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}),ye(c).catch(()=>{})}function A(q){let Y=setTimeout(()=>{x(q)},R(q));Y.unref?.(),q==="text_done"?(C(),b=Y):(O(),_=Y)}let M=Dc({usageState:i==="claude"?_f(!!e.sessionId):void 0,onEvent:q=>{f=Date.now(),g=q.type!=="result",q.type==="system"&&q.subtype==="init"&&(y=q.session_id||y),q.type==="assistant"?(I=!tS(q),T=I&&q.message?.stop_reason==="pause_turn"):(q.type==="result"||q.type==="user")&&(I=!1,T=!1),C(),i==="claude"&&I&&!T&&!M.sawResult()&&A("text_done"),O(),i==="claude"&&!M.sawResult()&&A("tool_use_silence"),e.onEvent?.(q)},onText:q=>{h+=q,e.onText?.(q)}});function P(){p||(p=!0,
|
|
2257
|
+
${r}`:r}function nS(t){let e=t.tool||"claude",n=t.binaryPath||Aj[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=Mr(e,s)??Nj[e]??["--dangerously-skip-permissions"];if(r.push(...i),qe(e,r,s),t.cwd&&!QT(t.cwd))throw X({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new xe(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=je(t.env,t.cwd,t.sessionId);return{tool:e,binary:n,args:r,spawnEnv:e==="claude"?aT(o):o}}function rS(t,e){return new Promise((n,r)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=nS(e))}catch(q){return r(q instanceof Error?q:new Error(String(q)))}let c=YT(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",q=>{Je(`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"}),ye(c).catch(()=>{}),r(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,X({event:"transport_abort",provider:i}),ye(c).catch(()=>{}),r(Object.assign(new Error("Aborted"),{usage:M.usage()}))},{once:!0})}let d="",m=!1,p=!1,f=0,g=!1,h="",y="",b,_,v=null,E=null,I=!1,T=!1,k=ZT(),N=eS();function C(){b!==void 0&&(clearTimeout(b),b=void 0)}function O(){_!==void 0&&(clearTimeout(_),_=void 0)}let w=null;function S(){return m||u||M.sawResult()}function R(q){return q==="text_done"?k:N}async function x(q){if(q==="text_done"?b=void 0:_=void 0,S()||v!==null)return;w??=Date.now();let Y=R(q);if(e.holdOpen){let ae=(e.holdOpen.maxHoldMs??bc)-(Date.now()-w),Xe=ae>0?await wc(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),ae,e.signal):!1;if(S()||(q==="text_done"?b!==void 0:_!==void 0))return;if(Xe===!0){X({event:"transport_stall_grace_deferred",provider:i,grace_kind:q,grace_ms:Y,reason:"outstanding_dispatched_work"}),A(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}),ye(c).catch(()=>{})}function A(q){let Y=setTimeout(()=>{x(q)},R(q));Y.unref?.(),q==="text_done"?(C(),b=Y):(O(),_=Y)}let M=Dc({usageState:i==="claude"?_f(!!e.sessionId):void 0,onEvent:q=>{f=Date.now(),g=q.type!=="result",q.type==="system"&&q.subtype==="init"&&(y=q.session_id||y),q.type==="assistant"?(I=!tS(q),T=I&&q.message?.stop_reason==="pause_turn"):(q.type==="result"||q.type==="user")&&(I=!1,T=!1),C(),i==="claude"&&I&&!T&&!M.sawResult()&&A("text_done"),O(),i==="claude"&&!M.sawResult()&&A("tool_use_silence"),e.onEvent?.(q)},onText:q=>{h+=q,e.onText?.(q)}});function P(){p||(p=!0,En(e.holdOpen,{isAborted:()=>u,hasChildExited:()=>m,isTurnInFlight:()=>g,lastEventAtMs:()=>f,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function U(q){let Y=M.sawResult();M.processLine(q);let te=M.usage();te&&e.onUsage?.(te),!Y&&M.sawResult()&&P()}c.stdout?.on("data",q=>{d+=q.toString();let Y=d.split(`
|
|
2258
2258
|
`);d=Y.pop()||"";for(let te of Y)U(te)});let F="";c.stderr?.on("data",q=>{F+=q.toString()}),c.on("error",q=>{X({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:q.message}),r(new xe(`Failed to spawn ${o}: ${q.message}`,{cause:q}))}),c.on("exit",(q,Y)=>{if(m=!0,C(),O(),u)return;d.trim()&&U(d);let te=M.finalize();if(te?.isError)X({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:te.errorMessage}),r(Object.assign(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${te.errorMessage??"unknown error"}`),{usage:te.usage,sessionId:te.sessionId}));else if(te)Je(`stream-json: result ${te.result.slice(0,80)}${te.result.length>80?"...":""} (${te.durationMs}ms)`),n({result:te.result,sessionId:te.sessionId,durationMs:te.durationMs,numTurns:te.numTurns,usage:te.usage,exitCode:q});else if(v!==null&&E==="text_done"&&h.trim().length>0)X({event:"transport_stall_finalized",provider:i,reason:v,text_len:h.length}),n({result:h,sessionId:y||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:q,warnings:[v]});else if(v!==null&&E==="tool_use_silence"){let ae=F.trim()?`
|
|
2259
2259
|
${Ae(F,{provider:i})}`:"",Xe=`${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})`:"")+ae;X({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:q,signal:Y,stderr_summary:Xe}),r(new Pe(Xe,q,Y,F))}else{let ae=v!==null?`${v} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:"")+(F.trim()?`
|
|
2260
2260
|
${Ae(F,{provider:i})}`:""):Cj({tool:i,exitCode:q,signal:Y,stderr:F});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:ae}),r(new Pe(ae,q,Y,F))}});let ee=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(ee+`
|
|
@@ -2262,7 +2262,7 @@ ${Ae(F,{provider:i})}`:""):Cj({tool:i,exitCode:q,signal:Y,stderr:F});X({event:"t
|
|
|
2262
2262
|
`);te=W.pop()||"";for(let oe of W)Wt(oe)}),i.on("error",B=>{if(d=new xe(`Failed to spawn ${n}: ${B.message}`,{cause:B}),X({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:B.message}),Y(d),k!==null){let W=k;k=null,a.turnActive=!1,W.reject(d)}}),i.on("exit",(B,W)=>{a.exited=!0,a.exitCode=B,a.signal=W,w(),S(),te.trim()&&Wt(te),Y(a.exited&&!P?new Pe(`stream-json bundle: ${e} ${W?`terminated by ${W}`:`exited (code ${String(B)})`} before its init event`,B,W):void 0);let oe=k;if(oe!==null&&(k=null,a.turnActive=!1,!oe.aborted))if(y!==null&&b==="text_done"&&p.trim().length>0)X({event:"transport_stall_finalized",provider:e,reason:y,text_len:p.length}),oe.resolve({result:p,sessionId:f||t.sessionId||"",durationMs:Date.now()-oe.startMs,numTurns:1,warnings:[y]});else if(y!==null&&b==="tool_use_silence"){let ve=m.trim()?Ae(m,{provider:e}):"";X({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:B,signal:W,...ve?{stderr_summary:ve}:{}}),oe.reject(new Pe(`${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})`:"")+(ve?`
|
|
2263
2263
|
${ve}`:""),B,W,m))}else{let ve=O(),gt=m.trim()?Ae(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,...gt?{stderr_summary:gt}:{}}),oe.reject(new Pe(gt?`${ve.message}
|
|
2264
2264
|
${gt}`:ve.message,B,W,m))}for(let ve of N.splice(0))ve()});try{t.sessionId&&await zT(e,t.sessionId,t.sessionFileRoots),await ee}catch(B){let W=d??(B instanceof Error?B:new Error(String(B))),oe=t.closeTimeoutMs??2e3;throw await ye(i,{softDelayMs:Math.min(1e3,oe),killDelayMs:Math.min(1e3,oe)}).catch(()=>{}),W}let Fe=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 O();if(k!==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 oe=()=>(a.closed=!0,ye(i).catch(()=>{}),new Error("Aborted"));if(W.signal?.aborted)throw oe();if(t.sessionId&&(await zT(e,t.sessionId,t.sessionFileRoots),a.exited))throw O();if(W.signal?.aborted)throw oe();return p="",g=!1,h=!1,y=null,b=null,_=null,new Promise((ve,gt)=>{let Vr=Dc({usageState:c,resultIds:u,sessionId:f||l,onText:ke=>{p+=ke,W.onText?.(ke)}}),Ms={processor:Vr,resolve:ve,reject:gt,startMs:Date.now(),aborted:!1,onEventForward:W.onEvent};k=Ms,a.turnActive=!0;let $=()=>{Ms.aborted=!0,X({event:"transport_abort",provider:e}),a.closed=!0,ye(i).catch(()=>{}),k===Ms&&(k=null,a.turnActive=!1),gt(Object.assign(new Error("Aborted"),{usage:Vr.usage()}))};W.signal?.addEventListener("abort",$,{once:!0});let K=JSON.stringify({type:"user",message:{role:"user",content:B}});i.stdin?.write(`${K}
|
|
2265
|
-
`),Je(`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=>{
|
|
2265
|
+
`),Je(`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=>{En(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??2e3;await Promise.race([C(),Fe(B)]),a.exited||await ye(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,B),killDelayMs:Math.min(1e3,B)}).catch(()=>{})}})()),a.closing}}}var Aj,Nj,wf=L(()=>{"use strict";Lr();bs();Tn();Se();Ho();on();bf();We();sn();bf();Aj={claude:"claude",qwen:"qwen"};Nj={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function $c(t={}){return[]}var Ef=L(()=>{"use strict"});function Tf(t){return t==="plan"?"read-only":"danger-full-access"}function iS(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function jc(){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 Uc(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function oS(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 Hc(){return{pendingCodexError:null}}function Bc(t,e){let n=oS(t);return n.willRetry||(e.pendingCodexError=n.turnError),n}function Wc(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 Sf=L(()=>{"use strict"});import{spawn as aS}from"node:child_process";import{createInterface as lS}from"node:readline";import{existsSync as Lj,readFileSync as Mj}from"node:fs";import{fileURLToPath as Pj}from"node:url";function cS(){return iS(Dj)}function $r(t,e){Je(`[codex:${t}] ${JSON.stringify(e)}`)}function Fj(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.
|
|
2266
2266
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
2267
2267
|
${Ae(e,{provider:"codex"})}
|
|
2268
2268
|
|
|
@@ -2272,42 +2272,42 @@ ${n}`:n}function uS(t){let e=t.binaryPath||"codex",n=["app-server","--listen","s
|
|
|
2272
2272
|
`),X({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:C instanceof Error?C.message:String(C)});let w=(await I("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;w?.id&&(g=w.id,e.onSessionId?.(g))}else{let O=(await I("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;O?.id&&(g=O.id,e.onSessionId?.(g))}c=l.turn(g),await I("turn/start",{threadId:g,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(C){ye(a).catch(()=>{}),r(C instanceof Error?C:new Error(String(C)))}})()})}async function pS(t){let{binary:e,codexArgs:n,sandbox:r}=uS(t),s=aS(e,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:je(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=uf(),c=null,u="";s.stderr?.on("data",O=>{u+=O.toString()});let d=lS({input:s.stdout}),m=new Map,p=1;function f(O,w={}){return new Promise((S,R)=>{let x=p++;m.set(x,{resolve:S,reject:R});let A=JSON.stringify({jsonrpc:"2.0",id:x,method:O,params:w});s.stdin?.write(A+`
|
|
2273
2273
|
`)})}function g(O,w={}){let S=JSON.stringify({jsonrpc:"2.0",method:O,params:w});s.stdin?.write(S+`
|
|
2274
2274
|
`)}let h=[],y=()=>o.exited?Promise.resolve():new Promise(O=>{h.push(O)}),b=()=>new Pe(`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,I,T=O=>{O.turnId&&f("turn/interrupt",{threadId:a,turnId:O.turnId}).catch(()=>{})};function k(O){let w=_;w===null||w.settled||(w.settled=!0,_=null,w.usage.finish(),O&&w.reject(Object.assign(O,{usage:w.usage.usage(),sessionId:a})))}d.on("line",O=>{let w;try{w=JSON.parse(O)}catch{return}if(typeof w.id=="number"&&m.has(w.id)){dS(l,w);let P=m.get(w.id);if(m.delete(w.id),w.error){let U=w.error,F=typeof U?.message=="string"&&U.message.length>0?U.message:JSON.stringify(w.error);P.reject(Uo(`codex app-server error: ${F}`,U))}else P.resolve(w);_?.onEvent?.(w);return}let S=w.method;if(!S){_?.onEvent?.(w);return}if(S==="thread/started"){let U=w.params?.thread;U?.id&&(a=U.id,t.onSessionId?.(a))}let R=w.params,x=R?.turnId??R?.turn?.id;if(v&&(S==="turn/started"&&!v.turnId&&x&&(v.usage.bind(x),v.usage.finish(),v.turnId=x,T(v)),S==="turn/completed"&&x===v.turnId&&(l.remember(a,x),v=null,I?.()),S.startsWith("turn/")||S.startsWith("item/")||S==="error"))return;let A=_;if(x&&A?.turnId&&x!==A.turnId||A!==null&&!A.usage.event(w))return;let M=A?.usage.usage();if(M&&A?.onUsage?.(M),S==="turn/started"&&A!==null){let U=w.params?.turn;U?.id&&(A.turnId=U.id),wi(w,A.agentState,A.onDelta,void 0)}if(A!==null&&(S==="item/started"||S==="item/agentMessage/delta"||S==="item/completed")&&wi(w,A.agentState,A.onDelta,void 0),S==="turn/completed"&&A!==null&&!A.settled){Uc(A.agentState);let P=Wc(w,A.turnState);A.settled=!0,A.usage.finish(),_=null,P.shouldReject?A.reject(Object.assign(P.turnError,{usage:A.usage.usage(),sessionId:a})):(o.completedTurns+=1,A.resolve({text:A.agentState.resultText,usage:A.usage.usage(),sessionId:a,turnId:A.turnId,durationMs:Date.now()-A.startMs}))}S==="error"&&A!==null&&Bc(w,A.turnState),A?.onEvent?.(w)});let N=O=>{c=new xe(`Failed to spawn codex app-server: ${O.message}`,{cause:O}),X({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:O.message});for(let w of m.values())w.reject(c);m.clear(),k(c)};s.on("error",N),s.stdin?.on("error",N),s.on("exit",(O,w)=>{o.exited=!0,I?.(),o.exitCode=O,o.signal=w;let S=b();for(let x of m.values())x.reject(S);m.clear();let R=_;if(R!==null&&!R.settled)if(R.settled=!0,R.usage.finish(),_=null,R.turnState.pendingCodexError)R.reject(Object.assign(R.turnState.pendingCodexError,{usage:R.usage.usage(),sessionId:a}));else{let x=u.trim()?Ae(u,{provider:"codex"}):"";X({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:O,signal:w,...x?{stderr_summary:x}:{}}),R.reject(Object.assign(new Pe(x?`${S.message}
|
|
2275
|
-
${x}`:S.message,O,w,u),{usage:R.usage.usage(),sessionId:a}))}for(let x of h.splice(0))x()});try{if(await f("initialize",cS()),g("initialized",{}),t.threadId){let O;try{O=await f("thread/resume",{threadId:t.threadId,sandbox:r,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(S){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${S instanceof Error?S.message:String(S)} (the thread/start fallback is disabled in bundle mode)`)}let w=O.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(O){let w=c??(O instanceof Error?O:new Error(String(O))),S=t.closeTimeoutMs??2e3;throw await ye(s,{softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{}),w}let C=O=>new Promise(w=>{setTimeout(w,O).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(O,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((S,R)=>{let x={usage:l.turn(a),onUsage:w.onUsage,agentState:jc(),turnState:Hc(),resolve:S,reject:R,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};_=x;let A=()=>{x.settled||(x.settled=!0,_=null,v=x,E=new Promise(M=>{I=M}),T(x),w.signal?.removeEventListener("abort",A),x.usage.finish(),R(Object.assign(new Error("Aborted"),{usage:x.usage.usage(),sessionId:a})))};w.signal?.addEventListener("abort",A,{once:!0}),f("turn/start",{threadId:a,input:[{type:"text",text:O}],...t.model?{model:t.model}:{}}).then(M=>{x.usage.bind(M.result?.turn?.id)}).catch(M=>{if(x.settled){v===x&&(v=null,I?.());return}x.settled=!0,_=null,w.signal?.removeEventListener("abort",A),x.usage.finish(),R(Object.assign(o.exited?b():M instanceof Error?M:new Error(String(M)),{usage:x.usage.usage(),sessionId:a}))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,I?.(),!o.exited&&(t.holdOpen!==void 0?await new Promise(O=>{
|
|
2275
|
+
${x}`:S.message,O,w,u),{usage:R.usage.usage(),sessionId:a}))}for(let x of h.splice(0))x()});try{if(await f("initialize",cS()),g("initialized",{}),t.threadId){let O;try{O=await f("thread/resume",{threadId:t.threadId,sandbox:r,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(S){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${S instanceof Error?S.message:String(S)} (the thread/start fallback is disabled in bundle mode)`)}let w=O.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(O){let w=c??(O instanceof Error?O:new Error(String(O))),S=t.closeTimeoutMs??2e3;throw await ye(s,{softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{}),w}let C=O=>new Promise(w=>{setTimeout(w,O).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(O,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((S,R)=>{let x={usage:l.turn(a),onUsage:w.onUsage,agentState:jc(),turnState:Hc(),resolve:S,reject:R,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};_=x;let A=()=>{x.settled||(x.settled=!0,_=null,v=x,E=new Promise(M=>{I=M}),T(x),w.signal?.removeEventListener("abort",A),x.usage.finish(),R(Object.assign(new Error("Aborted"),{usage:x.usage.usage(),sessionId:a})))};w.signal?.addEventListener("abort",A,{once:!0}),f("turn/start",{threadId:a,input:[{type:"text",text:O}],...t.model?{model:t.model}:{}}).then(M=>{x.usage.bind(M.result?.turn?.id)}).catch(M=>{if(x.settled){v===x&&(v=null,I?.());return}x.settled=!0,_=null,w.signal?.removeEventListener("abort",A),x.usage.finish(),R(Object.assign(o.exited?b():M instanceof Error?M:new Error(String(M)),{usage:x.usage.usage(),sessionId:a}))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,I?.(),!o.exited&&(t.holdOpen!==void 0?await new Promise(O=>{En(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>_!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),O()},label:"codex"})}):s.stdin?.end(),!o.exited)){let O=t.closeTimeoutMs??2e3;await Promise.race([y(),C(O)]),o.exited||await ye(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,O),killDelayMs:Math.min(1e3,O)}).catch(()=>{})}})()),o.closing}}}var Dj,fS=L(()=>{"use strict";pf();Se();Se();Lr();bs();Ho();Tn();Ef();Se();on();sn();Sf();Sf();Dj=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(Mj(Pj(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});function Ne(t,e=120){let n=t.replace(/\s+/g," ").trim();return n.length>e?n.slice(0,e-1)+"\u2026":n}function gS(t,e){return n=>{if(n.kind==="tool_use"&&typeof n.id=="string"){if(t.size>=$j){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 hS(){let t=new Map;return(e,n)=>{jj(e,gS(t,n))}}function jj(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(Ne(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(Ne(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:Ne(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=Ne(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:Ne(u),id:l,raw:i})}else if(o==="thinking"||o==="redacted_thinking"){let a=i.thinking||i.data||"";e({kind:"thinking",summary:Ne(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(`
|
|
2276
2276
|
`).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(`
|
|
2277
|
-
`).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 qc(t,e){let n=e.binary==="qwen"?"qwen":"claude",r=e.onProgress?hS():void 0;if(e.bundleSession!==void 0)return Kn(e.bundleSession,n,e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let s=await rS(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 Xc(t){let e=t.binary==="qwen"?"qwen":"claude",n=await sS({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,sessionFileRoots:t.sessionFileRoots});return{provider:e,get sessionId(){return n.sessionId},get completedTurns(){return n.completedTurns},async sendTurn(r,s={}){let i=hS(),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 yS(){let t=new Map;return(e,n)=>{Uj(e,gS(t,n))}}function Uj(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:Ne(a)});return}if(i==="agent_thought_chunk"||i==="thought"||i==="reasoning"){let a=s.content?.text||"";e({kind:"thinking",summary:Ne(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=Ne(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:Ne(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 ${Ne(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:i})}}function _S(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function
|
|
2277
|
+
`).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 qc(t,e){let n=e.binary==="qwen"?"qwen":"claude",r=e.onProgress?hS():void 0;if(e.bundleSession!==void 0)return Kn(e.bundleSession,n,e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let s=await rS(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 Xc(t){let e=t.binary==="qwen"?"qwen":"claude",n=await sS({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,sessionFileRoots:t.sessionFileRoots});return{provider:e,get sessionId(){return n.sessionId},get completedTurns(){return n.completedTurns},async sendTurn(r,s={}){let i=hS(),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 yS(){let t=new Map;return(e,n)=>{Uj(e,gS(t,n))}}function Uj(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:Ne(a)});return}if(i==="agent_thought_chunk"||i==="thought"||i==="reasoning"){let a=s.content?.text||"";e({kind:"thinking",summary:Ne(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=Ne(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:Ne(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 ${Ne(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:i})}}function _S(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function an(t,e){let n=e.acpTool||e.binary,r=e.onProgress?yS():void 0;if(e.bundleSession!==void 0)return Kn(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";dt({event:"model_ignored",provider:n,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await LT(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,..._S(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function Sn(t){let e=t.acpTool||t.binary,n=await MT({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});return{provider:e,get sessionId(){return n.sessionId},get completedTurns(){return n.completedTurns},async sendTurn(r,s={}){let i=yS(),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,..._S(o.result,o.sawActivity)?{status:"empty"}:{},...o.warnings!==void 0?{warnings:o.warnings}:{}}},close:()=>n.close()}}function vS(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: ${Ne(o,120)}`}:{kind:"other",summary:`codex error: ${Ne(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:Ne(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:Ne(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:Ne(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:Ne(s)}:{kind:"text",summary:Ne(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:Ne(s)});return}if(n==="item/commandExecution/outputDelta"){let s=(typeof r?.delta=="string"?r.delta:"")||"";if(s){let i=s.split(`
|
|
2278
2278
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${Ne(o,60)}`:Ne(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(n==="item/commandExecution/terminalInteraction"||n==="item/commandExecution/outputChunk"||n==="item/commandExecution/output"){let s=(typeof r?.stdin=="string"?r.stdin:"")||(typeof r?.delta=="string"?r.delta:"")||(typeof r?.output=="string"?r.output:"")||(typeof r?.text=="string"?r.text:"")||(typeof r?.content=="string"?r.content:"")||(typeof r?.chunk=="string"?r.chunk:"")||"";if(s){let i=s.split(`
|
|
2279
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${Ne(o,60)}`:Ne(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(n.startsWith("item/")){e({kind:"other",summary:n.slice(5)});return}}async function bS(t,e){if(e.bundleSession!==void 0)return Kn(e.bundleSession,"codex",e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let n=await mS(t,{threadId:e.sessionId,requireResume:e.requireResume,onSessionId:e.onSessionId,onUsage:e.onUsage,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,alias:e.alias,isLead:e.isLead,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:e.onProgress?r=>vS(r,e.onProgress):void 0,signal:e.signal});return{text:n.result,...n.usage?{usage:n.usage}:{},sessionId:n.threadId,durationMs:n.durationMs}}async function wS(t){let e=await pS({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(n,r={}){let s=await e.sendTurn(n,{...r,onEvent:i=>{r.onEvent?.(i),r.onProgress&&vS(i,r.onProgress)}});return{text:s.text,...s.usage?{usage:s.usage}:{},sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var $j,Yn=L(()=>{"use strict";wf();wf();fS();rf();vi();Se();$j=256});function kf(t={}){let e=hl(t.miniplayerHome),n=r=>({...r??process.env,MINIPLAYER_HOME:e});return new class extends _e{constructor(){super({provider:new gl({miniplayerHome:e}),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeSession:!
|
|
2280
|
-
`):"";v&&!/^<(?:command-name>|local-command-|task-notification>\s*<)/u.test(v.trimStart())&&!/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(v.trim())&&!v.trimStart().startsWith("lmctl seed initial connection only.")&&g.push(v)}if(typeof _=="string"){let v=_.trim();if(v.includes("<command-name>")||v.includes("<local-command-")||/^<task-notification>\s*</u.test(v)||v.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(v))continue;u||(u=z(_.trim(),80)),d=z(_.trim(),80),f=void 0,s.push({role:"user",timestamp:b,content:Te(_.trim())})}else if(Array.isArray(_)){for(let v of _)if(v.type==="tool_result"){let E=typeof v.content=="string"?Te(v.content):JSON.stringify(v.content);s.push({role:"tool_result",timestamp:b,content:E,toolCallId:v.tool_use_id})}}}if(y.type==="assistant"&&y.message){y.message.stop_reason===null||y.message.stop_reason==="tool_use"?f="in_progress":typeof y.message.stop_reason=="string"&&(f="complete"),y.message.model&&(l=y.message.model);let b=new Date(y.timestamp||0),_=y.message.content;if(Array.isArray(_))for(let v of _)v.type==="text"&&v.text?s.push({role:"assistant",timestamp:b,content:Te(v.text),model:y.message.model,...typeof y.message.stop_reason=="string"?{stopReason:y.message.stop_reason}:{}}):v.type==="tool_use"?s.push({role:"tool_use",timestamp:b,content:v.name||"unknown tool",toolName:v.name,toolInput:JSON.stringify(v.input,null,2),toolInputData:v.input,toolCallId:v.id,model:y.message.model,...typeof y.message.stop_reason=="string"?{stopReason:y.message.stop_reason}:{}}):v.type==="thinking"&&v.thinking&&s.push({role:"thinking",timestamp:b,content:v.thinking})}}if(!i)return null;Jj(s);let h=await SS(n);return{provider:"claude",sessionId:p,slug:o,cwd:i,createdAt:m||r.createdAt,modifiedAt:r.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:f,firstUserMessage:u,lastUserMessage:d,messageCount:h.messageCount,filePath:n,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:h.totalCacheWriteInputTokens||void 0,totalCacheWrite5mInputTokens:h.totalCacheWrite5mInputTokens||void 0,totalCacheWrite1hInputTokens:h.totalCacheWrite1hInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:s,userPrompts:g}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await Hj(n),!0):!1}async resolveSessionFile(e){let n;try{n=await Gc(this.projectsDir)}catch{return null}let r=[];for(let o of n){let a=Ei(this.projectsDir,o);if(!(await ES(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await Gc(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=TS(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&r.push({filePath:Ei(a,u),fileSessionId:d})}}let s=r.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=r.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of r){let a=await Mt(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{join as RS}from"node:path";function xf(t){return new If(t)}var If,Af=L(()=>{"use strict";kS();rt();We();Yn();
|
|
2279
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${Ne(o,60)}`:Ne(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(n.startsWith("item/")){e({kind:"other",summary:n.slice(5)});return}}async function bS(t,e){if(e.bundleSession!==void 0)return Kn(e.bundleSession,"codex",e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let n=await mS(t,{threadId:e.sessionId,requireResume:e.requireResume,onSessionId:e.onSessionId,onUsage:e.onUsage,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,alias:e.alias,isLead:e.isLead,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:e.onProgress?r=>vS(r,e.onProgress):void 0,signal:e.signal});return{text:n.result,...n.usage?{usage:n.usage}:{},sessionId:n.threadId,durationMs:n.durationMs}}async function wS(t){let e=await pS({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(n,r={}){let s=await e.sendTurn(n,{...r,onEvent:i=>{r.onEvent?.(i),r.onProgress&&vS(i,r.onProgress)}});return{text:s.text,...s.usage?{usage:s.usage}:{},sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var $j,Yn=L(()=>{"use strict";wf();wf();fS();rf();vi();Se();$j=256});function kf(t={}){let e=hl(t.miniplayerHome),n=r=>({...r??process.env,MINIPLAYER_HOME:e});return new class extends _e{constructor(){super({provider:new gl({miniplayerHome:e}),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeSession:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none",leaderSetupHint:"Miniplayer provides native file, shell and web tools. A stored session can be resumed (history is rebuilt from its completed turns)."},binary:"miniplayer",seedArgs:[],resumeTemplate:"",startTemplate:"miniplayer run",transport:(r,s)=>an(r,{...s,env:n(s.env),acpTool:"miniplayer"})})}openSession(r){return Sn({...r,env:n(r.env),binary:"miniplayer",acpTool:"miniplayer"})}manualSeedHint(){return{launchCommand:"miniplayer --help",postLaunchNote:'Use lmctl prompt --provider miniplayer --model <model> "<prompt>". Each invocation creates a fresh run unless a session id is given.',lsCommand:"lmctl ls --provider miniplayer"}}resumeCommand(){throw new Error("miniplayer has no interactive terminal; use lmctl prompt or lmctl batch")}async seed(r,s){try{s?.signal?.throwIfAborted();try{s?.onDispatch?.()}catch{}let i=await an(s?.prompt??ce,{binary:"miniplayer",acpTool:"miniplayer",sessionId:"",requireResume:!1,cwd:r,env:n(s?.env),signal:s?.signal,model:s?.model});return{success:!0,sessionId:i.sessionId,usage:i.usage}}catch(i){return{success:!1,usage:i?.usage,error:`miniplayer seed failed: ${i instanceof Error?i.message:String(i)}`}}}}}var Rf=L(()=>{"use strict";rt();_l();Yn();ze()});import{readdir as Gc,stat as ES,unlink as Hj}from"node:fs/promises";import{join as Ei,basename as TS}from"node:path";function Bj(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function Wj(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return Te(e.trim());if(e!==void 0)return JSON.stringify(e,null,2)}return t.type==="progress"&&t.data!==void 0?JSON.stringify(t.data,null,2):JSON.stringify(t,null,2)}function qj(t,e){t.input=Math.max(t.input,e.input),t.cacheRead=Math.max(t.cacheRead,e.cacheRead),t.cacheWrite=Math.max(t.cacheWrite,e.cacheWrite),t.output=Math.max(t.output,e.output),t.cacheWriteSplitExposed||=e.cacheWriteSplitExposed,e.cacheWrite5m!==void 0&&(t.cacheWrite5m=Math.max(t.cacheWrite5m??0,e.cacheWrite5m)),e.cacheWrite1h!==void 0&&(t.cacheWrite1h=Math.max(t.cacheWrite1h??0,e.cacheWrite1h))}function Xj(t){let e=t?.cache_creation?.ephemeral_5m_input_tokens,n=t?.cache_creation?.ephemeral_1h_input_tokens,r=typeof e=="number"||typeof n=="number",s=(e??0)+(n??0);return{input:t?.input_tokens??0,cacheRead:t?.cache_read_input_tokens??0,cacheWrite:Math.max(t?.cache_creation_input_tokens??0,s),...typeof e=="number"?{cacheWrite5m:e}:{},...typeof n=="number"?{cacheWrite1h:n}:{},cacheWriteSplitExposed:r,output:t?.output_tokens??0}}function Gj(t){let e=t.cacheWrite1h??0;if(!t.cacheWriteSplitExposed)return{total:t.cacheWrite,fiveMinute:t.cacheWrite,oneHour:0};let n=t.cacheWrite5m??Math.max(0,t.cacheWrite-e),r=n+e;return{total:Math.max(t.cacheWrite,r),fiveMinute:r>t.cacheWrite?n:n+(t.cacheWrite-r),oneHour:e}}async function SS(t){let e=0,n=0,r=0,s=0,i=0,o=0,a,l,c=new Map,u=[];for await(let f of Ie(t))if(!f.isSidechain){if(f.type==="user"&&!f.isMeta&&f.message){let g=f.message.content;if(typeof g=="string"){if(g.includes("<command-name>")||g.includes("<local-command-"))continue;e++,l=z(g.trim(),80)}}else if(f.type==="assistant"&&f.message){let g=f.message.content;if(Array.isArray(g))for(let y of g)y.type==="text"&&e++;let h=f.message.usage;if(h){let y=Xj(h),b=f.message.id?.trim();if(b){let v=c.get(b);v?qj(v,y):c.set(b,y)}else u.push(y);let _=y.input+y.cacheWrite+y.cacheRead;_&&(o=_),a={inputTokens:y.input,cacheWriteInputTokens:y.cacheWrite,cachedInputTokens:y.cacheRead,outputTokens:y.output}}}}let d=0,m=0,p=f=>{let g=Gj(f);n+=f.input+f.cacheRead+g.total,r+=f.cacheRead,s+=g.total,d+=g.fiveMinute,m+=g.oneHour,i+=f.output};for(let f of c.values())p(f);for(let f of u)p(f);return{messageCount:e,totalInputTokens:n,totalCacheReadInputTokens:r,totalCacheWriteInputTokens:s,totalCacheWrite5mInputTokens:d,totalCacheWrite1hInputTokens:m,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function Jj(t){let e=Vj(t),n=new Set;for(let r of t){if(r.role!=="tool_use"||r.toolName!=="Bash"||r.toolInputData?.run_in_background!==!0||r.toolCallId===void 0)continue;let s=e.get(r.toolCallId);if(s===void 0)continue;let i=s.content.match(/Command running in background with ID:\s*([A-Za-z0-9_-]+)/)?.[1];i!==void 0&&(n.add(i),r.backgroundTaskId=i,s.backgroundTaskId=i)}for(let r of t){if(r.role!=="tool_use"||r.toolName!=="TaskOutput"&&r.toolName!=="TaskStop"||r.toolCallId===void 0)continue;let s=r.toolInputData?.task_id;if(typeof s!="string"||!n.has(s))continue;r.backgroundTaskId=s;let i=e.get(r.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function Vj(t){let e=new Map;for(let n of t)n.role==="tool_result"&&n.toolCallId!==void 0&&e.set(n.toolCallId,n);return e}var Jc,kS=L(()=>{"use strict";We();Jc=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Ei(ie,".claude"),this.projectsDir=Ei(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],n;try{n=await Gc(this.projectsDir)}catch{return e}for(let r of n){let s=Ei(this.projectsDir,r);if(!(await ES(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Gc(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=TS(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Ei(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,n){let r=await Mt(e,50),s=await De(e),i="",o,a,l,c,u,d;for(let p of r)if(!Bj(p.type)&&(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!d&&p.timestamp&&(d=new Date(p.timestamp)),p.type==="assistant"&&p.message?.model&&(l=p.message.model),p.type==="user"&&!p.isMeta&&p.message)){let f=p.message.content;if(typeof f=="string"){if(f.includes("<command-name>")||f.includes("<local-command-"))continue;c||(c=z(f.trim(),80)),u=z(f.trim(),80)}}if(!i)return null;let m=await SS(e);return{provider:"claude",sessionId:n,slug:o,cwd:i,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:m.lastUserMessage??u,messageCount:m.messageCount,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:m.totalCacheWriteInputTokens||void 0,totalCacheWrite5mInputTokens:m.totalCacheWrite5mInputTokens||void 0,totalCacheWrite1hInputTokens:m.totalCacheWrite1hInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async loadSession(e){let n=await this.resolveSessionFile(e);if(!n)return null;let r=await De(n),s=[],i="",o,a,l,c,u,d,m,p=e,f,g=[];for await(let y of Ie(n))if(y.type!=="file-history-snapshot"&&!y.isSidechain){if(!i&&y.cwd&&(i=y.cwd),!o&&y.slug&&(o=y.slug),!a&&y.version&&(a=y.version),!c&&y.gitBranch&&(c=y.gitBranch),!m&&y.timestamp&&(m=new Date(y.timestamp)),y.sessionId&&(p=y.sessionId),y.type==="system"||y.type==="progress"||y.type==="queue-operation"){s.push({role:"system",timestamp:new Date(y.timestamp||0),content:Wj(y)});continue}if(y.type==="user"&&y.message){if(y.isMeta)continue;let b=new Date(y.timestamp||0),_=y.message.content;if(y.isCompactSummary!==!0&&y.isVisibleInTranscriptOnly!==!0&&y.promptSource!=="system"&&y.toolUseResult===void 0&&y.origin?.kind!=="task-notification"&&y.interruptedMessageId===void 0&&y.interruptedByShutdown!==!0&&y.scheduledTaskId===void 0&&y.scheduledFireId===void 0&&!(Array.isArray(_)&&_.some(v=>v.type==="tool_result"))){let v=typeof _=="string"?_:Array.isArray(_)?_.filter(E=>E.type==="text"&&typeof E.text=="string").map(E=>E.text).join(`
|
|
2280
|
+
`):"";v&&!/^<(?:command-name>|local-command-|task-notification>\s*<)/u.test(v.trimStart())&&!/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(v.trim())&&!v.trimStart().startsWith("lmctl seed initial connection only.")&&g.push(v)}if(typeof _=="string"){let v=_.trim();if(v.includes("<command-name>")||v.includes("<local-command-")||/^<task-notification>\s*</u.test(v)||v.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(v))continue;u||(u=z(_.trim(),80)),d=z(_.trim(),80),f=void 0,s.push({role:"user",timestamp:b,content:Te(_.trim())})}else if(Array.isArray(_)){for(let v of _)if(v.type==="tool_result"){let E=typeof v.content=="string"?Te(v.content):JSON.stringify(v.content);s.push({role:"tool_result",timestamp:b,content:E,toolCallId:v.tool_use_id})}}}if(y.type==="assistant"&&y.message){y.message.stop_reason===null||y.message.stop_reason==="tool_use"?f="in_progress":typeof y.message.stop_reason=="string"&&(f="complete"),y.message.model&&(l=y.message.model);let b=new Date(y.timestamp||0),_=y.message.content;if(Array.isArray(_))for(let v of _)v.type==="text"&&v.text?s.push({role:"assistant",timestamp:b,content:Te(v.text),model:y.message.model,...typeof y.message.stop_reason=="string"?{stopReason:y.message.stop_reason}:{}}):v.type==="tool_use"?s.push({role:"tool_use",timestamp:b,content:v.name||"unknown tool",toolName:v.name,toolInput:JSON.stringify(v.input,null,2),toolInputData:v.input,toolCallId:v.id,model:y.message.model,...typeof y.message.stop_reason=="string"?{stopReason:y.message.stop_reason}:{}}):v.type==="thinking"&&v.thinking&&s.push({role:"thinking",timestamp:b,content:v.thinking})}}if(!i)return null;Jj(s);let h=await SS(n);return{provider:"claude",sessionId:p,slug:o,cwd:i,createdAt:m||r.createdAt,modifiedAt:r.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:f,firstUserMessage:u,lastUserMessage:d,messageCount:h.messageCount,filePath:n,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:h.totalCacheWriteInputTokens||void 0,totalCacheWrite5mInputTokens:h.totalCacheWrite5mInputTokens||void 0,totalCacheWrite1hInputTokens:h.totalCacheWrite1hInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:s,userPrompts:g}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await Hj(n),!0):!1}async resolveSessionFile(e){let n;try{n=await Gc(this.projectsDir)}catch{return null}let r=[];for(let o of n){let a=Ei(this.projectsDir,o);if(!(await ES(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await Gc(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=TS(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&r.push({filePath:Ei(a,u),fileSessionId:d})}}let s=r.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=r.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of r){let a=await Mt(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{join as RS}from"node:path";function xf(t){return new If(t)}var If,Af=L(()=>{"use strict";kS();rt();We();Yn();ze();If=class extends _e{claudeDir;constructor(e){super({provider:new Jc(e),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",ce,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:qc}),this.claudeDir=e?.claudeDir??RS(ie,".claude")}openSession(e){return Xc({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[RS(this.claudeDir,"projects")]})}seedArgsFor(e){let n=super.seedArgsFor(e);return e?.model?[...n,"--model",e.model]:n}}});import{readdir as Kj,stat as IS,unlink as zj}from"node:fs/promises";import{join as Zo,basename as Yj}from"node:path";function Cf(t,e){if(!Array.isArray(t)||e>=t.length)return!1;let n=t[e];return typeof n=="string"&&Qj.has(n)}function Zj(t,e,n){return`${t}|${e.toISOString()}|${n}`}function ea(t,e,n){let r=Zj(n.role,n.timestamp,n.content);e.has(r)||(e.add(r),t.push(n))}function xS(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function eU(t){if(!t)return;let e=t.cached_input_tokens??t.cache_read_input_tokens;return{inputTokens:t.input_tokens,cachedInputTokens:e,outputTokens:t.output_tokens,reasoningOutputTokens:t.reasoning_output_tokens,totalTokens:t.total_tokens}}function Ti(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){let r=n;if(typeof r.text=="string")return r.text;if(typeof r.image_url=="string")return"[input_image]";if(typeof r.type=="string")return`[${r.type}]`}return Ti(n)}).filter(n=>n.length>0).join(`
|
|
2281
2281
|
`);try{return JSON.stringify(t)}catch{return String(t)}}function tU(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 nU(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 AS(t){let e=0,n=0,r=0,s=0,i=0,o,a,l=new Set,c,u;for await(let d of Ie(t)){if(d.type==="event_msg"&&d.payload?.type==="user_message"){let m=d.payload.message||d.payload.text;m&&(u=z(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 g=m.content[f];Cf(p,f)||g.type==="input_text"&&typeof g.text=="string"&&g.text&&(e++,u=z(g.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 g=JSON.stringify([d.timestamp??null,d.ordinal??null,m,p]);if(!l.has(g)){l.add(g);let h=[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],h.forEach((y,b)=>{a[b]+=y})}}let f=eU(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 Qj,Vc,CS=L(()=>{"use strict";We();Qj=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"]);Vc=class{name="codex";codexDirs;constructor(e={}){let n=[Zo(ie,".codex"),Zo(ie,".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:Zo(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let n of this.codexDirs){let r=Zo(n,"sessions");try{await IS(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 Kj(e)}catch{return n}for(let s of r){let i=Zo(e,s),o=await IS(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=Yj(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 Mt(e,30),r=await De(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 g=f.payload.message||f.payload.text;g&&(c||(c=z(g.trim(),80)),u=z(g.trim(),80))}if(f.type==="response_item"&&f.payload?.type==="message"&&f.payload.role==="user"&&f.payload.content){let g=f.payload.internal_chat_message_metadata_passthrough?.content_item_kinds;for(let h=0;h<f.payload.content.length;h++){let y=f.payload.content[h];Cf(g,h)||y.type==="input_text"&&typeof y.text=="string"&&y.text&&(c||(c=z(y.text.trim(),80)),u=z(y.text.trim(),80))}}}if(!i)return null;let p=await AS(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||r.createdAt,modifiedAt:r.modifiedAt,model:a,cliVersion:o,startCommand:xS(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 De(n),s=[],i="",o,a,l,c,u,d=e,m,p,f=new Set,g=[],h=new Set,y=[],b=(E,I)=>{let T=y.find(k=>!k.mirrored&&k.source!==I&&k.text===E);T?T.mirrored=!0:y.push({text:E,source:I,mirrored:!1})},_=()=>{g.push(...y.map(E=>E.text)),y=[]};for await(let E of Ie(n)){let I=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=xS(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 T=E.payload;if(T.type==="message"){if(T.role==="user"&&T.content){let k=T.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(k)){let N=T.content.filter((C,O)=>k[O]==="user.text"&&typeof C.text=="string").map(C=>C.text).join(`
|
|
2282
2282
|
`);k.includes("user.text")&&N&&(!T.id||!h.has(T.id))&&(b(N,"metadata"),T.id&&h.add(T.id))}for(let N=0;N<T.content.length;N++){let C=T.content[N];if(!Cf(k,N)&&C.type==="input_text"&&typeof C.text=="string"&&C.text){let O=C.text.trim();c||(c=z(O,80)),u=z(O,80),ea(s,f,{role:"user",timestamp:I,content:Te(O)})}}continue}if(T.role==="assistant"&&T.content){for(let k of T.content)k.type==="output_text"&&typeof k.text=="string"&&k.text&&ea(s,f,{role:"assistant",timestamp:I,content:Te(k.text),model:a});continue}if(T.role!=="user"&&T.role!=="assistant"&&T.content){for(let k of T.content)(k.type==="input_text"||k.type==="output_text")&&typeof k.text=="string"&&k.text&&ea(s,f,{role:"system",timestamp:I,content:Te(k.text.trim())});continue}}if(T.type==="function_call"){s.push({role:"tool_use",timestamp:I,content:T.name||"unknown tool",toolName:T.name,toolInput:T.arguments!==void 0?Te(Ti(T.arguments)):void 0,toolInputData:tU(T.arguments),toolCallId:T.call_id});continue}if(T.type==="function_call_output"){s.push({role:"tool_result",timestamp:I,content:Te(Ti(T.output)),toolCallId:T.call_id});continue}if(T.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:I,content:T.name||"unknown tool",toolName:T.name,toolInput:T.input!==void 0?Te(Ti(T.input)):void 0,toolInputData:nU(T.name,T.input),toolCallId:T.call_id});continue}if(T.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:I,content:Te(Ti(T.output)),toolCallId:T.call_id});continue}if(T.type==="reasoning"&&T.summary){let k=T.summary.map(N=>Ti(N.text)).join(`
|
|
2283
|
-
`);k.trim()&&ea(s,f,{role:"thinking",timestamp:I,content:Te(k)});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 T=E.payload.message||E.payload.text;T&&ea(s,f,{role:"thinking",timestamp:I,content:Te(T)})}}if(!i)return null;_();let v=await AS(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:g}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await zj(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 Mt(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 rU}from"node:child_process";import{realpathSync as NS,readdirSync as sU}from"node:fs";import{homedir as iU}from"node:os";import{join as Kc,resolve as OS,sep as oU}from"node:path";function Lf(t){return new Of(t)}var Nf,Of,Mf=L(()=>{"use strict";CS();rt();Yn();
|
|
2283
|
+
`);k.trim()&&ea(s,f,{role:"thinking",timestamp:I,content:Te(k)});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 T=E.payload.message||E.payload.text;T&&ea(s,f,{role:"thinking",timestamp:I,content:Te(T)})}}if(!i)return null;_();let v=await AS(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:g}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await zj(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 Mt(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 rU}from"node:child_process";import{realpathSync as NS,readdirSync as sU}from"node:fs";import{homedir as iU}from"node:os";import{join as Kc,resolve as OS,sep as oU}from"node:path";function Lf(t){return new Of(t)}var Nf,Of,Mf=L(()=>{"use strict";CS();rt();Yn();ze();Nf="gpt-5.6-sol",Of=class extends _e{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 Vc(e),protocol:{transport:"codex-app-server",perTurnCancellation:"process",persistentCancellation:"turn"},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:`${ce}
|
|
2284
2284
|
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:bS})}async preflightNativeLaunch(e){let n=performance.now()+1800,r=(N,C)=>new Promise(O=>{let w=Math.ceil(n-performance.now());if(w<=0){O(void 0);return}let S,R=()=>{try{S?.kill("SIGKILL")}catch{}},x=()=>{R()},A=()=>{R()},M=()=>{R()};process.once("exit",x),process.once("SIGINT",A),process.once("SIGTERM",M);let P=()=>{process.removeListener("exit",x),process.removeListener("SIGINT",A),process.removeListener("SIGTERM",M)};S=rU(N,C,{cwd:e.cwd,env:e.env,signal:e.signal,timeout:w,killSignal:"SIGKILL",maxBuffer:65536},(U,F)=>{P(),O(U?void 0:F)})}),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,g=p+"; using the daemon's binary. "+f,h={kind:"ok",message:p+"; no matching daemon binary is available, launching the PATH CLI. "+f},y=OS(e.cwd,e.env.CODEX_HOME||Kc(e.env.HOME||iU(),".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 I=N=>N.replace(/\+.*$/,""),T=I(u),k=process.arch==="arm64"?"aarch64":"x86_64";for(let N of["app-server-daemon","standalone"]){let C=Kc(y,"packages",N,"releases");try{_.push(NS(C)+oU);let O=sU(C).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===T||w.startsWith(u+"-")||w.startsWith(T+"-"));O.sort((w,S)=>{let R=w.includes(k)?0:1,x=S.includes(k)?0:1;return R!==x?R-x:w.localeCompare(S)});for(let w of O)b.push(Kc(C,w,"bin",v)),b.push(Kc(C,w,v))}catch{}}for(let N of new Set(b)){if(performance.now()>=n||e.signal?.aborted)break;let C;try{if(C=NS(OS(e.cwd,N)),!_.some(S=>C.startsWith(S)))continue}catch{continue}let w=(await r(C,["--version"]))?.trim().match(/^codex(?:-cli)?\s+([0-9A-Za-z.+-]+)/)?.[1];if(w&&(w===u||I(w)===T))return{kind:"use-binary",binary:C,message:g}}return h}openSession(e){return wS({...e,model:e.model??Nf})}seedArgsFor(e){let n=super.seedArgsFor(e),r=e?.model??Nf;return[...n.slice(0,-1),"--model",r,n[n.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Nf}}}});import{createHash as aU}from"node:crypto";import{readdir as ta,readFile as LS,stat as zc,unlink as lU}from"node:fs/promises";import{join as jt,basename as cU,dirname as uU}from"node:path";import{cwd as dU}from"node:process";function Pf(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function MS(t){return t==="user"}function Df(t){return t==="gemini"||t==="assistant"}function Ss(t,e=new Date(0)){if(!t)return e;let n=new Date(t);return Number.isNaN(n.getTime())?e:n}function mU(t){return`${t.sessionId}\0${t.cwd}`}function pU(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 Yc(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function PS(t){let e=0,n=0,r=0,s=0,i=0,o;for(let a of t){if(!Df(a.type)||!a.tokens)continue;let l=Yc(a.tokens.input),c=Yc(a.tokens.cached),u=Math.max(l-c,0),d=Yc(a.tokens.output),m=Yc(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 fU(t){return aU("sha256").update(t).digest("hex")}function na(t,e){let n=e;for(;n&&!t.has(n);){t.add(n);let r=uU(n);if(r===n)break;n=r}}var Qc,DS=L(()=>{"use strict";We();xl();Se();Qc=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let n=e.geminiDir||jt(ie,".gemini");this.geminiProjectsFile=jt(n,"projects.json"),this.geminiTmpDir=jt(n,"tmp");let r=e.claudeDir||jt(ie,".claude");this.claudeProjectsDir=jt(r,"projects");let s=[jt(ie,".codex"),jt(ie,".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=>jt(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=mU(s),o=n.get(i);n.set(i,o?pU(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 De(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=Ss(y.timestamp),_=y.type,v=Te(Pf(y.content));if(MS(_)){let I=Pf(y.content);I&&o.push(I);let T=v.trim();T&&(d||(d=z(T,80)),m=z(T,80)),i.push({role:"user",timestamp:b,content:T||v});continue}if(Df(_)){y.model&&(p=y.model);for(let I of y.thoughts||[]){let T=[I.subject,I.description].filter(Boolean).join(`
|
|
2285
|
-
`).trim();T&&i.push({role:"thinking",timestamp:Ss(I.timestamp,b),content:Te(T)})}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=Ss(r.startTime,s.createdAt),g=Ss(r.lastUpdated,s.modifiedAt),h=PS(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:f,modifiedAt:g,model:p,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(y=>y.role==="user"||y.role==="assistant").length,filePath:n,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let n=await this.readSessionFile(e);if(!n)return null;let r=await De(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(MS(p.type)){d++;let f=Pf(p.content).trim();f&&(l||(l=z(Te(f),80)),c=z(Te(f),80))}else Df(p.type)&&(d++,p.model&&(u=p.model));let m=PS(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Ss(n.startTime,r.createdAt),modifiedAt:Ss(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 LS(e,"utf-8");if(_o(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 as(n)}catch{return null}}extractSessionIdFromFilename(e){let n=cU(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 ta(this.geminiTmpDir)}catch{return e}for(let r of n){let s=jt(this.geminiTmpDir,r,"chats");if(!(await zc(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await ta(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(jt(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await lU(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 De(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));r.push({filePath:s,modifiedAt:Ss(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;na(e,dU());for(let r of this.extraWorkspacePaths)na(e,r);for(let r of await this.collectGeminiProjectPaths())na(e,r);for(let r of await this.collectCodexCwds())na(e,r);for(let r of await this.collectClaudeCwds())na(e,r);let n=new Map;for(let r of e)n.set(fU(r),r);return this.workspaceHashMap=n,n}async collectGeminiProjectPaths(){let e;try{e=await LS(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 Mt(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,n;try{n=await ta(this.claudeProjectsDir)}catch{return[]}for(let r of n){let s=jt(this.claudeProjectsDir,r);if(!(await zc(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await ta(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=jt(s,a),u=(await Mt(l,1).catch(()=>[]))[0]?.cwd;u&&e.add(u)}}return[...e]}async findJsonlFiles(e){let n=[];if(!(await zc(e).catch(()=>null))?.isDirectory())return n;let s;try{s=await ta(e)}catch{return n}for(let i of s){let o=jt(e,i),a=await zc(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 gU,writeFileSync as hU,mkdirSync as yU}from"node:fs";import{join as _U,dirname as vU}from"node:path";import{randomUUID as bU}from"node:crypto";function $f(t){return new Ff(t)}var Ff,jf=L(()=>{"use strict";ui();DS();rt();
|
|
2286
|
-
`)}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:Cc,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=gU(r,"utf-8"),i=_o(s),o=as(s),a=bU();o.sessionId=a,o.kind="main";let l=vU(r),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,m=_U(l,d);return yU(l,{recursive:!0}),hU(m,Zv(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 FS,readFile as wU,rm as EU,stat as Si}from"node:fs/promises";import{basename as TU,join as
|
|
2285
|
+
`).trim();T&&i.push({role:"thinking",timestamp:Ss(I.timestamp,b),content:Te(T)})}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=Ss(r.startTime,s.createdAt),g=Ss(r.lastUpdated,s.modifiedAt),h=PS(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:f,modifiedAt:g,model:p,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(y=>y.role==="user"||y.role==="assistant").length,filePath:n,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let n=await this.readSessionFile(e);if(!n)return null;let r=await De(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(MS(p.type)){d++;let f=Pf(p.content).trim();f&&(l||(l=z(Te(f),80)),c=z(Te(f),80))}else Df(p.type)&&(d++,p.model&&(u=p.model));let m=PS(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Ss(n.startTime,r.createdAt),modifiedAt:Ss(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 LS(e,"utf-8");if(_o(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 as(n)}catch{return null}}extractSessionIdFromFilename(e){let n=cU(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 ta(this.geminiTmpDir)}catch{return e}for(let r of n){let s=jt(this.geminiTmpDir,r,"chats");if(!(await zc(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await ta(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(jt(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let n=await this.resolveSessionFile(e);return n?(await lU(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 De(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));r.push({filePath:s,modifiedAt:Ss(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;na(e,dU());for(let r of this.extraWorkspacePaths)na(e,r);for(let r of await this.collectGeminiProjectPaths())na(e,r);for(let r of await this.collectCodexCwds())na(e,r);for(let r of await this.collectClaudeCwds())na(e,r);let n=new Map;for(let r of e)n.set(fU(r),r);return this.workspaceHashMap=n,n}async collectGeminiProjectPaths(){let e;try{e=await LS(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 Mt(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,n;try{n=await ta(this.claudeProjectsDir)}catch{return[]}for(let r of n){let s=jt(this.claudeProjectsDir,r);if(!(await zc(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await ta(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=jt(s,a),u=(await Mt(l,1).catch(()=>[]))[0]?.cwd;u&&e.add(u)}}return[...e]}async findJsonlFiles(e){let n=[];if(!(await zc(e).catch(()=>null))?.isDirectory())return n;let s;try{s=await ta(e)}catch{return n}for(let i of s){let o=jt(e,i),a=await zc(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 gU,writeFileSync as hU,mkdirSync as yU}from"node:fs";import{join as _U,dirname as vU}from"node:path";import{randomUUID as bU}from"node:crypto";function $f(t){return new Ff(t)}var Ff,jf=L(()=>{"use strict";ui();DS();rt();ze();xl();Ff=class extends _e{constructor(e){super({provider:new Qc(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",ce,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:()=>Promise.reject(new Error(Ar))})}seed(e,n){return Promise.resolve({success:!1,error:Ar})}sendTurn(e,n){return Promise.reject(new Error(Ar))}openSession(e){return Promise.reject(new Error(Ar))}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(`
|
|
2286
|
+
`)}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:Cc,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=gU(r,"utf-8"),i=_o(s),o=as(s),a=bU();o.sessionId=a,o.kind="main";let l=vU(r),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,m=_U(l,d);return yU(l,{recursive:!0}),hU(m,Zv(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 FS,readFile as wU,rm as EU,stat as Si}from"node:fs/promises";import{basename as TU,join as ln}from"node:path";function SU(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 Uf(){return{shutdownTotals:null,assistantOutputSum:0}}function jS(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=SU(e.data?.modelMetrics);n&&(t.shutdownTotals=n)}}function $S(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 kU(t){let e={};for(let n of t.split(`
|
|
2287
2287
|
`)){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 ks(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function RU(t){let e=0,n=Uf(),r;for await(let s of Ie(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(r=z(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;jS(n,s)}return{messageCount:e,tokens:n,lastUserMessage:r}}function IU(t){let e=xU(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(`
|
|
2288
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${r.toolCallId}`;n.set(u,d),r.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(r.toolName??""))continue;let s=r.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=n.get(i);if(o===void 0)continue;r.backgroundTaskId=o;let a=e.get(r.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function xU(t){let e=new Map;for(let n of t)n.role==="tool_result"&&n.toolCallId!==void 0&&e.set(n.toolCallId,n);return e}var Zc,US=L(()=>{"use strict";We();Zc=class{name="copilot";sessionStateDir;constructor(e={}){let n=e.copilotDir||
|
|
2288
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${r.toolCallId}`;n.set(u,d),r.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(r.toolName??""))continue;let s=r.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=n.get(i);if(o===void 0)continue;r.backgroundTaskId=o;let a=e.get(r.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function xU(t){let e=new Map;for(let n of t)n.role==="tool_result"&&n.toolCallId!==void 0&&e.set(n.toolCallId,n);return e}var Zc,US=L(()=>{"use strict";We();Zc=class{name="copilot";sessionStateDir;constructor(e={}){let n=e.copilotDir||ln(ie,".copilot");this.sessionStateDir=ln(n,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],n;try{n=await FS(this.sessionStateDir)}catch{return e}for(let r of n){let s=ln(this.sessionStateDir,r);if((await Si(s).catch(()=>null))?.isDirectory())try{let o=await this.extractSummary(s,r);o&&e.push(o)}catch{}}return e}async loadSession(e){let n=await this.resolveSessionDir(e);if(!n)return null;let r=await this.readWorkspaceYaml(n),s=ln(n,"events.jsonl"),i=await Si(s).catch(()=>null),o=i?s:ln(n,"workspace.yaml"),a=await De(i?s:n),l=[],c=[],u=r?.cwd||"(unknown workspace)",d,m,p,f,g,h,y=r?.id||TU(n)||e,b=Uf();if(i)for await(let _ of Ie(s)){let v=ks(_.timestamp)||a.modifiedAt;if(jS(b,_),_.type==="session.start"&&_.data){_.data.sessionId&&(y=_.data.sessionId),_.data.copilotVersion&&(m=_.data.copilotVersion),_.data.startTime&&(h=ks(_.data.startTime)),_.data.selectedModel&&(d=_.data.selectedModel),_.data.context&&(_.data.context.cwd&&(u=_.data.context.cwd),_.data.context.branch&&(p=_.data.context.branch));continue}if(_.type==="session.model_change"&&_.data?.newModel){d=_.data.newModel;continue}if(_.type==="user.message"&&_.data){let E=_.data.content||"";E&&c.push(E);let I=E.trim();I&&(f||(f=z(I,80)),g=z(I,80)),l.push({role:"user",timestamp:v,content:Te(I||E)});continue}if(_.type==="assistant.message"&&_.data){let E=(_.data.content||"").trim();if(E&&l.push({role:"assistant",timestamp:v,content:Te(E),model:d}),_.data.toolRequests)for(let I of _.data.toolRequests)l.push({role:"tool_use",timestamp:v,content:I.name||"unknown tool",toolName:I.name,toolInput:I.arguments?JSON.stringify(I.arguments,null,2):void 0,toolInputData:Jt(I.arguments),toolCallId:I.toolCallId});continue}if(_.type==="tool.execution_complete"&&_.data){let E=_.data.result?.content||"",I=_.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:v,content:Te(E),toolDetailedContent:I?Te(I):void 0,toolCallId:_.data.toolCallId});continue}if(_.type==="assistant.reasoning"&&_.data?.content){l.push({role:"thinking",timestamp:v,content:Te(_.data.content)});continue}if(_.type==="session.error"||_.type==="session.warning"||_.type==="session.info"||_.type==="system.message"){let E=_.data?.message||"";E.trim()&&l.push({role:"system",timestamp:v,content:Te(E)});continue}}if(!f){let _=(r?.summary||"").trim();_&&(f=z(_,80))}return IU(l),{provider:"copilot",sessionId:y,cwd:u,createdAt:h??ks(r?.created_at)??a.createdAt,modifiedAt:ks(r?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",gitBranch:p,firstUserMessage:f,lastUserMessage:g,messageCount:l.filter(_=>_.role==="user"||_.role==="assistant").length,filePath:o,...$S(b),messages:l,userPrompts:c}}async extractSummary(e,n){let r=await this.readWorkspaceYaml(e),s=ln(e,"events.jsonl"),i=await Si(s).catch(()=>null),o=i?s:ln(e,"workspace.yaml"),a=await De(i?s:e),l=i?await Mt(s,20):[],c=r?.id||n,u=r?.cwd||"(unknown workspace)",d,m,p,f,g;for(let y of l)if(y.type==="session.start"&&y.data&&(y.data.sessionId&&(c=y.data.sessionId),y.data.copilotVersion&&(m=y.data.copilotVersion),y.data.startTime&&(p=ks(y.data.startTime)),y.data.selectedModel&&(d=y.data.selectedModel),y.data.context?.cwd&&(u=y.data.context.cwd)),y.type==="session.model_change"&&y.data?.newModel&&(d||(d=y.data.newModel)),y.type==="user.message"&&y.data){let b=(y.data.content||"").trim();b&&(f||(f=z(b,80)),g=z(b,80))}if(!f){let y=(r?.summary||"").trim();y&&(f=z(y,80))}let h=i?await RU(s):{messageCount:0,tokens:Uf()};return{provider:"copilot",sessionId:c,cwd:u,createdAt:p??ks(r?.created_at)??a.createdAt,modifiedAt:ks(r?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",firstUserMessage:f,lastUserMessage:h.lastUserMessage??g,messageCount:h.messageCount,filePath:o,...$S(h.tokens)}}async readWorkspaceYaml(e){let n=ln(e,"workspace.yaml");try{let r=await wU(n,"utf-8");return kU(r)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let n=await this.resolveSessionDir(e);return n?(await EU(n,{recursive:!0}),!0):!1}async resolveSessionDir(e){let n;try{n=await FS(this.sessionStateDir)}catch{return null}if(n.includes(e)){let s=ln(this.sessionStateDir,e);if((await Si(s).catch(()=>null))?.isDirectory())return s}let r=[];for(let s of n)if(s.startsWith(e)){let i=ln(this.sessionStateDir,s);(await Si(i).catch(()=>null))?.isDirectory()&&r.push(i)}if(r.length===1)return r[0];for(let s of n){let i=ln(this.sessionStateDir,s);if(!(await Si(i).catch(()=>null))?.isDirectory())continue;let a=await this.readWorkspaceYaml(i);if(a&&(a.id===e||a.id?.startsWith(e)))return i}return null}}});function Bf(t){return new Hf(t)}var Hf,Wf=L(()=>{"use strict";US();rt();Yn();Se();ze();Hf=class extends _e{copilotDir;constructor(e){super({provider:new Zc(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",ce,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(n,r)=>an(n,{...r,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return Sn({...e,env:this.copilotDir!==void 0?{...e.env??process.env,COPILOT_HOME:this.copilotDir}:e.env,binary:"copilot",acpTool:"copilot"})}async seed(e,n){let r=await super.seed(e,n);if(n?.model===void 0||n.model.trim().length===0)return r;let s="copilot seed does not implement per-session model selection";return dt({event:"model_ignored",provider:"copilot",model:n.model,reason:s}),{...r,warnings:[...r.warnings??[],`copilot seed ignored model=${n.model}: ${s}`]}}}});function Xf(t){return new qf(t)}var qf,Gf=L(()=>{"use strict";Xo();rt();Yn();ze();qf=class extends _e{constructor(e){super({provider:new yi(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"custom-tool",leaderSetupHint:"OpenCode supports custom tools via .opencode/tools/ directory"},binary:"opencode",seedArgs:["run",ce],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(n,r)=>an(n,{...r,acpTool:"opencode"})})}openSession(e){return Sn({...e,binary:"opencode",acpTool:"opencode"})}seedArgsFor(e){let n=["run"];return e?.model&&n.push("--model",e.model),e?.effort&&n.push("--variant",e.effort),n.push(e?.prompt??ce),n}}});import{appendFile as AU,mkdir as CU,readFile as HS,readdir as BS,rm as NU,stat as WS}from"node:fs/promises";import{basename as OU,dirname as LU,isAbsolute as qS,join as Rs,relative as MU,resolve as Jf}from"node:path";function Vf(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function $U(t){return typeof t=="number"?new Date(t):Vf(t)??new Date(0)}function XS(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
|
|
2289
2289
|
`).trim():""}function GS(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function jU(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:GS(t)??""}function UU(t){let e=HU(t),n=new Set;for(let r of t){if(r.role!=="tool_use"||r.toolName!=="Bash"||r.toolInputData?.run_in_background!==!0||r.toolCallId===void 0)continue;let s=e.get(r.toolCallId);if(s===void 0)continue;let i=s.content.match(/(?:^|\n)task_id:\s*([^\s]+)/)?.[1];i!==void 0&&(n.add(i),r.backgroundTaskId=i,s.backgroundTaskId=i)}for(let r of t){if(r.role!=="tool_use"||r.toolName!=="TaskOutput"&&r.toolName!=="TaskStop"||r.toolCallId===void 0)continue;let s=r.toolInputData?.task_id;if(typeof s!="string"||!n.has(s))continue;r.backgroundTaskId=s;let i=e.get(r.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function HU(t){let e=new Map;for(let n of t)n.role==="tool_result"&&n.toolCallId!==void 0&&e.set(n.toolCallId,n);return e}var PU,DU,FU,eu,JS=L(()=>{"use strict";We();PU="1.4",DU="1.5",FU=new Set([PU,DU]),eu=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=Jf(e?.kimiHome??process.env.KIMI_CODE_HOME??Rs(ie,".kimi-code")),this.sessionsDir=Rs(this.homeDir,"sessions")}async discoverSessions(){let e=[];for(let n of await this.sessionFiles())try{let r=await this.summary(n);r&&e.push(r)}catch{}return e.sort((n,r)=>r.modifiedAt.getTime()-n.modifiedAt.getTime())}async loadSession(e){let n=await this.findSession(e);if(!n)return null;let r=await this.summary(n);if(!r)return null;let s=await this.parseWire(n.wirePath);return{...r,messages:s.messages,userPrompts:s.userPrompts}}async resolveSessionPath(e){return(await this.findSession(e))?.wirePath??null}async deleteSession(e){let n=await this.findSession(e);return n?(await NU(n.sessionDir,{recursive:!0,force:!0}),await CU(LU(this.indexPath()),{recursive:!0,mode:448}),await AU(this.indexPath(),`${JSON.stringify({sessionId:n.sessionId,deleted:!0})}
|
|
2290
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return Rs(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),n=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&n.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let r;try{r=await BS(this.sessionsDir,{withFileTypes:!0})}catch{return[...n.values()]}for(let s of r){if(!s.isDirectory())continue;let i=Rs(this.sessionsDir,s.name),o;try{o=await BS(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||n.has(a.name))continue;let l=Rs(i,a.name);n.set(a.name,this.filesFor(a.name,l))}}return[...n.values()]}async readIndex(){let e;try{e=await HS(this.indexPath(),"utf-8")}catch{return new Map}let n=new Map;for(let r of e.split(/\r?\n/))if(r.trim())try{let s=JSON.parse(r);if(typeof s.sessionId!="string")continue;s.deleted===!0?n.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&n.set(s.sessionId,{sessionId:s.sessionId,sessionDir:Jf(s.sessionDir),workDir:s.workDir})}catch{}return n}filesFor(e,n,r){return{sessionId:e,sessionDir:n,statePath:Rs(n,"state.json"),wirePath:Rs(n,"agents","main","wire.jsonl"),indexedWorkDir:r}}validSessionDir(e,n){if(!qS(e)||OU(e)!==n)return!1;let r=MU(this.sessionsDir,Jf(e));return r!==""&&r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!qS(r)}async findSession(e){let n=await this.sessionFiles(),r=n.find(i=>i.sessionId===e);if(r)return r;let s=n.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let n=JSON.parse(await HS(e,"utf-8"));return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async summary(e){let n=await this.readState(e.statePath);if(!n)return null;let r;try{r=await WS(e.wirePath)}catch{return null}let s=await WS(e.statePath).catch(()=>r),i=await this.parseWire(e.wirePath),o=Vf(n.createdAt)??s.birthtime,a=Vf(n.updatedAt)??(s.mtime>r.mtime?s.mtime:r.mtime);return{provider:"kimi",sessionId:e.sessionId,slug:n.title,cwd:n.workDir??e.indexedWorkDir??"(unknown)",createdAt:o,modifiedAt:a,model:i.model,startCommand:"kimi",firstUserMessage:i.firstUserMessage,lastUserMessage:i.lastUserMessage??(n.lastPrompt?z(n.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let n=[],r=[],s=new Set,i=!0,o,a,l,c=0,u=0,d=0,m=0,p=!1,f=0,g,h;for await(let y of Ie(e)){let b=$U(y.time??y.created_at);if(i&&(i=!1,y.type==="metadata"&&!FU.has(y.protocol_version))){let v=`Kimi transcript wire protocol version ${JSON.stringify(y.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:b,content:v}],userPrompts:[],messageCount:1,firstUserMessage:v,lastUserMessage:v}}if((y.type==="config.update"||y.type==="profile.bind")&&y.modelAlias&&(o=y.modelAlias),y.type==="usage.record"){y.model&&(o=y.model),p||=y.usage!==void 0;let v=y.usage?.inputOther??0,E=y.usage?.inputCacheRead??0,I=y.usage?.inputCacheCreation??0,T=y.usage?.output??0;c+=v,u+=E,d+=I,m+=T,y.usageScope==="turn"&&(g=v+E+I,h={inputTokens:v,cachedInputTokens:E,cacheWriteInputTokens:I,outputTokens:T,totalTokens:g+T});continue}if(y.type==="turn.prompt"&&y.origin?.kind==="user"){let v=XS(y.input);v&&((!y.promptId||!s.has(y.promptId))&&(r.push(v),y.promptId&&s.add(y.promptId)),a??=z(v,80),l=z(v,80),n.push({role:"user",timestamp:b,content:v}),f++);continue}if(y.type==="turn.steer"){let v=XS(y.input);v&&(n.push({role:"system",timestamp:b,content:v}),f++);continue}if(y.type!=="context.append_loop_event"||!y.event)continue;let _=y.event;_.type==="content.part"&&_.part?.type==="text"&&_.part.text?(n.push({role:"assistant",timestamp:b,content:_.part.text,model:o}),f++):_.type==="content.part"&&_.part?.type==="think"&&_.part.think?n.push({role:"thinking",timestamp:b,content:_.part.think,model:o}):_.type==="tool.call"?n.push({role:"tool_use",timestamp:b,content:_.name??"tool",toolName:_.name,toolInput:GS(_.args),toolInputData:Jt(_.args),toolCallId:_.toolCallId,model:o}):_.type==="tool.result"&&n.push({role:"tool_result",timestamp:b,content:jU(_.result),toolCallId:_.toolCallId,model:o})}return UU(n),{messages:n,userPrompts:r,messageCount:f,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:p?c:void 0,totalCachedInputTokens:p?u:void 0,totalCacheWriteInputTokens:p?d:void 0,totalOutputTokens:p?m:void 0,lastInputTokens:g,lastTokenUsage:h}}}});function zf(t){return new Kf(t)}var Kf,Yf=L(()=>{"use strict";JS();rt();Yn();
|
|
2290
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return Rs(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),n=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&n.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let r;try{r=await BS(this.sessionsDir,{withFileTypes:!0})}catch{return[...n.values()]}for(let s of r){if(!s.isDirectory())continue;let i=Rs(this.sessionsDir,s.name),o;try{o=await BS(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||n.has(a.name))continue;let l=Rs(i,a.name);n.set(a.name,this.filesFor(a.name,l))}}return[...n.values()]}async readIndex(){let e;try{e=await HS(this.indexPath(),"utf-8")}catch{return new Map}let n=new Map;for(let r of e.split(/\r?\n/))if(r.trim())try{let s=JSON.parse(r);if(typeof s.sessionId!="string")continue;s.deleted===!0?n.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&n.set(s.sessionId,{sessionId:s.sessionId,sessionDir:Jf(s.sessionDir),workDir:s.workDir})}catch{}return n}filesFor(e,n,r){return{sessionId:e,sessionDir:n,statePath:Rs(n,"state.json"),wirePath:Rs(n,"agents","main","wire.jsonl"),indexedWorkDir:r}}validSessionDir(e,n){if(!qS(e)||OU(e)!==n)return!1;let r=MU(this.sessionsDir,Jf(e));return r!==""&&r!==".."&&!r.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!qS(r)}async findSession(e){let n=await this.sessionFiles(),r=n.find(i=>i.sessionId===e);if(r)return r;let s=n.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let n=JSON.parse(await HS(e,"utf-8"));return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}catch{return null}}async summary(e){let n=await this.readState(e.statePath);if(!n)return null;let r;try{r=await WS(e.wirePath)}catch{return null}let s=await WS(e.statePath).catch(()=>r),i=await this.parseWire(e.wirePath),o=Vf(n.createdAt)??s.birthtime,a=Vf(n.updatedAt)??(s.mtime>r.mtime?s.mtime:r.mtime);return{provider:"kimi",sessionId:e.sessionId,slug:n.title,cwd:n.workDir??e.indexedWorkDir??"(unknown)",createdAt:o,modifiedAt:a,model:i.model,startCommand:"kimi",firstUserMessage:i.firstUserMessage,lastUserMessage:i.lastUserMessage??(n.lastPrompt?z(n.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let n=[],r=[],s=new Set,i=!0,o,a,l,c=0,u=0,d=0,m=0,p=!1,f=0,g,h;for await(let y of Ie(e)){let b=$U(y.time??y.created_at);if(i&&(i=!1,y.type==="metadata"&&!FU.has(y.protocol_version))){let v=`Kimi transcript wire protocol version ${JSON.stringify(y.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:b,content:v}],userPrompts:[],messageCount:1,firstUserMessage:v,lastUserMessage:v}}if((y.type==="config.update"||y.type==="profile.bind")&&y.modelAlias&&(o=y.modelAlias),y.type==="usage.record"){y.model&&(o=y.model),p||=y.usage!==void 0;let v=y.usage?.inputOther??0,E=y.usage?.inputCacheRead??0,I=y.usage?.inputCacheCreation??0,T=y.usage?.output??0;c+=v,u+=E,d+=I,m+=T,y.usageScope==="turn"&&(g=v+E+I,h={inputTokens:v,cachedInputTokens:E,cacheWriteInputTokens:I,outputTokens:T,totalTokens:g+T});continue}if(y.type==="turn.prompt"&&y.origin?.kind==="user"){let v=XS(y.input);v&&((!y.promptId||!s.has(y.promptId))&&(r.push(v),y.promptId&&s.add(y.promptId)),a??=z(v,80),l=z(v,80),n.push({role:"user",timestamp:b,content:v}),f++);continue}if(y.type==="turn.steer"){let v=XS(y.input);v&&(n.push({role:"system",timestamp:b,content:v}),f++);continue}if(y.type!=="context.append_loop_event"||!y.event)continue;let _=y.event;_.type==="content.part"&&_.part?.type==="text"&&_.part.text?(n.push({role:"assistant",timestamp:b,content:_.part.text,model:o}),f++):_.type==="content.part"&&_.part?.type==="think"&&_.part.think?n.push({role:"thinking",timestamp:b,content:_.part.think,model:o}):_.type==="tool.call"?n.push({role:"tool_use",timestamp:b,content:_.name??"tool",toolName:_.name,toolInput:GS(_.args),toolInputData:Jt(_.args),toolCallId:_.toolCallId,model:o}):_.type==="tool.result"&&n.push({role:"tool_result",timestamp:b,content:jU(_.result),toolCallId:_.toolCallId,model:o})}return UU(n),{messages:n,userPrompts:r,messageCount:f,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:p?c:void 0,totalCachedInputTokens:p?u:void 0,totalCacheWriteInputTokens:p?d:void 0,totalOutputTokens:p?m:void 0,lastInputTokens:g,lastTokenUsage:h}}}});function zf(t){return new Kf(t)}var Kf,Yf=L(()=>{"use strict";JS();rt();Yn();ze();Kf=class extends _e{kimiHome;constructor(e){super({provider:new eu(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Kimi supports skills through ~/.kimi-code/skills and --skills-dir."},binary:"kimi",seedArgs:["-p",ce,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(n,r)=>an(n,{...r,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return Sn({...e,env:this.kimiHome!==void 0?{...e.env??process.env,KIMI_CODE_HOME:this.kimiHome}:e.env,binary:"kimi",acpTool:"kimi"})}seedArgsFor(e){let n=[];return e?.model&&n.push("--model",e.model),n.push("-p",e?.prompt??ce,"--output-format","stream-json"),n}}});import{spawn as BU}from"node:child_process";import{mkdirSync as WU}from"node:fs";function Zf(t){return new Qf(t)}async function qU(t,e){let n=Date.now(),r=VS({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});qe("lmplayer",r,e.permissionMode??"yolo");let s=await zS(e.binary,r,{cwd:e.cwd,env:je(e.env,e.cwd,e.sessionId),signal:e.signal,onText:i=>{e.onProgress?.({kind:"text",summary:i.slice(0,120)}),e.onDelta?.(i)}});if(s.code!==0&&s.code!==null)throw new Error(KS(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-n}}function VS(t){let e=["run"];return t.model&&e.push("--model",t.model),t.sessionId&&e.push("--session",t.sessionId),t.formatJson&&e.push("--format","json"),t.effort&&e.push("--effort",t.effort),e.push(...Mr("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function KS(t){let n=[vs(t.stderr).trim(),t.error].filter(Boolean).join(`
|
|
2291
2291
|
`);return n?Ae(n,{provider:"lmplayer"}):`exit code ${t.code}`}function zS(t,e,n){return new Promise((r,s)=>{let i;try{i=BU(t,e,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(g){s(g);return}let o="",a="",l="",c,u,d,m=[],p=!1,f=g=>{let h=g.trim();if(!h)return;let y;try{y=JSON.parse(h)}catch{m.push(g),n.onText?.(g);return}if(!ki(y))return;let b=tu(y,!1);c===void 0&&b!==void 0&&(c=b),u=tu(y,!0)??u;let _=XU(y);_!==void 0&&(d=_);let v=YS(y);v&&(m.push(v),n.onText?.(v))};i.stdout?.on("data",g=>{let h=g.toString("utf8");o+=h,l+=h;let y=l.indexOf(`
|
|
2292
2292
|
`);for(;y>=0;){let b=l.slice(0,y);l=l.slice(y+1),f(b),y=l.indexOf(`
|
|
2293
|
-
`)}}),i.stderr?.on("data",g=>{a+=g.toString("utf8")}),n.signal&&(n.signal.aborted?i.kill():n.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",g=>{p||(p=!0,l.length>0&&f(l),r({code:g,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",g=>{p||(p=!0,s(g))})})}function XU(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(ki(e)){let n=e.data;if(ki(n)&&typeof n.message=="string"&&n.message.length>0)return typeof e.name=="string"?`${e.name}: ${n.message}`:n.message;if(typeof e.message=="string"&&e.message.length>0)return e.message}}function YS(t){for(let e of["text","content","delta","output","message"]){let n=t[e];if(typeof n=="string")return n}for(let e of["data","event","payload","part"]){let n=t[e];if(ki(n)){let r=YS(n);if(r)return r}}}function tu(t,e){for(let r of["sessionID","sessionId","session_id"]){let s=t[r];if(typeof s=="string"&&s.length>0)return s}let n=t.session;if(typeof n=="string"&&n.length>0)return n;if(ki(n)){let r=tu(n,e);if(r!==void 0)return r}if(e){let r=t.id;if(typeof r=="string"&&r.length>0)return r}for(let r of["data","event","payload","part"]){let s=t[r];if(ki(s)){let i=tu(s,e);if(i!==void 0)return i}}}function ki(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Qf,eg=L(()=>{"use strict";Xo();rt();
|
|
2293
|
+
`)}}),i.stderr?.on("data",g=>{a+=g.toString("utf8")}),n.signal&&(n.signal.aborted?i.kill():n.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",g=>{p||(p=!0,l.length>0&&f(l),r({code:g,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",g=>{p||(p=!0,s(g))})})}function XU(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(ki(e)){let n=e.data;if(ki(n)&&typeof n.message=="string"&&n.message.length>0)return typeof e.name=="string"?`${e.name}: ${n.message}`:n.message;if(typeof e.message=="string"&&e.message.length>0)return e.message}}function YS(t){for(let e of["text","content","delta","output","message"]){let n=t[e];if(typeof n=="string")return n}for(let e of["data","event","payload","part"]){let n=t[e];if(ki(n)){let r=YS(n);if(r)return r}}}function tu(t,e){for(let r of["sessionID","sessionId","session_id"]){let s=t[r];if(typeof s=="string"&&s.length>0)return s}let n=t.session;if(typeof n=="string"&&n.length>0)return n;if(ki(n)){let r=tu(n,e);if(r!==void 0)return r}if(e){let r=t.id;if(typeof r=="string"&&r.length>0)return r}for(let r of["data","event","payload","part"]){let s=t[r];if(ki(s)){let i=tu(s,e);if(i!==void 0)return i}}}function ki(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Qf,eg=L(()=>{"use strict";Xo();rt();ze();Tn();on();hc();sn();Qf=class extends _e{constructor(e){super({provider:new yi({providerName:"lmplayer",startCommand:"lmplayer",dbPaths:e?.lmplayerDbPaths,dbPath:e?.lmplayerDbPath}),protocol:{transport:"lmplayer",perTurnCancellation:"process"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none"},binary:"lmplayer",seedArgs:["run","--format","json","--dangerously-skip-permissions",ce],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:qU})}async sendTurn(e,n){let r=await super.sendTurn(e,n);return n.permissionMode==="plan"?{...r,warnings:[...r.warnings??[],"lmplayer does not enforce plan mode; this turn used full permissions"]}:r}seedArgsFor(e){return VS({prompt:e?.prompt??ce,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,n){WU(e,{recursive:!0});let r=this.seedArgsFor(n);qe("lmplayer",r);try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}let s=await zS(this.binary,r,{cwd:e,env:hi(n?.env,e),signal:n?.signal});return s.code!==0&&s.code!==null?{success:!1,error:KS(s)}:s.sessionId?{success:!0,sessionId:s.sessionId}:{success:!1,error:"lmplayer seed failed; provider did not report a sessionID"}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}manualSeedHint(e){return{launchCommand:`cd ${e} && lmplayer run --format json --dangerously-skip-permissions "${ce}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as nu,readFile as GU,rm as JU}from"node:fs/promises";import{basename as QS,join as jr}from"node:path";function VU(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function ra(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function KU(t,e){if(!e)return;t.observed=!0;let n=ra(e.promptTokenCount),r=ra(e.cachedContentTokenCount),s=ra(e.candidatesTokenCount),i=ra(e.thoughtsTokenCount);t.totalInputTokens+=n,t.totalCachedInputTokens+=r,t.totalOutputTokens+=s,t.totalReasoningOutputTokens+=i,t.lastInputTokens=n,t.lastTokenUsage={inputTokens:Math.max(n-r,0),cachedInputTokens:r,outputTokens:s,reasoningOutputTokens:i,totalTokens:ra(e.totalTokenCount)||n+s}}function zU(t){return{totalInputTokens:t.observed?t.totalInputTokens:void 0,totalCachedInputTokens:t.observed?t.totalCachedInputTokens:void 0,totalOutputTokens:t.observed?t.totalOutputTokens:void 0,totalReasoningOutputTokens:t.observed?t.totalReasoningOutputTokens:void 0,lastInputTokens:t.lastInputTokens,lastTokenUsage:t.lastTokenUsage}}function ZS(t){return t.type==="user"||t.message?.role==="user"}function ek(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function tk(t){let e=t.message;return e?typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(n=>n.type==="text").map(n=>n.text||"").join(`
|
|
2294
2294
|
`):Array.isArray(e.parts)?e.parts.filter(n=>!n.thought&&n.type!=="thinking").map(n=>n.text||"").join(`
|
|
2295
|
-
`):"":""}function nk(t){return t.model||t.message?.model}function YU(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:sk(t).filter(n=>!n.thought&&n.type!=="thinking"&&typeof n.text=="string"&&n.text.length>0).length}function sa(t,e=!1){if(t!==void 0){if(typeof t=="string")return t;try{return JSON.stringify(t,null,e?2:void 0)}catch{return String(t)}}}function QU(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return sa(e.output??e.error??t)}return sa(t)}function sk(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function rk(t,e,n){let r=t.name||"tool";return{role:"tool_use",timestamp:e,content:r,toolName:r,toolInput:sa(t.args,!0),toolInputData:Jt(t.args),toolCallId:t.id,model:n}}var ru,ik=L(()=>{"use strict";We();ru=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||jr(ie,".qwen")}async discoverSessions(){let e=jr(this.baseDir,"projects"),n;try{n=await nu(e)}catch{return[]}let r=[];for(let s of n){let i=jr(e,s,"chats"),o;try{o=await nu(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=jr(i,a);try{let u=await this.extractSummary(c,l);u&&r.push(u)}catch{}}}return r}async extractSummary(e,n){let r=!1,s=await De(e),i="(unknown)",o,a,l,c,u=0;for await(let d of Ie(e)){if(r=!0,d.cwd&&(i=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(i=d.cwd,d.version&&(a=d.version),d.model&&(o=d.model)),ZS(d)){let m=tk(d).trim();m&&(l||(l=z(m,80)),c=z(m,80),u++)}if(ek(d)){let m=nk(d);m&&(o=m),u+=YU(d)}}return r?{provider:"qwen",sessionId:n,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e}:null}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;let r=QS(n,".jsonl");return this.loadFromFile(n,r)}async loadFromFile(e,n){let r=await De(e),s="(unknown)",i,o,a,l,c,u,d=[],m=VU();for await(let p of Ie(e)){if(KU(m,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let f=p.message,g=p.timestamp?new Date(p.timestamp):r.modifiedAt;if(p.type==="tool_result"){let h=sk(p).filter(y=>y.functionResponse!==void 0);h.length===0&&p.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:g,content:sa(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let y of h){let b=y.functionResponse,_=QU(b.response),v=sa(p.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:g,content:v??_??p.toolCallResult?.status??"tool result",toolName:b.name,toolCallId:p.toolCallResult?.callId??b.id,..._!==void 0?{toolDetailedContent:_}:{}})}}else if(ZS(p)){let h=tk(p);h.trim()&&(c||(c=z(h.trim(),80)),u=z(h.trim(),80)),d.push({role:"user",timestamp:g,content:h})}else if(ek(p)){let h=nk(p);if(h&&(i=h),Array.isArray(f.content))for(let y of f.content)y.type==="text"&&y.text?d.push({role:"assistant",timestamp:g,content:y.text,model:h}):y.type==="thinking"&&y.thinking?d.push({role:"thinking",timestamp:g,content:y.thinking}):y.functionCall&&d.push(rk(y.functionCall,g,h));else if(typeof f.content=="string")d.push({role:"assistant",timestamp:g,content:f.content,model:h});else if(Array.isArray(f.parts))for(let y of f.parts)if(y.thought||y.type==="thinking"){let b=y.thinking||y.text;b&&d.push({role:"thinking",timestamp:g,content:b})}else y.functionCall?d.push(rk(y.functionCall,g,h)):y.text&&d.push({role:"assistant",timestamp:g,content:y.text,model:h})}}return{provider:"qwen",sessionId:n,slug:l,cwd:s,createdAt:r.createdAt,modifiedAt:r.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...zU(m),messages:d}}async resolveSessionPath(e){let n=jr(this.baseDir,"projects");try{let r=await nu(n),s=[];for(let i of r){let o=jr(n,i,"chats",`${e}.jsonl`);try{return await GU(o,{flag:"r"}),o}catch{continue}}for(let i of r){let o=jr(n,i,"chats"),a;try{a=await nu(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;QS(l,".jsonl").startsWith(e)&&s.push(jr(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;try{return await JU(n),!0}catch{return!1}}}});function ng(t){return new tg(t)}var tg,rg=L(()=>{"use strict";ik();rt();Yn();nt();tg=class extends _e{constructor(e){super({provider:new ru(e),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",ue,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:qc})}openSession(e){return Xc({...e,binary:"qwen"})}seedArgsFor(e){let n=super.seedArgsFor(e);return e?.model?[...n,"--model",e.model]:n}}});import{readdir as ok,readFile as ak,rm as lk,stat as ck}from"node:fs/promises";import{basename as sg,join as kn}from"node:path";import{fileURLToPath as ZU}from"node:url";async function e1(t){let e=await Promise.all(t.map(n=>De(n)));return{createdAt:new Date(Math.min(...e.map(n=>n.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(n=>n.modifiedAt.getTime())))}}function t1(t,e){if(!t)return e;let n=new Date(t);return Number.isNaN(n.getTime())?e:n}function uk(t){return t.type==="USER_INPUT"}function dk(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function n1(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function mk(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function pk(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function r1(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function s1(t){for await(let e of Ie(t)){let n=e.tool_calls?.map(s=>s.args)??[];for(let s of n){let i=i1(s);if(i)return i}let r=o1(e.content);if(r)return r}return null}function i1(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,n=e.Cwd??e.cwd??e.DirectoryPath;return typeof n!="string"?null:n.replace(/^"|"$/g,"")}function o1(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function a1(t,e){if(t.status!=="RUNNING"||!t.content)return;let n=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(t.content);if(!(!n||n[1]!==e)&&!(t.step_index===void 0||Number(n[3])!==t.step_index))return n[2]}function l1(t,e){let n=new Set;for(let r of e){let s=c1(t,n,r);if(!s)continue;n.add(s);let i=r.event.step_index===void 0?void 0:`agy-step-${r.event.step_index}`;s.message.toolCallId=i,s.message.backgroundTaskId=r.message.backgroundTaskId,r.message.toolName=s.name,r.message.toolCallId=i}}function c1(t,e,n){let r=n.message.backgroundTaskId===void 0?void 0:p1(n.event.content);if(r!==void 0)return fk(t.filter(i=>!e.has(i)&&f1(i)===r),n.event.step_index);let s=m1(n.event);if(s!==void 0)return fk(t.filter(i=>!e.has(i)&&u1(i.name,n.event.type)&&hk(d1(i))===s),n.event.step_index)}function fk(t,e){if(t.length===0)return;if(t.length===1)return t[0];if(e===void 0)return;let n=t.map(r=>({call:r,distance:r.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(e-r.stepIndex)})).sort((r,s)=>r.distance-s.distance);return n[0].distance<n[1].distance?n[0].call:void 0}function u1(t,e){return e==="VIEW_FILE"?t==="view_file":e!=="CODE_ACTION"?!1:t==="write_to_file"||t==="replace_file_content"||t==="multi_replace_file_content"}function d1(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function m1(t){if(!t.content)return;let e;return t.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(t.content)?.[1]:t.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(t.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(t.content)?.[1]),hk(e)}function hk(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return ZU(e)}catch{return}}function p1(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function f1(t){if(t.name==="run_command"){let e=t.input?.CommandLine;return typeof e=="string"?e:void 0}if(t.name==="schedule"){let e=t.input?.DurationSeconds,n=t.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof n!="string"?void 0:`Timer: ${e}s, Prompt: ${n}`}}function gk(t){if(t.endsWith(".db"))return sg(t,".db");let e="/brain/",n=t.indexOf(e);return n===-1?null:t.slice(n+e.length).split("/")[0]||null}var su,yk=L(()=>{"use strict";We();su=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||kn(ie,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:kn(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=kn(this.baseDir,"conversations"),n;try{n=await ok(e)}catch{return[]}let r=[];for(let s of n){if(!s.endsWith(".db"))continue;let i=sg(s,".db");try{let o=await this.extractSummary(i);o&&r.push(o)}catch{}}return r}conversationPath(e){return kn(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,n){return kn(this.baseDir,"brain",e,".system_generated","logs",n?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let n of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await ck(n),n}catch{}return null}async extractSummary(e){let n=this.conversationPath(e),r=await this.existingTranscriptPath(e),s=r??n,i=await e1([n,r].filter(Boolean)),o=await this.resolveCwd(e,r),a,l,c,u=0;if(r)for await(let d of Ie(r)){let m=pk(d.content);if(m&&(a=m),uk(d)){let p=mk(d.content).trim();p&&(l||(l=z(p,80)),c=z(p,80)),u++}else dk(d)&&d.content&&u++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:s,filePaths:r?[n,r]:[n]}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;let r=gk(n);if(!r)return null;let s=await this.extractSummary(r);if(!s)return null;let i=await this.existingTranscriptPath(r),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,u=[],d=[];if(i)for await(let m of Ie(i)){let p=t1(m.created_at,s.modifiedAt),f=pk(m.content);if(f&&(a=f),uk(m)){let g=mk(m.content),h=g.trim();h&&(l||(l=z(h,80)),c=z(h,80)),o.push({role:"user",timestamp:p,content:g});continue}if(Array.isArray(m.tool_calls))for(let g of m.tool_calls){let h=g.name||"tool",y=r1(g.args),b=Jt(g.args),_={role:"tool_use",timestamp:p,content:y,toolName:h,toolInput:y,toolInputData:b};o.push(_),u.push({name:h,stepIndex:m.step_index,input:b,message:_})}if(dk(m)&&m.content)o.push({role:"assistant",timestamp:p,content:m.content,model:a});else if(n1(m)&&m.content){let g=a1(m,r),h=g===void 0?null:await this.readTaskLog(r,g),y={role:"tool_result",timestamp:h?.modifiedAt??p,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:g,...h===null?{}:{toolDetailedContent:h.content}};o.push(y),d.push({event:m,message:y})}m.thinking&&o.push({role:"thinking",timestamp:p,content:m.thinking})}return l1(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(m=>m.role==="user"||m.role==="assistant").length,messages:o}}async resolveSessionPath(e){let n=this.conversationPath(e);try{return await ck(n),n}catch{}let r=kn(this.baseDir,"conversations");try{let s=[];for(let i of await ok(r)){if(!i.endsWith(".db"))continue;sg(i,".db").startsWith(e)&&s.push(kn(r,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;let r=gk(n);return r?(await lk(this.conversationPath(r),{force:!0}),await lk(kn(this.baseDir,"brain",r),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,n){let r=await this.cwdFromLastConversationCache(e);if(r)return r;if(n){let s=await s1(n);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let n=kn(this.baseDir,"cache","last_conversations.json");try{let r=JSON.parse(await ak(n,"utf8"));for(let[s,i]of Object.entries(r))if(i===e)return s}catch{}return null}async readTaskLog(e,n){if(!/^task-\d+$/.test(n))return null;let r=kn(this.baseDir,"brain",e,".system_generated","tasks",`${n}.log`);try{let[s,i]=await Promise.all([ak(r,"utf8"),De(r)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as g1}from"node:child_process";import{StringDecoder as _k}from"node:string_decoder";function iu(t){return async(e,n)=>{let r=Date.now(),s=t.buildArgs(e,n);t.assertArgs?.(s,n),n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await h1(t.label,n.binary,s,{cwd:n.cwd,env:je(n.env,n.cwd,n.sessionId),signal:n.signal});return n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:n.sessionId,durationMs:Date.now()-r}}}function h1(t,e,n,r){return new Promise((s,i)=>{if(r.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=g1(e,n,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new _k("utf8"),u=new _k("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=u.write(m)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{r.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,p)=>{if(r.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let f=p?`signal ${p}`:`exit code ${m}`,g=l.trim()||a.trim();i(new Error(gi(`${t} failed (${f})`,g?Ae(g,{provider:t}):"")))}),r.signal?.aborted?d():r.signal?.addEventListener("abort",d,{once:!0})})}var ig=L(()=>{"use strict";on();sn()});import{basename as y1}from"node:path";import{randomUUID as _1}from"node:crypto";function ag(t){return new og(t)}function b1(t){return t!==void 0&&t<=0?"0":t===void 0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var og,v1,lg=L(()=>{"use strict";yk();rt();nt();En();ig();og=class extends _e{constructor(e){super({provider:new su(e),protocol:{transport:"print",perTurnCancellation:"process"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",ue,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:v1})}async sendTurn(e,n){if(n.requireResume){let s=await this.resolvePath(n.sessionId);if(s===null||y1(s)!==`${n.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${n.sessionId}"`)}let r=await super.sendTurn(e,n);return n.permissionMode==="plan"?{...r,warnings:[...r.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:r}seedArgsFor(e){let n=[...super.seedArgsFor(e)];return e?.model&&n.push("--model",e.model),n}async seed(e,n){let r=_1(),s=`[lmctl-seed:${r}]`,i=await super.seed(e,{...n,prompt:Nc({flightToken:r,prompt:n?.prompt})});if(!i.success&&(i.errorCode==="ENOENT"||i.errorCode==="ABORT_ERR"))return i;let o=(await this.provider.discoverSessions()).filter(a=>a.firstUserMessage?.startsWith(s));if(i.success&&o.length===1)return{...i,sessionId:o[0].sessionId};for(let a of o)await this.provider.deleteSession(a.sessionId);return{...i,success:!1,error:i.error??`agy seed created ${o.length} identifiable sessions; expected one`}}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},v1=iu({label:"agy",buildArgs:(t,e)=>{let n=[...e.sessionId?["--conversation",e.sessionId]:[],"-p",t,"--dangerously-skip-permissions","--print-timeout",b1(e.timeoutMs)];return e.model&&n.push("--model",e.model),n},assertArgs:(t,e)=>qe("agy",t,e.permissionMode??"yolo")})});import{existsSync as ia,readdirSync as w1,statSync as vk}from"node:fs";import{readdir as cg,rm as E1}from"node:fs/promises";import bk,{join as Rn}from"node:path";function T1(t){if(t.length===0)throw new Error("cannot encode an empty project path");let e="",n=!1;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=String.fromCharCode(i);o==="/"||o==="\\"||o===":"?(n||(e+="-"),n=!0):o!=="~"&&/^[A-Za-z0-9._-]$/.test(o)?(e+=o,n=!1):(e+="~"+i.toString(16).toUpperCase().padStart(4,"0"),n=!1)}return`--${(e.replace(/^-+/,"")||"root").slice(0,251)}--`}function S1(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Ri(t,e){let n=e??(process.platform==="win32"?bk.win32:bk.posix),r=t,s="session.jsonl.zstd";if((t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl"))&&(r=n.dirname(t),s=n.basename(t)),!ia(r))return t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl")?t:n.join(t,s);try{let i=w1(r),o=[];for(let a of i){let l=/^session(?:\.v(\d+))?\.jsonl\.zstd$/.exec(a);if(l){let c=l[1]?parseInt(l[1],10):0;if(Number.isSafeInteger(c))try{let u=n.join(r,a);vk(u).isFile()&&o.push({name:a,version:c})}catch{}}}if(o.length>0)return o.sort((a,l)=>l.version-a.version),n.join(r,o[0].name)}catch{}try{if(ia(t)&&vk(t).isFile())return t}catch{}return n.join(r,s)}function ug(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let n of t)n&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join("")}function k1(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)n&&typeof n=="object"&&n.type==="reasoning"&&typeof n.text=="string"&&e.push(n.text);return e}function wk(t){let e=[];for(let n of t){let r=n.data??{},s=n.time?new Date(n.time):new Date(0);if(n.type==="user/message"){let i=r;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:ug(i.content)})}else if(n.type==="assistant/message"){let i=r.message;for(let o of k1(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:ug(i?.content),model:i?.source?.model})}else if(n.type==="tool/call"){let i=r,o;if(typeof i.arguments=="string")try{o=JSON.parse(i.arguments)}catch{}else i.arguments&&typeof i.arguments=="object"&&(o=i.arguments);e.push({role:"tool_use",timestamp:s,content:typeof i.arguments=="string"?i.arguments:JSON.stringify(i.arguments??{}),toolName:i.name,toolCallId:i.callId,toolInputData:o})}else if(n.type==="tool/result"){let i=r,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:ug(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function R1(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.type==="turn/end")return n.data?.reason?.kind==="completed"?"complete":"aborted";if(n.type==="turn/start")return"in_progress"}}function Ek(t,e,n){let r=t.find(p=>p.type==="session");if(!r)return null;let s=r,i=r.data,o=s.id??i?.id;if(!o)return null;let a;for(let p of t)if(p.type==="request/header"){let f=p.data?.header;f?.config?.model&&(a=f.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,m=n.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:m[0]?.content,lastUserMessage:m.at(-1)?.content,messageCount:n.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...I1(t)}}function I1(t){let e=new Map;for(let o of t){let a=o.data?.turn??null,l=e.get(a)??[];l.push(o),e.set(a,l)}let n=[],r=[];for(let o of e.values()){let a=new bi("",-1,new Set);a.update(o);let l=a.usage();l&&(n.push(l),r.push(a.lastUsage()))}if(!n.length)return{};let s=o=>{if(n.some(l=>l.invalidCounters||l[o]===null))return;let a=n.reduce((l,c)=>l+c[o],0);return Number.isSafeInteger(a)?a:void 0},i=r.at(-1);return{totalInputTokens:s("inputUncached"),totalCachedInputTokens:s("cacheRead"),totalOutputTokens:s("output"),totalReasoningOutputTokens:s("reasoning"),lastInputTokens:i.inputUncached!==null&&i.cacheRead!==null?i.inputUncached+i.cacheRead:void 0,lastTokenUsage:{totalTokens:i.inputUncached!==null&&i.cacheRead!==null&&i.output!==null?i.inputUncached+i.cacheRead+i.output:void 0,inputTokens:i.inputUncached??void 0,cachedInputTokens:i.cacheRead??void 0,outputTokens:i.output??void 0,reasoningOutputTokens:i.reasoning??void 0}}}var ou,Tk=L(()=>{"use strict";Lc();We();wl();ou=class{name="dsh";sessionsDir;constructor(e={}){let n=e.dshHome||process.env.DSH_HOME||Rn(ie,".dsh");this.sessionsDir=Rn(n,"sessions")}async discoverSessions(){let e=[],n;try{n=await cg(this.sessionsDir)}catch{return[]}for(let r of n){let s;try{s=await cg(Rn(this.sessionsDir,r))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(r,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let n=await this.findSessionDir(e);if(!n)return null;let r=await this.readRecords(n.cwdDir,n.sessionDir);if(r.length===0)return null;let s=wk(r),i=Ek(r,n.filePath,s);return i?{...i,turnStatus:R1(r),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let n=await this.findSessionDir(e);return n?(await E1(Rn(this.sessionsDir,n.cwdDir,n.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,n){let r=T1(e),s=S1(e),i=r,o=Rn(this.sessionsDir,r,n),a=Rn(this.sessionsDir,s,n);!ia(o)&&ia(a)&&(i=s);let l=Rn(this.sessionsDir,i,n);return Ri(l)}async findSessionDir(e){let n;try{n=await cg(this.sessionsDir)}catch{return null}for(let r of n){let s=e,i=Rn(this.sessionsDir,r,s);try{let o=Ri(i);if(ia(o))return{cwdDir:r,sessionDir:s,filePath:o}}catch{}}return null}async readRecords(e,n){let{readFile:r}=await import("node:fs/promises"),s=Rn(this.sessionsDir,e,n),i=Ri(s),o=await r(i),a=bl(o),l=[];for(let c of a.split(`
|
|
2295
|
+
`):"":""}function nk(t){return t.model||t.message?.model}function YU(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:sk(t).filter(n=>!n.thought&&n.type!=="thinking"&&typeof n.text=="string"&&n.text.length>0).length}function sa(t,e=!1){if(t!==void 0){if(typeof t=="string")return t;try{return JSON.stringify(t,null,e?2:void 0)}catch{return String(t)}}}function QU(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return sa(e.output??e.error??t)}return sa(t)}function sk(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function rk(t,e,n){let r=t.name||"tool";return{role:"tool_use",timestamp:e,content:r,toolName:r,toolInput:sa(t.args,!0),toolInputData:Jt(t.args),toolCallId:t.id,model:n}}var ru,ik=L(()=>{"use strict";We();ru=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||jr(ie,".qwen")}async discoverSessions(){let e=jr(this.baseDir,"projects"),n;try{n=await nu(e)}catch{return[]}let r=[];for(let s of n){let i=jr(e,s,"chats"),o;try{o=await nu(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=jr(i,a);try{let u=await this.extractSummary(c,l);u&&r.push(u)}catch{}}}return r}async extractSummary(e,n){let r=!1,s=await De(e),i="(unknown)",o,a,l,c,u=0;for await(let d of Ie(e)){if(r=!0,d.cwd&&(i=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(i=d.cwd,d.version&&(a=d.version),d.model&&(o=d.model)),ZS(d)){let m=tk(d).trim();m&&(l||(l=z(m,80)),c=z(m,80),u++)}if(ek(d)){let m=nk(d);m&&(o=m),u+=YU(d)}}return r?{provider:"qwen",sessionId:n,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e}:null}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;let r=QS(n,".jsonl");return this.loadFromFile(n,r)}async loadFromFile(e,n){let r=await De(e),s="(unknown)",i,o,a,l,c,u,d=[],m=VU();for await(let p of Ie(e)){if(KU(m,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let f=p.message,g=p.timestamp?new Date(p.timestamp):r.modifiedAt;if(p.type==="tool_result"){let h=sk(p).filter(y=>y.functionResponse!==void 0);h.length===0&&p.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:g,content:sa(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let y of h){let b=y.functionResponse,_=QU(b.response),v=sa(p.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:g,content:v??_??p.toolCallResult?.status??"tool result",toolName:b.name,toolCallId:p.toolCallResult?.callId??b.id,..._!==void 0?{toolDetailedContent:_}:{}})}}else if(ZS(p)){let h=tk(p);h.trim()&&(c||(c=z(h.trim(),80)),u=z(h.trim(),80)),d.push({role:"user",timestamp:g,content:h})}else if(ek(p)){let h=nk(p);if(h&&(i=h),Array.isArray(f.content))for(let y of f.content)y.type==="text"&&y.text?d.push({role:"assistant",timestamp:g,content:y.text,model:h}):y.type==="thinking"&&y.thinking?d.push({role:"thinking",timestamp:g,content:y.thinking}):y.functionCall&&d.push(rk(y.functionCall,g,h));else if(typeof f.content=="string")d.push({role:"assistant",timestamp:g,content:f.content,model:h});else if(Array.isArray(f.parts))for(let y of f.parts)if(y.thought||y.type==="thinking"){let b=y.thinking||y.text;b&&d.push({role:"thinking",timestamp:g,content:b})}else y.functionCall?d.push(rk(y.functionCall,g,h)):y.text&&d.push({role:"assistant",timestamp:g,content:y.text,model:h})}}return{provider:"qwen",sessionId:n,slug:l,cwd:s,createdAt:r.createdAt,modifiedAt:r.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...zU(m),messages:d}}async resolveSessionPath(e){let n=jr(this.baseDir,"projects");try{let r=await nu(n),s=[];for(let i of r){let o=jr(n,i,"chats",`${e}.jsonl`);try{return await GU(o,{flag:"r"}),o}catch{continue}}for(let i of r){let o=jr(n,i,"chats"),a;try{a=await nu(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;QS(l,".jsonl").startsWith(e)&&s.push(jr(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;try{return await JU(n),!0}catch{return!1}}}});function ng(t){return new tg(t)}var tg,rg=L(()=>{"use strict";ik();rt();Yn();ze();tg=class extends _e{constructor(e){super({provider:new ru(e),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",ce,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:qc})}openSession(e){return Xc({...e,binary:"qwen"})}seedArgsFor(e){let n=super.seedArgsFor(e);return e?.model?[...n,"--model",e.model]:n}}});import{readdir as ok,readFile as ak,rm as lk,stat as ck}from"node:fs/promises";import{basename as sg,join as kn}from"node:path";import{fileURLToPath as ZU}from"node:url";async function e1(t){let e=await Promise.all(t.map(n=>De(n)));return{createdAt:new Date(Math.min(...e.map(n=>n.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(n=>n.modifiedAt.getTime())))}}function t1(t,e){if(!t)return e;let n=new Date(t);return Number.isNaN(n.getTime())?e:n}function uk(t){return t.type==="USER_INPUT"}function dk(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function n1(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function mk(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function pk(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function r1(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function s1(t){for await(let e of Ie(t)){let n=e.tool_calls?.map(s=>s.args)??[];for(let s of n){let i=i1(s);if(i)return i}let r=o1(e.content);if(r)return r}return null}function i1(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,n=e.Cwd??e.cwd??e.DirectoryPath;return typeof n!="string"?null:n.replace(/^"|"$/g,"")}function o1(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function a1(t,e){if(t.status!=="RUNNING"||!t.content)return;let n=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(t.content);if(!(!n||n[1]!==e)&&!(t.step_index===void 0||Number(n[3])!==t.step_index))return n[2]}function l1(t,e){let n=new Set;for(let r of e){let s=c1(t,n,r);if(!s)continue;n.add(s);let i=r.event.step_index===void 0?void 0:`agy-step-${r.event.step_index}`;s.message.toolCallId=i,s.message.backgroundTaskId=r.message.backgroundTaskId,r.message.toolName=s.name,r.message.toolCallId=i}}function c1(t,e,n){let r=n.message.backgroundTaskId===void 0?void 0:p1(n.event.content);if(r!==void 0)return fk(t.filter(i=>!e.has(i)&&f1(i)===r),n.event.step_index);let s=m1(n.event);if(s!==void 0)return fk(t.filter(i=>!e.has(i)&&u1(i.name,n.event.type)&&hk(d1(i))===s),n.event.step_index)}function fk(t,e){if(t.length===0)return;if(t.length===1)return t[0];if(e===void 0)return;let n=t.map(r=>({call:r,distance:r.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(e-r.stepIndex)})).sort((r,s)=>r.distance-s.distance);return n[0].distance<n[1].distance?n[0].call:void 0}function u1(t,e){return e==="VIEW_FILE"?t==="view_file":e!=="CODE_ACTION"?!1:t==="write_to_file"||t==="replace_file_content"||t==="multi_replace_file_content"}function d1(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function m1(t){if(!t.content)return;let e;return t.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(t.content)?.[1]:t.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(t.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(t.content)?.[1]),hk(e)}function hk(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return ZU(e)}catch{return}}function p1(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function f1(t){if(t.name==="run_command"){let e=t.input?.CommandLine;return typeof e=="string"?e:void 0}if(t.name==="schedule"){let e=t.input?.DurationSeconds,n=t.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof n!="string"?void 0:`Timer: ${e}s, Prompt: ${n}`}}function gk(t){if(t.endsWith(".db"))return sg(t,".db");let e="/brain/",n=t.indexOf(e);return n===-1?null:t.slice(n+e.length).split("/")[0]||null}var su,yk=L(()=>{"use strict";We();su=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||kn(ie,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:kn(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=kn(this.baseDir,"conversations"),n;try{n=await ok(e)}catch{return[]}let r=[];for(let s of n){if(!s.endsWith(".db"))continue;let i=sg(s,".db");try{let o=await this.extractSummary(i);o&&r.push(o)}catch{}}return r}conversationPath(e){return kn(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,n){return kn(this.baseDir,"brain",e,".system_generated","logs",n?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let n of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await ck(n),n}catch{}return null}async extractSummary(e){let n=this.conversationPath(e),r=await this.existingTranscriptPath(e),s=r??n,i=await e1([n,r].filter(Boolean)),o=await this.resolveCwd(e,r),a,l,c,u=0;if(r)for await(let d of Ie(r)){let m=pk(d.content);if(m&&(a=m),uk(d)){let p=mk(d.content).trim();p&&(l||(l=z(p,80)),c=z(p,80)),u++}else dk(d)&&d.content&&u++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:s,filePaths:r?[n,r]:[n]}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;let r=gk(n);if(!r)return null;let s=await this.extractSummary(r);if(!s)return null;let i=await this.existingTranscriptPath(r),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,u=[],d=[];if(i)for await(let m of Ie(i)){let p=t1(m.created_at,s.modifiedAt),f=pk(m.content);if(f&&(a=f),uk(m)){let g=mk(m.content),h=g.trim();h&&(l||(l=z(h,80)),c=z(h,80)),o.push({role:"user",timestamp:p,content:g});continue}if(Array.isArray(m.tool_calls))for(let g of m.tool_calls){let h=g.name||"tool",y=r1(g.args),b=Jt(g.args),_={role:"tool_use",timestamp:p,content:y,toolName:h,toolInput:y,toolInputData:b};o.push(_),u.push({name:h,stepIndex:m.step_index,input:b,message:_})}if(dk(m)&&m.content)o.push({role:"assistant",timestamp:p,content:m.content,model:a});else if(n1(m)&&m.content){let g=a1(m,r),h=g===void 0?null:await this.readTaskLog(r,g),y={role:"tool_result",timestamp:h?.modifiedAt??p,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:g,...h===null?{}:{toolDetailedContent:h.content}};o.push(y),d.push({event:m,message:y})}m.thinking&&o.push({role:"thinking",timestamp:p,content:m.thinking})}return l1(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(m=>m.role==="user"||m.role==="assistant").length,messages:o}}async resolveSessionPath(e){let n=this.conversationPath(e);try{return await ck(n),n}catch{}let r=kn(this.baseDir,"conversations");try{let s=[];for(let i of await ok(r)){if(!i.endsWith(".db"))continue;sg(i,".db").startsWith(e)&&s.push(kn(r,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let n=await this.resolveSessionPath(e);if(!n)return!1;let r=gk(n);return r?(await lk(this.conversationPath(r),{force:!0}),await lk(kn(this.baseDir,"brain",r),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,n){let r=await this.cwdFromLastConversationCache(e);if(r)return r;if(n){let s=await s1(n);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let n=kn(this.baseDir,"cache","last_conversations.json");try{let r=JSON.parse(await ak(n,"utf8"));for(let[s,i]of Object.entries(r))if(i===e)return s}catch{}return null}async readTaskLog(e,n){if(!/^task-\d+$/.test(n))return null;let r=kn(this.baseDir,"brain",e,".system_generated","tasks",`${n}.log`);try{let[s,i]=await Promise.all([ak(r,"utf8"),De(r)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as g1}from"node:child_process";import{StringDecoder as _k}from"node:string_decoder";function iu(t){return async(e,n)=>{let r=Date.now(),s=t.buildArgs(e,n);t.assertArgs?.(s,n),n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await h1(t.label,n.binary,s,{cwd:n.cwd,env:je(n.env,n.cwd,n.sessionId),signal:n.signal});return n.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:n.sessionId,durationMs:Date.now()-r}}}function h1(t,e,n,r){return new Promise((s,i)=>{if(r.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=g1(e,n,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new _k("utf8"),u=new _k("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=u.write(m)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{r.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,p)=>{if(r.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let f=p?`signal ${p}`:`exit code ${m}`,g=l.trim()||a.trim();i(new Error(gi(`${t} failed (${f})`,g?Ae(g,{provider:t}):"")))}),r.signal?.aborted?d():r.signal?.addEventListener("abort",d,{once:!0})})}var ig=L(()=>{"use strict";on();sn()});import{basename as y1}from"node:path";import{randomUUID as _1}from"node:crypto";function ag(t){return new og(t)}function b1(t){return t!==void 0&&t<=0?"0":t===void 0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var og,v1,lg=L(()=>{"use strict";yk();rt();ze();Tn();ig();og=class extends _e{constructor(e){super({provider:new su(e),protocol:{transport:"print",perTurnCancellation:"process"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",ce,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:v1})}async sendTurn(e,n){if(n.requireResume){let s=await this.resolvePath(n.sessionId);if(s===null||y1(s)!==`${n.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${n.sessionId}"`)}let r=await super.sendTurn(e,n);return n.permissionMode==="plan"?{...r,warnings:[...r.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:r}seedArgsFor(e){let n=[...super.seedArgsFor(e)];return e?.model&&n.push("--model",e.model),n}async seed(e,n){let r=_1(),s=`[lmctl-seed:${r}]`,i=await super.seed(e,{...n,prompt:Nc({flightToken:r,prompt:n?.prompt})});if(!i.success&&(i.errorCode==="ENOENT"||i.errorCode==="ABORT_ERR"))return i;let o=(await this.provider.discoverSessions()).filter(a=>a.firstUserMessage?.startsWith(s));if(i.success&&o.length===1)return{...i,sessionId:o[0].sessionId};for(let a of o)await this.provider.deleteSession(a.sessionId);return{...i,success:!1,error:i.error??`agy seed created ${o.length} identifiable sessions; expected one`}}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},v1=iu({label:"agy",buildArgs:(t,e)=>{let n=[...e.sessionId?["--conversation",e.sessionId]:[],"-p",t,"--dangerously-skip-permissions","--print-timeout",b1(e.timeoutMs)];return e.model&&n.push("--model",e.model),n},assertArgs:(t,e)=>qe("agy",t,e.permissionMode??"yolo")})});import{existsSync as ia,readdirSync as w1,statSync as vk}from"node:fs";import{readdir as cg,rm as E1}from"node:fs/promises";import bk,{join as Rn}from"node:path";function T1(t){if(t.length===0)throw new Error("cannot encode an empty project path");let e="",n=!1;for(let s=0;s<t.length;s++){let i=t.charCodeAt(s),o=String.fromCharCode(i);o==="/"||o==="\\"||o===":"?(n||(e+="-"),n=!0):o!=="~"&&/^[A-Za-z0-9._-]$/.test(o)?(e+=o,n=!1):(e+="~"+i.toString(16).toUpperCase().padStart(4,"0"),n=!1)}return`--${(e.replace(/^-+/,"")||"root").slice(0,251)}--`}function S1(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Ri(t,e){let n=e??(process.platform==="win32"?bk.win32:bk.posix),r=t,s="session.jsonl.zstd";if((t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl"))&&(r=n.dirname(t),s=n.basename(t)),!ia(r))return t.endsWith(".jsonl.zstd")||t.endsWith(".jsonl")?t:n.join(t,s);try{let i=w1(r),o=[];for(let a of i){let l=/^session(?:\.v(\d+))?\.jsonl\.zstd$/.exec(a);if(l){let c=l[1]?parseInt(l[1],10):0;if(Number.isSafeInteger(c))try{let u=n.join(r,a);vk(u).isFile()&&o.push({name:a,version:c})}catch{}}}if(o.length>0)return o.sort((a,l)=>l.version-a.version),n.join(r,o[0].name)}catch{}try{if(ia(t)&&vk(t).isFile())return t}catch{}return n.join(r,s)}function ug(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let n of t)n&&typeof n=="object"&&n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join("")}function k1(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)n&&typeof n=="object"&&n.type==="reasoning"&&typeof n.text=="string"&&e.push(n.text);return e}function wk(t){let e=[];for(let n of t){let r=n.data??{},s=n.time?new Date(n.time):new Date(0);if(n.type==="user/message"){let i=r;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:ug(i.content)})}else if(n.type==="assistant/message"){let i=r.message;for(let o of k1(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:ug(i?.content),model:i?.source?.model})}else if(n.type==="tool/call"){let i=r,o;if(typeof i.arguments=="string")try{o=JSON.parse(i.arguments)}catch{}else i.arguments&&typeof i.arguments=="object"&&(o=i.arguments);e.push({role:"tool_use",timestamp:s,content:typeof i.arguments=="string"?i.arguments:JSON.stringify(i.arguments??{}),toolName:i.name,toolCallId:i.callId,toolInputData:o})}else if(n.type==="tool/result"){let i=r,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:ug(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function R1(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.type==="turn/end")return n.data?.reason?.kind==="completed"?"complete":"aborted";if(n.type==="turn/start")return"in_progress"}}function Ek(t,e,n){let r=t.find(p=>p.type==="session");if(!r)return null;let s=r,i=r.data,o=s.id??i?.id;if(!o)return null;let a;for(let p of t)if(p.type==="request/header"){let f=p.data?.header;f?.config?.model&&(a=f.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,m=n.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:m[0]?.content,lastUserMessage:m.at(-1)?.content,messageCount:n.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...I1(t)}}function I1(t){let e=new Map;for(let o of t){let a=o.data?.turn??null,l=e.get(a)??[];l.push(o),e.set(a,l)}let n=[],r=[];for(let o of e.values()){let a=new bi("",-1,new Set);a.update(o);let l=a.usage();l&&(n.push(l),r.push(a.lastUsage()))}if(!n.length)return{};let s=o=>{if(n.some(l=>l.invalidCounters||l[o]===null))return;let a=n.reduce((l,c)=>l+c[o],0);return Number.isSafeInteger(a)?a:void 0},i=r.at(-1);return{totalInputTokens:s("inputUncached"),totalCachedInputTokens:s("cacheRead"),totalOutputTokens:s("output"),totalReasoningOutputTokens:s("reasoning"),lastInputTokens:i.inputUncached!==null&&i.cacheRead!==null?i.inputUncached+i.cacheRead:void 0,lastTokenUsage:{totalTokens:i.inputUncached!==null&&i.cacheRead!==null&&i.output!==null?i.inputUncached+i.cacheRead+i.output:void 0,inputTokens:i.inputUncached??void 0,cachedInputTokens:i.cacheRead??void 0,outputTokens:i.output??void 0,reasoningOutputTokens:i.reasoning??void 0}}}var ou,Tk=L(()=>{"use strict";Lc();We();wl();ou=class{name="dsh";sessionsDir;constructor(e={}){let n=e.dshHome||process.env.DSH_HOME||Rn(ie,".dsh");this.sessionsDir=Rn(n,"sessions")}async discoverSessions(){let e=[],n;try{n=await cg(this.sessionsDir)}catch{return[]}for(let r of n){let s;try{s=await cg(Rn(this.sessionsDir,r))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(r,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let n=await this.findSessionDir(e);if(!n)return null;let r=await this.readRecords(n.cwdDir,n.sessionDir);if(r.length===0)return null;let s=wk(r),i=Ek(r,n.filePath,s);return i?{...i,turnStatus:R1(r),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let n=await this.findSessionDir(e);return n?(await E1(Rn(this.sessionsDir,n.cwdDir,n.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,n){let r=T1(e),s=S1(e),i=r,o=Rn(this.sessionsDir,r,n),a=Rn(this.sessionsDir,s,n);!ia(o)&&ia(a)&&(i=s);let l=Rn(this.sessionsDir,i,n);return Ri(l)}async findSessionDir(e){let n;try{n=await cg(this.sessionsDir)}catch{return null}for(let r of n){let s=e,i=Rn(this.sessionsDir,r,s);try{let o=Ri(i);if(ia(o))return{cwdDir:r,sessionDir:s,filePath:o}}catch{}}return null}async readRecords(e,n){let{readFile:r}=await import("node:fs/promises"),s=Rn(this.sessionsDir,e,n),i=Ri(s),o=await r(i),a=bl(o),l=[];for(let c of a.split(`
|
|
2296
2296
|
`))if(c.trim())try{let u=JSON.parse(c);if(u.type?.endsWith("-chunks")||u.type==="assistant/chunk"&&u.data?.chunk?.type!=="usage")continue;l.push(u)}catch{}return l}async readSummary(e,n){let r=Rn(this.sessionsDir,e,n),s=Ri(r),i=await this.readRecords(e,n);return i.length===0?null:Ek(i,s,wk(i))}}});import{spawn as x1}from"node:child_process";import{randomUUID as A1}from"node:crypto";function dg(t,e=[]){if(t==null)return t;if(typeof t=="string"){let n=t;for(let r of e)r&&typeof r=="string"&&r.length>=8&&n.includes(r)&&(n=n.replaceAll(r,"[REDACTED]"));return n=n.replace(/(?:sk-|dsh-)[A-Za-z0-9_\-\.]+/gi,"[REDACTED]"),n=n.replace(/(?:token=)[A-Za-z0-9_\-\.]+/gi,"token=[REDACTED]"),n=n.replace(/bearer\s+[A-Za-z0-9_\-\.]+/gi,"Bearer [REDACTED]"),n}if(Array.isArray(t))return t.map(n=>dg(n,e));if(typeof t=="object"){let n={};for(let[r,s]of Object.entries(t))/api[_-]?key|secret|token|password|auth|authorization|credential|cookie/i.test(r)?n[r]="[REDACTED]":n[r]=dg(s,e);return n}return t}function N1(t){let e;try{e=new URL(t)}catch{throw new Error("invalid dsh boot URL: malformed URL")}if(e.protocol!=="http:")throw new Error(`invalid dsh boot URL scheme "${e.protocol}": must be http:`);if(e.username||e.password)throw new Error("invalid dsh boot URL: userinfo credentials are not allowed");let n=e.hostname;if(!(n==="127.0.0.1"||n==="localhost"||n==="::1"||n==="[::1]"))throw new Error(`invalid dsh boot URL host "${n}": loopback host (127.0.0.1 or localhost) required`);return e}function kk(t,e=2e3){if(!t||t.exitCode!==null||t.signalCode!==null)return;try{t.kill("SIGTERM")}catch{}let n,r=()=>{n!==void 0&&(clearTimeout(n),n=void 0)};if(t.once("exit",r),t.exitCode!==null||t.signalCode!==null){r();return}n=setTimeout(()=>{n=void 0;try{t.exitCode===null&&t.signalCode===null&&t.kill("SIGKILL")}catch{}},e),n.unref()}async function au(t,e=n=>mg.spawn(n)){if(Ur){let n=await Ur.catch(()=>{});if(n?.alive)return n;Ur=void 0}return Ur=e(t),Ur}async function oa(){if(!Ur)return;(await Ur.catch(()=>{}))?.shutdown(),Ur=void 0}var C1,Sk,Qn,mg,Ur,Rk=L(()=>{"use strict";sn();C1=/dsh web:\s*(https?:\/\/\S+)/,Sk=2e4;Qn=class t extends Error{method;detail;constructor(e,n,r=[]){let s=dg(n,r),i=typeof s=="string"?s:JSON.stringify(s);super(`dsh RPC ${e} failed: ${i}`),this.name="DshRpcCallError",this.method=e,this.detail=s,Object.setPrototypeOf(this,t.prototype)}};mg=class t{constructor(e,n,r,s=!1,i){this.baseUrl=e;this.child=n;this.cookie=r;this.isV2=s;this.tokenUrl=i;if(this.cookie&&this.recordSecret(this.cookie),this.tokenUrl){this.recordSecret(this.tokenUrl);try{let a=new URL(this.tokenUrl).searchParams.get("token");a&&this.recordSecret(a)}catch{}}}static MAX_RETAINED_SECRETS=8;cookieExchangePromise;knownSecrets=[];recordSecret(e){if(!e||typeof e!="string"||e.length<8)return;let n=r=>{if(r.length<8)return;let s=this.knownSecrets.indexOf(r);for(s!==-1&&this.knownSecrets.splice(s,1),this.knownSecrets.push(r);this.knownSecrets.length>t.MAX_RETAINED_SECRETS;)this.knownSecrets.shift()};if(n(e),e.includes("=")){let r=e.split("=")[1];r&&r.length>=8&&n(r)}}getSecretsToRedact(e=[]){let n=new Set;for(let r of this.knownSecrets)r&&r.length>=8&&n.add(r);if(this.cookie&&this.cookie.length>=8){n.add(this.cookie);let r=this.cookie.split("=")[1];r&&r.length>=8&&n.add(r)}if(this.tokenUrl)try{let s=new URL(this.tokenUrl).searchParams.get("token");s&&s.length>=8&&n.add(s)}catch{}for(let r of e)if(r&&r.length>=8&&(n.add(r),r.includes("="))){let s=r.split("=")[1];s&&s.length>=8&&n.add(s)}return Array.from(n)}static forTesting(e,n){let r=e,s=n?.isV2??!1,i=n?.cookie;try{let o=new URL(e);o.searchParams.has("token")&&(s=!0,r=o.origin)}catch{}return new t(r,void 0,i,s,e)}static async fromBootUrl(e,n,r){let s=N1(e),i=s.searchParams.has("token"),o;if(i)for(let a=0;a<5;a++){if(r?.aborted)throw new Error("dsh web boot aborted");try{let c=(await fetch(e,{redirect:"manual",signal:r})).headers.get("set-cookie");if(c){o=c.split(";")[0];break}}catch(l){if(r?.aborted)throw l;await new Promise(c=>setTimeout(c,100))}}return new t(s.origin,n,o,i,e)}async ensureCookie(e=!1){return this.tokenUrl?this.cookie&&!e?this.cookie:(this.cookieExchangePromise||(this.cookieExchangePromise=(async()=>{for(let n=0;n<5;n++)try{let r=AbortSignal.timeout(1e4),i=(await fetch(this.tokenUrl,{redirect:"manual",signal:r})).headers.get("set-cookie");if(i)return this.cookie=i.split(";")[0],this.recordSecret(this.cookie),this.cookie}catch{await new Promise(r=>setTimeout(r,100))}return this.cookie})().finally(()=>{this.cookieExchangePromise=void 0})),this.cookieExchangePromise):this.cookie}async rpc(e,n){this.isV2&&await this.ensureCookie();let r=this.cookie,s=r?[r]:[],i=`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.isV2?e.includes("/")?e:e.replace(/\./g,"/"):e.includes(".")?e:e.replace(/\//g,"."),a=n;if(this.isV2){let m=n;if(o==="session/prompt"&&m&&typeof m=="object"){let p=m;p.requestId||(m={...p,requestId:A1()})}m&&typeof m=="object"&&"args"in m?a=m:a={args:{request:m}}}let l={"content-type":"application/json"};this.cookie&&(l.cookie=this.cookie);let c;try{c=await fetch(`${this.baseUrl}/api/${o}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:i,method:o,payload:a}),redirect:"manual"})}catch(m){throw new Qn(e,`transport error: ${m instanceof Error?m.message:String(m)}`,this.getSecretsToRedact(s))}if(c.status>=300&&c.status<400)throw new Qn(e,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(s));if((c.status===401||c.status===403)&&this.isV2&&this.tokenUrl){let m=await this.ensureCookie(!0);if(m&&m!==l.cookie){l.cookie=m,s.push(m);try{c=await fetch(`${this.baseUrl}/api/${o}`,{method:"POST",headers:l,body:JSON.stringify({type:"client-request",rpcId:i,method:o,payload:a}),redirect:"manual"})}catch(p){throw new Qn(e,`transport error: ${p instanceof Error?p.message:String(p)}`,this.getSecretsToRedact(s))}if(c.status>=300&&c.status<400)throw new Qn(e,`redirects are not permitted (HTTP ${c.status})`,this.getSecretsToRedact(s))}}let u;try{u=await c.json()}catch{u=void 0}if(!c.ok)throw new Qn(e,u??c.statusText,this.getSecretsToRedact(s));let d=u&&typeof u=="object"?u.result:void 0;if(!d||typeof d!="object"||typeof d.ok!="boolean")throw new Qn(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope",this.getSecretsToRedact(s));if(d.ok===!1)throw new Qn(e,d.error??d,this.getSecretsToRedact(s));return"value"in d?d.value:void 0}get alive(){return this.child!==void 0&&this.child.exitCode===null&&this.child.signalCode===null}shutdown(){this.child!==void 0&&this.alive&&kk(this.child,2e3)}static spawn(e){return new Promise((n,r)=>{let s=x1("dsh",["web","--no-open","--port","0"],{env:e,stdio:["ignore","pipe","pipe"]}),i=!1,o=!1,a="",l="",c="",u=new AbortController,d=p=>{i||(i=!0,clearTimeout(m),u.abort(),kk(s,2e3),r(p))},m=setTimeout(()=>{let p=[l?`stdout:
|
|
2297
2297
|
${l}`:"",c?`stderr:
|
|
2298
2298
|
${c}`:""].filter(Boolean).join(`
|
|
2299
2299
|
`);d(new Error(`dsh web sidecar did not report a boot URL within ${Sk}ms `+(p?`
|
|
2300
2300
|
${Ae(p,{provider:"dsh"})}`:"(no output captured)")))},Sk);s.stdout?.on("data",p=>{let f=p.toString();if(l+=f,a+=f,i||o)return;let g=a.split(`
|
|
2301
2301
|
`);a=g.pop()??"";for(let h of g){let y=C1.exec(h);if(y){o=!0,t.fromBootUrl(y[1],s,u.signal).then(b=>{i||(i=!0,clearTimeout(m),n(b))},b=>{d(b instanceof Error?b:new Error(String(b)))});return}}}),s.stderr?.on("data",p=>{c+=p.toString()}),s.on("error",p=>{d(p)}),s.on("exit",(p,f)=>{let g=f?`signal ${f}`:`exit code ${p}`;d(new Error(gi(`dsh web exited before reporting a boot URL (${g})`,c.trim()?Ae(c,{provider:"dsh"}):"")))})})}}});import{randomUUID as Ik}from"node:crypto";import{existsSync as xk,statSync as O1}from"node:fs";import{readFile as L1,mkdir as M1}from"node:fs/promises";function yg(t){return new hg(t)}function gg(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function D1(t){let e=t?.kind??"unknown",n=t?.error?.message;return n?`dsh turn ended with reason=${e}: ${n}`:`dsh turn ended with reason=${e} and no assistant text`}function lu(t){return t instanceof Error?t.message:String(t)}async function Ak(t,e){let n;try{n=await L1(t)}catch{return e?.(),[]}e&&lo(n).reduce((i,o)=>i+o.length,0)!==n.length&&e?.();let r=bl(n),s=[];for(let i of r.split(`
|
|
2302
|
-
`))if(i.trim())try{let o=JSON.parse(i);o!==null&&typeof o=="object"&&!Array.isArray(o)&&s.push(o)}catch{e?.()}return s}function F1(t){let n=t.data?.message?.content;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=[];for(let s of n)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&r.push(s.text);return r.join("")}function cu(t,e){return Ri(t,e)}var pg,P1,fg,hg,_g=L(()=>{"use strict";Lc();vi();rt();Tk();wl();Rk();
|
|
2302
|
+
`))if(i.trim())try{let o=JSON.parse(i);o!==null&&typeof o=="object"&&!Array.isArray(o)&&s.push(o)}catch{e?.()}return s}function F1(t){let n=t.data?.message?.content;if(typeof n=="string")return n;if(!Array.isArray(n))return"";let r=[];for(let s of n)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&r.push(s.text);return r.join("")}function cu(t,e){return Ri(t,e)}var pg,P1,fg,hg,_g=L(()=>{"use strict";Lc();vi();rt();Tk();wl();Rk();ze();Tn();pg=new Map,P1=500,fg=8*60*60*1e3;hg=class extends _e{dshProvider;usageSeen=new Set;constructor(e){let n=new ou(e);super({provider:n,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(r,s)=>this.dshPromptTurn(r,s)}),this.dshProvider=n}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,n){await M1(e,{recursive:!0});let r=`session-${Ik()}`,s=gg(n?.env??process.env);qe("dsh",[],"yolo");try{let i;try{i=await au(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${lu(a)}`}}try{await i.rpc("session.create",{sessionId:r,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${lu(a)}`}}if(n?.model)try{await i.rpc("session.selectModel",{sessionId:r,provider:"deepseek-official",model:n.model})}catch(a){return{success:!1,error:`session.selectModel("${n.model}") failed: ${lu(a)}`}}let o=n?.prompt??ce;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}let a=await this.promptAndWait(i,e,r,o,fg,n?.signal);return{success:!0,sessionId:r,usage:a.usage}}catch(a){return{success:!1,sessionId:r,usage:a?.usage,error:`seed turn failed: ${lu(a)}`}}}finally{await oa()}}async dshPromptTurn(e,n){let r=Date.now();if(n.bundleSession!==void 0)return Kn(n.bundleSession,"dsh",n.sessionId,e,{onDelta:n.onDelta,onProgress:n.onProgress,signal:n.signal});let s=gg(n.env??process.env);qe("dsh",[],n.permissionMode??"yolo");let i=!n.sessionId,o=i?`session-${Ik()}`:n.sessionId,a;try{let l=await au(s);i&&await l.rpc("session.create",{sessionId:o,cwd:n.cwd}),n.model&&(await l.rpc("session.selectModel",{sessionId:o,provider:"deepseek-official",model:n.model}),n.onProgress?.({kind:"system",summary:`dsh model set to ${n.model}`})),n.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),a=await this.promptAndWait(l,n.cwd,o,e,n.timeoutMs??fg,n.signal)}finally{await oa()}return n.onProgress?.({kind:"system",summary:"dsh turn completed"}),{...a,sessionId:o,durationMs:Date.now()-r}}async openSession(e){let n=gg(e.env??process.env);qe("dsh",[],e.permissionMode??"yolo");let r=await au(n),s=cu(this.dshProvider.sessionFilePath(e.cwd,e.sessionId)),i=!1;try{i=xk(s)&&O1(s).isFile()}catch{i=!1}if(!i)throw await oa(),new Error(`dsh bundle: session file does not exist for session "${e.sessionId}" (${s}) \u2014 the session must exist before a bundle can resume it`);e.model&&await r.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let o=e.sessionId,a=this,l=0,c=!1,u=null,d=!1,m=!1,p=async()=>{m||(m=!0,await oa())};return{provider:"dsh",sessionId:o,get completedTurns(){return l},async sendTurn(f,g={}){if(c||u!==null)throw new Error("dsh bundle session is closed");if(d)throw new Error("dsh bundle session has a turn still in flight");if(g.signal?.aborted)throw new Error("Aborted");if(s=cu(s),!xk(s))throw new Error(`dsh bundle: session file for session "${o}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);d=!0;let h=Date.now();try{let y,b=a.promptAndWait(r,e.cwd,o,f,fg,g.signal,I=>{y=I});b.catch(()=>{});let _=()=>{},v=new Promise((I,T)=>{_=()=>{(async()=>{c=!0,await p()})().finally(()=>T(Object.assign(new Error("Aborted"),{usage:y,sessionId:o})))},g.signal?.addEventListener("abort",_,{once:!0})}),E;try{E=await Promise.race([b,v])}finally{g.signal?.removeEventListener("abort",_)}return l+=1,{...E,sessionId:o,durationMs:Date.now()-h}}finally{d=!1}},close(){return u!==null||(u=(async()=>{c=!0,await p()})()),u}}}async promptAndWait(e,n,r,s,i,o,a){let l=Date.now(),c=cu(this.dshProvider.sessionFilePath(n,r)),u=!1,d=await Ak(c,()=>{u=!0}),m=d.reduce((b,_)=>typeof _.seq=="number"&&Number.isSafeInteger(_.seq)?Math.max(b,_.seq):b,-1),p=new bi(r,m,this.usageSeen);u&&p.invalidateOwnership();let f=JSON.stringify([c,r]),g=pg.get(f)??new Set;if(g.size){p.invalidateOwnership();for(let b of g)b.invalidateOwnership()}g.add(p),pg.set(f,g),d.filter(b=>b.type==="turn/start"||b.type==="turn/end").at(-1)?.type==="turn/start"&&p.invalidateOwnership();let y;try{await e.rpc("session.prompt",{sessionId:r,mode:"queue",content:[{type:"text",text:s}]});let b=i>0?Date.now()+i:1/0;for(;;){c=cu(c);let _=await Ak(c),v=_.find(E=>E.type==="turn/end"&&(E.seq??-1)>m);if(_.length&&p.update(_,v?.seq??1/0),a?.(p.usage()),o?.aborted)throw new Error("Aborted");if(v){let E=v.data?.reason;E?.kind!=="completed"&&(y=E?.kind==="aborted"?"cancelled":"error");let I=[..._].reverse().find(N=>N.type==="assistant/message"&&(N.seq??-1)>m&&(N.seq??1/0)<=(v.seq??1/0)),T=I?F1(I):"";if(E?.kind!=="completed"&&!T)throw new Error(D1(E));p.finish();let k=p.usage();return{text:T,sessionId:r,durationMs:Date.now()-l,usage:k?{...k,...E?.kind==="completed"?{}:{outcome:E?.kind==="aborted"?"cancelled":"error"}}:void 0}}if(Date.now()>b)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(E=>setTimeout(E,P1))}}catch(b){if(p.finish(),b instanceof Error){let _=p.usage();Object.assign(b,{usage:_?{..._,outcome:y}:void 0,sessionId:r})}throw b}finally{g.delete(p),g.size||pg.delete(f)}}}});import{existsSync as $1}from"node:fs";import{join as Mk,resolve as j1}from"node:path";import{createRequire as U1}from"node:module";function H1(){return vg===null&&(vg=U1(import.meta.url)("node:sqlite").DatabaseSync),vg}function bg(t={}){return j1(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||Mk(ie,".hermes"))}function B1(t={}){return Mk(bg(t),"state.db")}function aa(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function St(t){return typeof t=="string"&&t.length>0?t:void 0}function W1(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Ok(t){return St(t.cwd)??St(W1(t.model_config).cwd)??"(unknown)"}function q1(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function X1(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string")return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Lk(t){let e=t.input_tokens??0,n=t.output_tokens??0,r=t.cache_read_tokens??0,s=t.cache_write_tokens??0,i=t.reasoning_tokens??0;return(t.message_count??0)>0&&e+n+r+s+i>0?{totalInputTokens:e,totalCachedInputTokens:r,totalCacheWriteInputTokens:s,totalOutputTokens:n,totalReasoningOutputTokens:i}:{}}var vg,Ck,Nk,uu,Pk=L(()=>{"use strict";We();Se();vg=null;Ck="acp";Nk=`id, source, model, model_config, started_at,
|
|
2303
2303
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
2304
2304
|
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;uu=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=B1(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!$1(this.dbPath))return null;let e=null;try{return e=new(H1())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(n){return e?.close(),X({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}}selectSessionRow(e,n){return e.prepare(`SELECT ${Nk} FROM sessions WHERE id = ? AND source = ?`).get(n,Ck)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let n=e.prepare(`SELECT ${Nk} FROM sessions
|
|
2305
2305
|
WHERE source = ?
|
|
2306
2306
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
2307
2307
|
LIMIT ?`).all(Ck,this.discoverLimit),r=[];for(let s of n){let i=this.previewTexts(e,s.id);r.push({provider:this.name,sessionId:s.id,slug:St(s.title),cwd:Ok(s),createdAt:aa(s.started_at),modifiedAt:aa(s.last_activity_at??s.started_at),model:St(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...Lk(s)})}return r}catch(n){return X({event:"hermes_discover_sessions_failed",provider:this.name,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),[]}finally{e.close()}}activeMessageRows(e,n){let r=new Set(e.prepare("PRAGMA table_info(messages)").all().map(a=>a.name)),i=`id, session_id, role, content, tool_call_id, tool_calls, tool_name,
|
|
2308
2308
|
timestamp, finish_reason${["_compressed_summary","display_kind"].filter(a=>r.has(a)).map(a=>`, ${a}`).join("")}`,o="WHERE session_id = ? AND role IN ('user', 'assistant', 'tool')";try{return e.prepare(`SELECT ${i} FROM messages ${o} AND active = 1 ORDER BY id ASC`).all(n)}catch(a){if(!/no such column/i.test(a instanceof Error?a.message:String(a)))throw a;return e.prepare(`SELECT ${i} FROM messages ${o} ORDER BY id ASC`).all(n)}}previewTexts(e,n){try{let[r,s]=["ASC","DESC"].map(i=>{let o=`SELECT content FROM messages WHERE session_id = ?
|
|
2309
|
-
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(n)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(n)}return a?z(a.content,80):void 0});return{first:r,last:s}}catch{return{}}}async loadSession(e){let n=this.openDb();if(!n)return null;try{let r=this.selectSessionRow(n,e);if(!r)return null;let s=this.activeMessageRows(n,e),i=[],o=[],a,l;for(let c of s){let u=aa(c.timestamp),d=c.content??"";if(c.role==="user"){d&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(d),d.length>0&&(a||(a=z(d,80)),l=z(d,80)),i.push({role:"user",timestamp:u,content:d||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:u,content:d,toolCallId:St(c.tool_call_id),toolName:St(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:St(r.model),stopReason:St(c.finish_reason)});for(let m of q1(c.tool_calls)){let p=X1(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:St(m.function?.name)??"tool_call",toolName:St(m.function?.name),toolCallId:St(m.call_id)??St(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Jt(p)})}}return{provider:this.name,sessionId:r.id,slug:St(r.title),cwd:Ok(r),createdAt:aa(r.started_at),modifiedAt:aa(r.last_activity_at??r.started_at),model:St(r.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:r.message_count??i.length,filePath:this.dbPath,...Lk(r),messages:i,userPrompts:o}}catch(r){return X({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),null}finally{n.close()}}async resolveSessionPath(e){let n=this.openDb();if(!n)return null;try{return this.selectSessionRow(n,e)?this.dbPath:null}catch{return null}finally{n.close()}}async deleteSession(e){return!1}}});import{mkdir as G1}from"node:fs/promises";function V1(t){return J1.test(t)}function Dk(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return K1}function Eg(t){return new wg(t)}var J1,K1,wg,Tg=L(()=>{"use strict";rt();Pk();Yn();nt();Se();J1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;K1="dont_ask";wg=class extends _e{hermesProvider;hermesHome;constructor(e){let n=new uu(e);super({provider:n,protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Hermes has no provider-side leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"hermes",seedArgs:[],resumeTemplate:"hermes --yolo --resume {{session_id}}",startTemplate:"hermes",transport:async(r,s)=>Tn(r,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:Dk(s.permissionMode)})}),this.hermesProvider=n,this.hermesHome=bg(e)}async openSession(e){return Sn({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:Dk(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,n){await G1(e,{recursive:!0});let r=[];if(n?.effort){let i="hermes has no ACP-level effort surface";X({event:"hermes_effort_ignored",provider:this.name,effort:n.effort,reason:i}),r.push(`hermes seed ignored effort=${n.effort}: ${i}`)}let s;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}s=await this.sendTurn(n?.prompt??ue,{sessionId:"",cwd:e,env:n?.env,signal:n?.signal,model:n?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return V1(s.sessionId)?(r.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,usage:s.usage,...r.length>0?{warnings:r}:{}}):(X({event:"hermes_seed_contract_violation",provider:this.name,session_id:s.sessionId,reason:"session/new did not return a UUID session id"}),{success:!1,error:`hermes ACP session/new did not return a UUID session id (got ${JSON.stringify(s.sessionId)})`})}}});import{readdir as Fk,rm as z1,stat as Y1}from"node:fs/promises";import{join as Sg}from"node:path";function kg(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function $k(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var du,jk=L(()=>{"use strict";We();du=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Sg(ie,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let n of await this.listSessionFiles())try{let r=await this.extractSummary(n);r&&e.push(r)}catch{}return e}async listSessionFiles(){let e;try{e=await Fk(this.baseDir)}catch{return[]}let n=[];for(let r of e){let s=Sg(this.baseDir,r);try{if(!(await Y1(s)).isDirectory())continue;for(let i of await Fk(s))i.endsWith(".jsonl")&&n.push(Sg(s,i))}catch{}}return n}async readHeader(e){for await(let n of Ie(e))return n.type==="session"?n:null;return null}async extractSummary(e){let n=await this.readHeader(e);if(!n)return null;let r=await De(e),s,i,o,a=0,l=0,c=0,u=0,d=0,m=0,p=0,f;for await(let g of Ie(e)){if(g.type==="model_change"&&g.provider&&g.modelId){s=`${g.provider}/${g.modelId}`;continue}if(g.type!=="message"||!g.message)continue;let h=g.message;if(h.provider&&h.model&&(s=`${h.provider}/${h.model}`),h.role==="user"){let y=kg(h).trim();y&&(i||(i=z(y,80)),o=z(y,80)),a++}else if(h.role==="assistant"){a++;let y=h.usage;y&&(l+=y.input??0,c+=y.cacheRead??0,u+=y.cacheWrite??0,d+=y.output??0,m+=y.reasoning??0,p=y.input??0,f={inputTokens:y.input,cachedInputTokens:y.cacheRead,cacheWriteInputTokens:y.cacheWrite,outputTokens:y.output,reasoningOutputTokens:y.reasoning,totalTokens:y.totalTokens})}}return{provider:"pi",sessionId:n.id,cwd:n.cwd??"(unknown)",createdAt:r.createdAt,modifiedAt:r.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:p,lastTokenUsage:f}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;let r=await this.extractSummary(n);if(!r)return null;let s=[],i=r.model;for await(let o of Ie(n)){if(o.type==="model_change"&&o.provider&&o.modelId){i=`${o.provider}/${o.modelId}`;continue}if(o.type!=="message"||!o.message)continue;let a=o.message;a.provider&&a.model&&(i=`${a.provider}/${a.model}`);let l=a.timestamp?new Date(a.timestamp):r.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:kg(a)});else if(a.role==="assistant"&&Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?s.push({role:"assistant",timestamp:l,content:c.text,model:i}):c.type==="thinking"&&c.thinking?s.push({role:"thinking",timestamp:l,content:c.thinking}):c.type==="toolCall"&&s.push({role:"tool_use",timestamp:l,content:$k(c.arguments),toolName:c.name??"tool",toolInput:$k(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:kg(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...r,model:i,messages:s}}async resolveSessionPath(e){let n=`_${e}.jsonl`,r=[];for(let s of await this.listSessionFiles()){if(s.endsWith(n))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&r.push(s)}return r.length===1?r[0]:null}async deleteSession(e){let n=await this.resolveSessionPath(e);return n?(await z1(n,{force:!0}),!0):!1}}});function Ig(t){return new Rg(t)}var Rg,Q1,xg=L(()=>{"use strict";jk();rt();nt();En();ig();Rg=class extends _e{constructor(e){super({provider:new du(e),protocol:{transport:"print",perTurnCancellation:"process"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"pi uses one-shot print turns; no streaming events are available."},binary:"pi",seedArgs:["-p",ue],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:Q1})}seedArgsFor(e){let n=[...super.seedArgsFor(e)];return e?.model&&n.push("--model",e.model),n}manualSeedHint(e){return{launchCommand:`cd ${e} && pi`,postLaunchNote:"Send the lmctl seed instruction, wait for the session file to write, then exit.",lsCommand:`lmctl ls --provider pi --sessiondir ${e}`}}},Q1=iu({label:"pi",buildArgs:(t,e)=>{let n=[...e.sessionId?["--session",e.sessionId]:[],"-p",t];return e.model&&n.push("--model",e.model),n},assertArgs:(t,e)=>qe("pi",t,e.permissionMode??"yolo")})});import{createHash as Z1}from"node:crypto";import{existsSync as eH,mkdirSync as Cg,readFileSync as tH,renameSync as nH,rmdirSync as Jk,statSync as rH,writeFileSync as sH}from"node:fs";import{dirname as Mg,join as Uk,resolve as Ag}from"node:path";function iH(t){return Z1("sha256").update(t).digest("hex").slice(0,8)}function oH(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function aH(t,e){let n=e?.prompt??"",r=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(n);return r!==null?r[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function Vk(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function mu(t){return Math.max(1,Math.ceil(t.length/4))}function xi(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Ag(e);let n=process.env.LMCTL_DB;return n!==void 0&&n.trim().length>0?Uk(Mg(Ag(n)),".lmctl-claude-mock","sessions.json"):Uk(Ag(t),".lmctl-claude-mock","sessions.json")}function Hk(){return{schemaVersion:1,sessions:{}}}function la(t){if(!eH(t))return Hk();try{let e=JSON.parse(tH(t,"utf8")),n=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},r=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=Ng(e.defaultDelayMs);return{schemaVersion:1,sessions:n,...i!==void 0?{defaultDelayMs:i}:{},...r!==void 0?{script:r}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Hk()}}function Kk(t,e){Cg(Mg(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;sH(n,`${JSON.stringify(e,null,2)}
|
|
2310
|
-
`,"utf8"),nH(n,t)}function uH(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function dH(t){let e=`${t}.lock`;Cg(Mg(t),{recursive:!0});let n=Date.now()+Bk;for(;;)try{return Cg(e),e}catch(r){if(r.code!=="EEXIST")throw r;try{if(Date.now()-rH(e).mtimeMs>lH){try{Jk(e)}catch{}continue}}catch{continue}if(Date.now()>=n)throw new Error(`ClaudeMock store lock timeout after ${Bk}ms: ${e}`);uH(cH)}}function mH(t){try{Jk(t)}catch{}}function zk(t,e){let n=dH(t);try{return e()}finally{mH(n)}}function pH(t){return{...t,timestamp:t.timestamp.toISOString()}}function fH(t){return{...t,timestamp:new Date(t.timestamp)}}function gH(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(pH)}}function Yk(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(fH)}}function pu(t,e=process.cwd()){let n=Ii.get(t);if(n!==void 0)return n;let s=la(xi(e)).sessions[t];if(s===void 0)return;let i=Yk(s);return Ii.set(i.sessionId,i),i}function Wk(t){Ii.set(t.sessionId,t);let e=xi(t.cwd);zk(e,()=>{let n=la(e);n.sessions[t.sessionId]=gH({...t,filePath:e}),Kk(e,n)})}function hH(t,e=process.cwd()){let n=xi(e);return zk(n,()=>{let r=la(n),s=r.sessions[t]!==void 0;return s&&(delete r.sessions[t],Kk(n,r)),s})}function yH(){let t=la(xi()),e=Object.values(t.sessions).map(Yk);for(let n of e)Ii.set(n.sessionId,n);return e}function Ng(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function qk(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Ng(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=Ng(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Xk(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function _H(t,e){let{script:n,scriptContains:r}=e;if(n!==void 0){let s=qk(n[t]??n[Vk(t)]);if(s!==void 0)return s}if(r!==void 0){for(let s of Object.keys(r))if(t.includes(s)){let i=qk(r[s]);if(i!==void 0)return i}}}function Gk(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function Pg(){return new Lg}var Ii,lH,cH,Bk,Og,Lg,Dg=L(()=>{"use strict";Ii=new Map;lH=5e3,cH=15,Bk=1e4;Og=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let n of yH())e.set(n.sessionId,n);for(let n of Ii.values())e.set(n.sessionId,n);return[...e.values()].map(Gk)}async loadSession(e){let n=pu(e);return n===void 0?null:{...Gk(n),messages:n.messages.slice()}}async resolveSessionPath(e){return pu(e)?.filePath??null}async deleteSession(e){let n=Ii.delete(e),r=hH(e);return n||r}},Lg=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Og;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[]}async seed(e,n){try{n?.onDispatch?.()}catch{}let r=oH(aH(e,n)),s=`mock-${r}-${iH(`${e}:${r}`)}`,i=new Date,o=xi(e),a=pu(s,e),l=n?.prompt??"ClaudeMock seed",c=mu(l),u={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return u.messages.push({role:"user",timestamp:i,content:l}),u.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),u.totalInputTokens+=c,u.totalOutputTokens+=mu("ACK: ClaudeMock seeded"),Wk(u),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,n){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,n){let r=Date.now(),s=pu(n.sessionId,n.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${n.sessionId}`);let i=new Date,o=la(xi(n.cwd)),a=_H(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Xk(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Vk(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:n.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=mu(e),s.totalOutputTokens+=mu(c),Wk(s),n.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Xk(l),{text:c,sessionId:n.sessionId,durationMs:Math.max(1,Date.now()-r),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function Zn(t){let e=[hf({museDataHome:t?.museDataHome}),kf({miniplayerHome:t?.miniplayerHome}),xf({claudeDir:t?.claudeDir}),Lf({codexDir:t?.codexDir,codeDir:t?.codeDir}),$f({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),Bf({copilotDir:t?.copilotDir}),Xf({dbPaths:t?.opencodeDbPaths}),zf({kimiHome:t?.kimiHome}),Zf({lmplayerDbPath:t?.lmplayerDbPath,lmplayerDbPaths:t?.lmplayerDbPaths}),ng({qwenDir:t?.qwenDir}),ag({agyDir:t?.agyDir}),yg({dshHome:t?.dshHome}),Eg({hermesHome:t?.hermesHome}),Ig({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Pg()),e}var Fg=L(()=>{"use strict";yf();yf();Rf();Rf();Af();Mf();jf();Wf();Gf();Yf();eg();rg();lg();_g();Tg();xg();Dg();Af();Mf();jf();Wf();Gf();Yf();eg();rg();lg();_g();Tg();xg();Dg()});var Qk,Zk,eR=L(()=>{"use strict";Qk=["claude","qwen","codex","dsh","miniplayer","muse","gemini","copilot","opencode","kimi","hermes"],Zk=["agy","pi","lmplayer"]});var rR={};On(rR,{BUNDLE_CAPABLE_PROVIDERS:()=>Qk,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Zk,ProviderRegistry:()=>zo,TransportConnectionError:()=>xe,TransportError:()=>Or,TransportJsonError:()=>vc,TransportProcessError:()=>Pe,TransportRpcError:()=>jo,_resetDefaultRegistryForTests:()=>TH,bundleSupportedProviders:()=>hu,canUsePersistentSession:()=>Ic,chat:()=>ca,countTokens:()=>kH,createAdapterRegistry:()=>zn,createAllAdapters:()=>Zn,deleteSession:()=>Bg,listSessions:()=>Hg,openBundleSession:()=>$g,openConversation:()=>jg,seed:()=>Ug});import{accessSync as vH,constants as bH,statSync as wH}from"node:fs";import{join as EH,delimiter as tR}from"node:path";function Hr(){return fu===null&&(fu=zn(Zn())),fu}function TH(){fu=null}function gu(t,e){oc(e);let n=t.getAdapter(e);if(!n)throw new Error(`provider "${e}" is not registered in this registry`);return n}async function ca(t){let e=t.registry??Hr(),n=gu(e,t.provider),r={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=t.bundleSession===void 0?await xc(n,{...r,execution:"per-turn",requireResume:t.requireResume??!1}):void 0,i;try{i=s?await s.sendTurn(t.prompt,{onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal}):await n.sendTurn(t.prompt,r)}finally{await s?.close()}return{text:i.text,...i.usage?{usage:i.usage}:{},sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,numTurns:i.numTurns,status:i.status,stalledAfterMs:i.stalledAfterMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}}function hu(t){return(t??Hr()).getAllAdapters().filter(n=>Wn(n.name)&&n.openSession!==void 0).map(n=>n.name)}async function $g(t){let e=t.registry??Hr(),n=gu(e,t.provider);if(n.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${hu(e).join(", ")})`);return xc(n,{...t,execution:"persistent"})}async function jg(t){return xc(gu(t.registry??Hr(),t.provider),t)}async function Ug(t){let e=t.registry??Hr(),n=gu(e,t.provider);if(n.seedBinary==="agy"){let u=t.env??process.env,d=u.PATH??u.Path??"/usr/bin:/bin",m=tR===";"?["",...(u.PATHEXT??".EXE;.CMD;.BAT").split(";")]:[""];if(!d.split(tR).some(f=>{try{return m.some(g=>{try{let h=EH(f||t.cwd,"agy"+g);return vH(h,bH.X_OK),wH(h).isFile()}catch{return!1}})}catch{return!1}}))return{success:!1,error:"Failed to spawn agy: executable not found on PATH",errorCode:"ENOENT"}}if(t.signal?.aborted)return{success:!1,error:"seed cancelled before dispatch",errorCode:"ABORT_ERR"};let r=await nR(e,t.provider,t.cwd);if(t.signal?.aborted)return{success:!1,error:"seed cancelled before dispatch",errorCode:"ABORT_ERR"};let s=await n.seed(t.cwd,{...t.env?{env:t.env}:{},...t.signal?{signal:t.signal}:{},onDispatch:t.onDispatch,model:t.model,effort:t.effort,prompt:t.prompt}),i;try{i=s.usage}catch{}let o={usage:i},a=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(s.success&&s.sessionId)return{success:!0,sessionId:s.sessionId,...a,...o};if(!s.success&&(s.errorCode==="ENOENT"||s.errorCode==="ABORT_ERR"))return{success:!1,error:s.error,errorCode:s.errorCode,sessionId:s.sessionId,...a,...o};let l=await nR(e,t.provider,t.cwd),c=SH(r,l);return s.success?c?{success:!0,sessionId:c,...a,...o}:{success:!0,...a,...o}:(c&&await n.delete?.(c).catch(()=>{}),{success:!1,error:s.error,errorCode:s.errorCode,sessionId:s.sessionId,...a,...o})}async function nR(t,e,n){let r=await t.listAll({provider:e,workspace:n}),s=new Map;for(let i of r)s.set(i.sessionId,i.modifiedAt);return s}function SH(t,e){let n=[];for(let r of e.keys())t.has(r)||n.push(r);return n.length===1?n[0]:void 0}async function Hg(t={}){return(t.registry??Hr()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function Bg(t,e,n=Hr()){return n.deleteSession(e,t)}async function kH(t){let n=await(t.registry??Hr()).getSession(t.sessionId,t.provider);if(!n)throw new Error(`session "${t.sessionId}" not found`);let r=n.totalInputTokens??0,s=n.totalCachedInputTokens??0,i=n.totalCacheWriteInputTokens??0,o=n.totalOutputTokens??0,a=n.totalReasoningOutputTokens??0;return{provider:n.provider,sessionId:n.sessionId,input:r,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:r+s+i+o+a,lastTurn:n.lastTokenUsage}}var fu,er=L(()=>{"use strict";vi();ui();of();Fg();vi();of();Fg();eR();Lr();fu=null});function qg(t){return Wn(t)&&IH.has(t)}function ua(){return Wg===null&&(Wg=zn(Zn())),Wg}function oR(t,e,n={}){if(!qg(t))return null;try{let r=ua().getAdapter?.(t);if(r===void 0)return null;let s=r.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&n.isLead===!0?$c({warn:()=>{}}):[],a=n.model!==void 0&&n.model.trim().length>0?RH[t]?.(n.model):void 0;return n.model!==void 0&&n.model.trim().length>0&&a===void 0&&n.onModelIgnored?.({provider:t,model:n.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...sR[t]??[]]}catch{return null}}async function aR(t,e){try{let n=ua().getAdapter(t);return n?.preflightNativeLaunch?await n.preflightNativeLaunch(e):{kind:"ok"}}catch{return{kind:"ok"}}}function lR(t){try{return ua().getAdapter(t)?.nativeLaunchFailureHint}catch{return}}function da(t,e){return ua().getSession(t,e)}async function cR(t){return(await ua().resolveSessions(t)).map(n=>n.provider.name)}var sR,RH,IH,iR,Wg,yu=L(()=>{"use strict";ui();er();Ef();sR={muse:["--yolo"],claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],pi:[],lmplayer:["--auto"],kimi:[],hermes:[]},RH={muse:t=>["--model",t],claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t],kimi:t=>["--model",t],hermes:t=>["--model",t],pi:t=>["--model",t]},IH=new Set(Object.keys(sR)),iR=/^[\w.:-]+$/;Wg=null});import{homedir as xH}from"node:os";function uR(t,e){let n=new Set;return{text:t.replace(CH,(s,i)=>{let o=i.trim(),a=AH[o];return a===void 0?(n.add(o),s):a(e)}),unknownNames:[...n].sort()}}function dR(t){return{workdir:t.workdir,teamfile:t.teamfile,date:NH(t.date)}}function NH(t){return t.toISOString().slice(0,10)}var AH,CH,mR=L(()=>{"use strict";vn();AH={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>No(t.teamfile),home:()=>xH(),date:t=>t.date},CH=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});import{existsSync as OH,mkdirSync as LH,readFileSync as MH,renameSync as PH,unlinkSync as DH,writeFileSync as FH}from"node:fs";import{homedir as fR}from"node:os";import{dirname as ma,join as pt,resolve as $H}from"node:path";function Ci(t,e,n){let r=ma($H(n)),s=new Set,i=new Map;for(let o of e.members){if(s.add(o.provider),o.teamfile!==void 0)continue;let a=o.sessiondir??r,l=i.get(a)??new Set;l.add(o.provider),i.set(a,l)}for(let[o,a]of i.entries())In(pt(o,".mcp.json"),"mcpServers",[Br(),Wr()]),a.has("opencode")&&In(pt(o,".opencode","opencode.json"),"mcp",[gR(),hR()]),a.has("kimi")&&In(pt(o,".kimi-code","mcp.json"),"mcpServers",[Br(),Wr()]);for(let o of s)WH(o)}function UH(t=Xg??fR()){return pt(t,".copilot","mcp-config.json")}function HH(t,e){Yt.mkdirSync(ma(t),{recursive:!0});let n=pt(ma(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Yt.writeFileSync(n,`${JSON.stringify(e,null,2)}
|
|
2309
|
+
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(n)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(n)}return a?z(a.content,80):void 0});return{first:r,last:s}}catch{return{}}}async loadSession(e){let n=this.openDb();if(!n)return null;try{let r=this.selectSessionRow(n,e);if(!r)return null;let s=this.activeMessageRows(n,e),i=[],o=[],a,l;for(let c of s){let u=aa(c.timestamp),d=c.content??"";if(c.role==="user"){d&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(d),d.length>0&&(a||(a=z(d,80)),l=z(d,80)),i.push({role:"user",timestamp:u,content:d||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:u,content:d,toolCallId:St(c.tool_call_id),toolName:St(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:St(r.model),stopReason:St(c.finish_reason)});for(let m of q1(c.tool_calls)){let p=X1(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:St(m.function?.name)??"tool_call",toolName:St(m.function?.name),toolCallId:St(m.call_id)??St(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Jt(p)})}}return{provider:this.name,sessionId:r.id,slug:St(r.title),cwd:Ok(r),createdAt:aa(r.started_at),modifiedAt:aa(r.last_activity_at??r.started_at),model:St(r.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:r.message_count??i.length,filePath:this.dbPath,...Lk(r),messages:i,userPrompts:o}}catch(r){return X({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),null}finally{n.close()}}async resolveSessionPath(e){let n=this.openDb();if(!n)return null;try{return this.selectSessionRow(n,e)?this.dbPath:null}catch{return null}finally{n.close()}}async deleteSession(e){return!1}}});import{mkdir as G1}from"node:fs/promises";function V1(t){return J1.test(t)}function Dk(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return K1}function Eg(t){return new wg(t)}var J1,K1,wg,Tg=L(()=>{"use strict";rt();Pk();Yn();ze();Se();J1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;K1="dont_ask";wg=class extends _e{hermesProvider;hermesHome;constructor(e){let n=new uu(e);super({provider:n,protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Hermes has no provider-side leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"hermes",seedArgs:[],resumeTemplate:"hermes --yolo --resume {{session_id}}",startTemplate:"hermes",transport:async(r,s)=>an(r,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:Dk(s.permissionMode)})}),this.hermesProvider=n,this.hermesHome=bg(e)}async openSession(e){return Sn({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:Dk(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,n){await G1(e,{recursive:!0});let r=[];if(n?.effort){let i="hermes has no ACP-level effort surface";X({event:"hermes_effort_ignored",provider:this.name,effort:n.effort,reason:i}),r.push(`hermes seed ignored effort=${n.effort}: ${i}`)}let s;try{n?.signal?.throwIfAborted();try{n?.onDispatch?.()}catch{}s=await this.sendTurn(n?.prompt??ce,{sessionId:"",cwd:e,env:n?.env,signal:n?.signal,model:n?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return V1(s.sessionId)?(r.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,usage:s.usage,...r.length>0?{warnings:r}:{}}):(X({event:"hermes_seed_contract_violation",provider:this.name,session_id:s.sessionId,reason:"session/new did not return a UUID session id"}),{success:!1,error:`hermes ACP session/new did not return a UUID session id (got ${JSON.stringify(s.sessionId)})`})}}});import{readdir as Fk,rm as z1,stat as Y1}from"node:fs/promises";import{join as Sg}from"node:path";function kg(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function $k(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var du,jk=L(()=>{"use strict";We();du=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Sg(ie,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let n of await this.listSessionFiles())try{let r=await this.extractSummary(n);r&&e.push(r)}catch{}return e}async listSessionFiles(){let e;try{e=await Fk(this.baseDir)}catch{return[]}let n=[];for(let r of e){let s=Sg(this.baseDir,r);try{if(!(await Y1(s)).isDirectory())continue;for(let i of await Fk(s))i.endsWith(".jsonl")&&n.push(Sg(s,i))}catch{}}return n}async readHeader(e){for await(let n of Ie(e))return n.type==="session"?n:null;return null}async extractSummary(e){let n=await this.readHeader(e);if(!n)return null;let r=await De(e),s,i,o,a=0,l=0,c=0,u=0,d=0,m=0,p=0,f;for await(let g of Ie(e)){if(g.type==="model_change"&&g.provider&&g.modelId){s=`${g.provider}/${g.modelId}`;continue}if(g.type!=="message"||!g.message)continue;let h=g.message;if(h.provider&&h.model&&(s=`${h.provider}/${h.model}`),h.role==="user"){let y=kg(h).trim();y&&(i||(i=z(y,80)),o=z(y,80)),a++}else if(h.role==="assistant"){a++;let y=h.usage;y&&(l+=y.input??0,c+=y.cacheRead??0,u+=y.cacheWrite??0,d+=y.output??0,m+=y.reasoning??0,p=y.input??0,f={inputTokens:y.input,cachedInputTokens:y.cacheRead,cacheWriteInputTokens:y.cacheWrite,outputTokens:y.output,reasoningOutputTokens:y.reasoning,totalTokens:y.totalTokens})}}return{provider:"pi",sessionId:n.id,cwd:n.cwd??"(unknown)",createdAt:r.createdAt,modifiedAt:r.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:p,lastTokenUsage:f}}async loadSession(e){let n=await this.resolveSessionPath(e);if(!n)return null;let r=await this.extractSummary(n);if(!r)return null;let s=[],i=r.model;for await(let o of Ie(n)){if(o.type==="model_change"&&o.provider&&o.modelId){i=`${o.provider}/${o.modelId}`;continue}if(o.type!=="message"||!o.message)continue;let a=o.message;a.provider&&a.model&&(i=`${a.provider}/${a.model}`);let l=a.timestamp?new Date(a.timestamp):r.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:kg(a)});else if(a.role==="assistant"&&Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?s.push({role:"assistant",timestamp:l,content:c.text,model:i}):c.type==="thinking"&&c.thinking?s.push({role:"thinking",timestamp:l,content:c.thinking}):c.type==="toolCall"&&s.push({role:"tool_use",timestamp:l,content:$k(c.arguments),toolName:c.name??"tool",toolInput:$k(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:kg(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...r,model:i,messages:s}}async resolveSessionPath(e){let n=`_${e}.jsonl`,r=[];for(let s of await this.listSessionFiles()){if(s.endsWith(n))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&r.push(s)}return r.length===1?r[0]:null}async deleteSession(e){let n=await this.resolveSessionPath(e);return n?(await z1(n,{force:!0}),!0):!1}}});function Ig(t){return new Rg(t)}var Rg,Q1,xg=L(()=>{"use strict";jk();rt();ze();Tn();ig();Rg=class extends _e{constructor(e){super({provider:new du(e),protocol:{transport:"print",perTurnCancellation:"process"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"pi uses one-shot print turns; no streaming events are available."},binary:"pi",seedArgs:["-p",ce],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:Q1})}seedArgsFor(e){let n=[...super.seedArgsFor(e)];return e?.model&&n.push("--model",e.model),n}manualSeedHint(e){return{launchCommand:`cd ${e} && pi`,postLaunchNote:"Send the lmctl seed instruction, wait for the session file to write, then exit.",lsCommand:`lmctl ls --provider pi --sessiondir ${e}`}}},Q1=iu({label:"pi",buildArgs:(t,e)=>{let n=[...e.sessionId?["--session",e.sessionId]:[],"-p",t];return e.model&&n.push("--model",e.model),n},assertArgs:(t,e)=>qe("pi",t,e.permissionMode??"yolo")})});import{createHash as Z1}from"node:crypto";import{existsSync as eH,mkdirSync as Cg,readFileSync as tH,renameSync as nH,rmdirSync as Jk,statSync as rH,writeFileSync as sH}from"node:fs";import{dirname as Mg,join as Uk,resolve as Ag}from"node:path";function iH(t){return Z1("sha256").update(t).digest("hex").slice(0,8)}function oH(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function aH(t,e){let n=e?.prompt??"",r=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(n);return r!==null?r[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function Vk(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function mu(t){return Math.max(1,Math.ceil(t.length/4))}function xi(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Ag(e);let n=process.env.LMCTL_DB;return n!==void 0&&n.trim().length>0?Uk(Mg(Ag(n)),".lmctl-claude-mock","sessions.json"):Uk(Ag(t),".lmctl-claude-mock","sessions.json")}function Hk(){return{schemaVersion:1,sessions:{}}}function la(t){if(!eH(t))return Hk();try{let e=JSON.parse(tH(t,"utf8")),n=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},r=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=Ng(e.defaultDelayMs);return{schemaVersion:1,sessions:n,...i!==void 0?{defaultDelayMs:i}:{},...r!==void 0?{script:r}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Hk()}}function Kk(t,e){Cg(Mg(t),{recursive:!0});let n=`${t}.${process.pid}.${Date.now()}.tmp`;sH(n,`${JSON.stringify(e,null,2)}
|
|
2310
|
+
`,"utf8"),nH(n,t)}function uH(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function dH(t){let e=`${t}.lock`;Cg(Mg(t),{recursive:!0});let n=Date.now()+Bk;for(;;)try{return Cg(e),e}catch(r){if(r.code!=="EEXIST")throw r;try{if(Date.now()-rH(e).mtimeMs>lH){try{Jk(e)}catch{}continue}}catch{continue}if(Date.now()>=n)throw new Error(`ClaudeMock store lock timeout after ${Bk}ms: ${e}`);uH(cH)}}function mH(t){try{Jk(t)}catch{}}function zk(t,e){let n=dH(t);try{return e()}finally{mH(n)}}function pH(t){return{...t,timestamp:t.timestamp.toISOString()}}function fH(t){return{...t,timestamp:new Date(t.timestamp)}}function gH(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(pH)}}function Yk(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(fH)}}function pu(t,e=process.cwd()){let n=Ii.get(t);if(n!==void 0)return n;let s=la(xi(e)).sessions[t];if(s===void 0)return;let i=Yk(s);return Ii.set(i.sessionId,i),i}function Wk(t){Ii.set(t.sessionId,t);let e=xi(t.cwd);zk(e,()=>{let n=la(e);n.sessions[t.sessionId]=gH({...t,filePath:e}),Kk(e,n)})}function hH(t,e=process.cwd()){let n=xi(e);return zk(n,()=>{let r=la(n),s=r.sessions[t]!==void 0;return s&&(delete r.sessions[t],Kk(n,r)),s})}function yH(){let t=la(xi()),e=Object.values(t.sessions).map(Yk);for(let n of e)Ii.set(n.sessionId,n);return e}function Ng(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function qk(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Ng(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=Ng(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Xk(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function _H(t,e){let{script:n,scriptContains:r}=e;if(n!==void 0){let s=qk(n[t]??n[Vk(t)]);if(s!==void 0)return s}if(r!==void 0){for(let s of Object.keys(r))if(t.includes(s)){let i=qk(r[s]);if(i!==void 0)return i}}}function Gk(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function Pg(){return new Lg}var Ii,lH,cH,Bk,Og,Lg,Dg=L(()=>{"use strict";Ii=new Map;lH=5e3,cH=15,Bk=1e4;Og=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let n of yH())e.set(n.sessionId,n);for(let n of Ii.values())e.set(n.sessionId,n);return[...e.values()].map(Gk)}async loadSession(e){let n=pu(e);return n===void 0?null:{...Gk(n),messages:n.messages.slice()}}async resolveSessionPath(e){return pu(e)?.filePath??null}async deleteSession(e){let n=Ii.delete(e),r=hH(e);return n||r}},Lg=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Og;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[]}async seed(e,n){try{n?.onDispatch?.()}catch{}let r=oH(aH(e,n)),s=`mock-${r}-${iH(`${e}:${r}`)}`,i=new Date,o=xi(e),a=pu(s,e),l=n?.prompt??"ClaudeMock seed",c=mu(l),u={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return u.messages.push({role:"user",timestamp:i,content:l}),u.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),u.totalInputTokens+=c,u.totalOutputTokens+=mu("ACK: ClaudeMock seeded"),Wk(u),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,n){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,n){let r=Date.now(),s=pu(n.sessionId,n.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${n.sessionId}`);let i=new Date,o=la(xi(n.cwd)),a=_H(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Xk(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Vk(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:n.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=mu(e),s.totalOutputTokens+=mu(c),Wk(s),n.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Xk(l),{text:c,sessionId:n.sessionId,durationMs:Math.max(1,Date.now()-r),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function Zn(t){let e=[hf({museDataHome:t?.museDataHome}),kf({miniplayerHome:t?.miniplayerHome}),xf({claudeDir:t?.claudeDir}),Lf({codexDir:t?.codexDir,codeDir:t?.codeDir}),$f({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),Bf({copilotDir:t?.copilotDir}),Xf({dbPaths:t?.opencodeDbPaths}),zf({kimiHome:t?.kimiHome}),Zf({lmplayerDbPath:t?.lmplayerDbPath,lmplayerDbPaths:t?.lmplayerDbPaths}),ng({qwenDir:t?.qwenDir}),ag({agyDir:t?.agyDir}),yg({dshHome:t?.dshHome}),Eg({hermesHome:t?.hermesHome}),Ig({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Pg()),e}var Fg=L(()=>{"use strict";yf();yf();Rf();Rf();Af();Mf();jf();Wf();Gf();Yf();eg();rg();lg();_g();Tg();xg();Dg();Af();Mf();jf();Wf();Gf();Yf();eg();rg();lg();_g();Tg();xg();Dg()});var Qk,Zk,eR=L(()=>{"use strict";Qk=["claude","qwen","codex","dsh","miniplayer","muse","gemini","copilot","opencode","kimi","hermes"],Zk=["agy","pi","lmplayer"]});var rR={};On(rR,{BUNDLE_CAPABLE_PROVIDERS:()=>Qk,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Zk,ProviderRegistry:()=>zo,TransportConnectionError:()=>xe,TransportError:()=>Or,TransportJsonError:()=>vc,TransportProcessError:()=>Pe,TransportRpcError:()=>jo,_resetDefaultRegistryForTests:()=>TH,bundleSupportedProviders:()=>hu,canUsePersistentSession:()=>Ic,chat:()=>ca,countTokens:()=>kH,createAdapterRegistry:()=>zn,createAllAdapters:()=>Zn,deleteSession:()=>Bg,listSessions:()=>Hg,openBundleSession:()=>$g,openConversation:()=>jg,seed:()=>Ug});import{accessSync as vH,constants as bH,statSync as wH}from"node:fs";import{join as EH,delimiter as tR}from"node:path";function Hr(){return fu===null&&(fu=zn(Zn())),fu}function TH(){fu=null}function gu(t,e){oc(e);let n=t.getAdapter(e);if(!n)throw new Error(`provider "${e}" is not registered in this registry`);return n}async function ca(t){let e=t.registry??Hr(),n=gu(e,t.provider),r={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=t.bundleSession===void 0?await xc(n,{...r,execution:"per-turn",requireResume:t.requireResume??!1}):void 0,i;try{i=s?await s.sendTurn(t.prompt,{onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal}):await n.sendTurn(t.prompt,r)}finally{await s?.close()}return{text:i.text,...i.usage?{usage:i.usage}:{},sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,numTurns:i.numTurns,status:i.status,stalledAfterMs:i.stalledAfterMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}}function hu(t){return(t??Hr()).getAllAdapters().filter(n=>Wn(n.name)&&n.openSession!==void 0).map(n=>n.name)}async function $g(t){let e=t.registry??Hr(),n=gu(e,t.provider);if(n.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${hu(e).join(", ")})`);return xc(n,{...t,execution:"persistent"})}async function jg(t){return xc(gu(t.registry??Hr(),t.provider),t)}async function Ug(t){let e=t.registry??Hr(),n=gu(e,t.provider);if(n.seedBinary==="agy"){let u=t.env??process.env,d=u.PATH??u.Path??"/usr/bin:/bin",m=tR===";"?["",...(u.PATHEXT??".EXE;.CMD;.BAT").split(";")]:[""];if(!d.split(tR).some(f=>{try{return m.some(g=>{try{let h=EH(f||t.cwd,"agy"+g);return vH(h,bH.X_OK),wH(h).isFile()}catch{return!1}})}catch{return!1}}))return{success:!1,error:"Failed to spawn agy: executable not found on PATH",errorCode:"ENOENT"}}if(t.signal?.aborted)return{success:!1,error:"seed cancelled before dispatch",errorCode:"ABORT_ERR"};let r=await nR(e,t.provider,t.cwd);if(t.signal?.aborted)return{success:!1,error:"seed cancelled before dispatch",errorCode:"ABORT_ERR"};let s=await n.seed(t.cwd,{...t.env?{env:t.env}:{},...t.signal?{signal:t.signal}:{},onDispatch:t.onDispatch,model:t.model,effort:t.effort,prompt:t.prompt}),i;try{i=s.usage}catch{}let o={usage:i},a=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(s.success&&s.sessionId)return{success:!0,sessionId:s.sessionId,...a,...o};if(!s.success&&(s.errorCode==="ENOENT"||s.errorCode==="ABORT_ERR"))return{success:!1,error:s.error,errorCode:s.errorCode,sessionId:s.sessionId,...a,...o};let l=await nR(e,t.provider,t.cwd),c=SH(r,l);return s.success?c?{success:!0,sessionId:c,...a,...o}:{success:!0,...a,...o}:(c&&await n.delete?.(c).catch(()=>{}),{success:!1,error:s.error,errorCode:s.errorCode,sessionId:s.sessionId,...a,...o})}async function nR(t,e,n){let r=await t.listAll({provider:e,workspace:n}),s=new Map;for(let i of r)s.set(i.sessionId,i.modifiedAt);return s}function SH(t,e){let n=[];for(let r of e.keys())t.has(r)||n.push(r);return n.length===1?n[0]:void 0}async function Hg(t={}){return(t.registry??Hr()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function Bg(t,e,n=Hr()){return n.deleteSession(e,t)}async function kH(t){let n=await(t.registry??Hr()).getSession(t.sessionId,t.provider);if(!n)throw new Error(`session "${t.sessionId}" not found`);let r=n.totalInputTokens??0,s=n.totalCachedInputTokens??0,i=n.totalCacheWriteInputTokens??0,o=n.totalOutputTokens??0,a=n.totalReasoningOutputTokens??0;return{provider:n.provider,sessionId:n.sessionId,input:r,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:r+s+i+o+a,lastTurn:n.lastTokenUsage}}var fu,er=L(()=>{"use strict";vi();ui();of();Fg();vi();of();Fg();eR();Lr();fu=null});function qg(t){return Wn(t)&&IH.has(t)}function ua(){return Wg===null&&(Wg=zn(Zn())),Wg}function oR(t,e,n={}){if(!qg(t))return null;try{let r=ua().getAdapter?.(t);if(r===void 0)return null;let s=r.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&n.isLead===!0?$c({warn:()=>{}}):[],a=n.model!==void 0&&n.model.trim().length>0?RH[t]?.(n.model):void 0;return n.model!==void 0&&n.model.trim().length>0&&a===void 0&&n.onModelIgnored?.({provider:t,model:n.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...sR[t]??[]]}catch{return null}}async function aR(t,e){try{let n=ua().getAdapter(t);return n?.preflightNativeLaunch?await n.preflightNativeLaunch(e):{kind:"ok"}}catch{return{kind:"ok"}}}function lR(t){try{return ua().getAdapter(t)?.nativeLaunchFailureHint}catch{return}}function da(t,e){return ua().getSession(t,e)}async function cR(t){return(await ua().resolveSessions(t)).map(n=>n.provider.name)}var sR,RH,IH,iR,Wg,yu=L(()=>{"use strict";ui();er();Ef();sR={muse:["--yolo"],claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],pi:[],lmplayer:["--auto"],kimi:[],hermes:[]},RH={muse:t=>["--model",t],claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t],kimi:t=>["--model",t],hermes:t=>["--model",t],pi:t=>["--model",t]},IH=new Set(Object.keys(sR)),iR=/^[\w.:-]+$/;Wg=null});import{homedir as xH}from"node:os";function uR(t,e){let n=new Set;return{text:t.replace(CH,(s,i)=>{let o=i.trim(),a=AH[o];return a===void 0?(n.add(o),s):a(e)}),unknownNames:[...n].sort()}}function dR(t){return{workdir:t.workdir,teamfile:t.teamfile,date:NH(t.date)}}function NH(t){return t.toISOString().slice(0,10)}var AH,CH,mR=L(()=>{"use strict";bn();AH={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>No(t.teamfile),home:()=>xH(),date:t=>t.date},CH=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});import{existsSync as OH,mkdirSync as LH,readFileSync as MH,renameSync as PH,unlinkSync as DH,writeFileSync as FH}from"node:fs";import{homedir as fR}from"node:os";import{dirname as ma,join as pt,resolve as $H}from"node:path";function Ci(t,e,n){let r=ma($H(n)),s=new Set,i=new Map;for(let o of e.members){if(s.add(o.provider),o.teamfile!==void 0)continue;let a=o.sessiondir??r,l=i.get(a)??new Set;l.add(o.provider),i.set(a,l)}for(let[o,a]of i.entries())In(pt(o,".mcp.json"),"mcpServers",[Br(),Wr()]),a.has("opencode")&&In(pt(o,".opencode","opencode.json"),"mcp",[gR(),hR()]),a.has("kimi")&&In(pt(o,".kimi-code","mcp.json"),"mcpServers",[Br(),Wr()]);for(let o of s)WH(o)}function UH(t=Xg??fR()){return pt(t,".copilot","mcp-config.json")}function HH(t,e){Yt.mkdirSync(ma(t),{recursive:!0});let n=pt(ma(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Yt.writeFileSync(n,`${JSON.stringify(e,null,2)}
|
|
2311
2311
|
`,"utf8"),Yt.renameSync(n,t)}catch(r){try{Yt.unlinkSync(n)}catch{}throw r}}function BH(t,e){Yt.mkdirSync(ma(t),{recursive:!0});let n=pt(ma(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Yt.writeFileSync(n,e,"utf8"),Yt.renameSync(n,t)}catch(r){try{Yt.unlinkSync(n)}catch{}throw r}}function In(t,e,n){try{if(!Yt.existsSync(t))return;let r=JSON.parse(Yt.readFileSync(t,"utf8"));if(!Ai(r)||!Ai(r[e]))return;let s={...r[e]},i=[];for(let{name:o,shouldRemove:a}of n)Object.prototype.hasOwnProperty.call(s,o)&&a(s[o])&&(delete s[o],i.push(o));if(i.length===0)return;r[e]=s,HH(t,r),X({event:"mcp_cleanup",path:t,removed:i})}catch{}}function Br(){return{name:vu,shouldRemove:YH}}function gR(){return{name:vu,shouldRemove:QH}}function Wr(){return{name:_u,shouldRemove:KH}}function hR(){return{name:_u,shouldRemove:zH}}function WH(t){let e=Xg??fR();switch(t){case"copilot":In(UH(e),"mcpServers",[Br(),Wr()]);return;case"claude":In(pt(e,".claude.json"),"mcpServers",[Br(),Wr()]);return;case"gemini":In(pt(e,".gemini","settings.json"),"mcpServers",[Br(),Wr()]);return;case"qwen":In(pt(e,".qwen","settings.json"),"mcpServers",[Br(),Wr()]);return;case"agy":In(pt(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[Br(),Wr()]);return;case"opencode":In(pt(e,".config","opencode","opencode.json"),"mcp",[gR(),hR()]);return;case"kimi":In(pt(Xg===void 0?process.env.KIMI_CODE_HOME??pt(e,".kimi-code"):pt(e,".kimi-code"),"mcp.json"),"mcpServers",[Br(),Wr()]);return;case"codex":qH(pt(e,".codex","config.toml"));return;default:return}}function qH(t){try{if(!Yt.existsSync(t))return;let e=Yt.readFileSync(t,"utf8"),n=XH(e);if(n===null)return;let r=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of r){let c=yR(l);if(c===null)return;if(c!==void 0){if(pR(c,n)){o=!0,a=c[1],i.add(a);continue}o=!1,a=void 0,s.push(l);continue}if(o){if(/^\s*(?:#.*)?$/.test(l)){s.push(l);continue}a!==void 0&&i.add(a);continue}let u=JH(l);if(u===null)return;if(u!==void 0&&pR(u,n)){i.add(u[1]);continue}s.push(l)}if(i.size===0)return;BH(t,s.join(`
|
|
2312
2312
|
`)),X({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function pR(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function XH(t){let e=new Map,n;for(let s of t.split(/\n/)){let i=yR(s);if(i===null)return null;if(i!==void 0){n=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=GH(a,n);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==_u&&c[1]!==vu)continue;let u=e.get(c[1])??{};if(c[2]==="command"){let d=_R(l);if(d===null)return null;u.command=d}else if(c[2]==="args"){let d=VH(l);if(d===null)return null;u.args=d}e.set(c[1],u)}let r=new Set;for(let[s,i]of e.entries())s===_u&&bR(i.command,i.args)&&r.add(s),s===vu&&wR(i.command,i.args)&&r.add(s);return r}function GH(t,e){if(t.startsWith("mcp_servers"))return bu(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let n=bu(t);return n===null?null:[...e,...n]}function yR(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:bu(e[1])}function JH(t){let e=t.indexOf("=");if(e<0)return;let n=t.slice(0,e).trim();if(!(n.length===0||!n.startsWith("mcp_servers")))return bu(n)}function bu(t){let e=[],n=0,r=()=>{for(;n<t.length&&/\s/.test(t[n]);)n+=1};for(;n<t.length;){if(r(),n>=t.length)return null;if(t[n]==='"'){n+=1;let s="",i=!1;for(;n<t.length;){let o=t[n];if(o==="\\"){if(n+1>=t.length)return null;s+=t[n+1],n+=2;continue}if(o==='"'){n+=1,i=!0;break}s+=o,n+=1}if(!i)return null;e.push(s)}else{let s=n;for(;n<t.length&&/[A-Za-z0-9_-]/.test(t[n]);)n+=1;if(n===s)return null;e.push(t.slice(s,n))}if(r(),n>=t.length)break;if(t[n]!==".")return null;n+=1}return e.length>0?e:null}function _R(t){let e=vR(t).trim();if(e.startsWith('"'))try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function VH(t){let e=vR(t).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let n=e.slice(1,-1).trim();if(n.length===0)return[];let r=n.split(",").map(s=>_R(s.trim()));return r.some(s=>s===null)?null:r}function vR(t){let e;for(let n=0;n<t.length;n+=1){let r=t[n];if(e!==void 0){if(e==='"'&&r==="\\"){n+=1;continue}r===e&&(e=void 0);continue}if(r==='"'||r==="'"){e=r;continue}if(r==="#")return t.slice(0,n)}return t}function KH(t){return Ai(t)?t.type==="stdio"&&typeof t.command=="string"&&bR(t.command,t.args):!1}function zH(t){return!Ai(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&TR(t.command[0])&&t.command[1]==="mcp"||t.command.length===3&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&typeof t.command[2]=="string"&&ER(t.command[0],[t.command[1],t.command[2]])}function YH(t){return Ai(t)?t.type==="stdio"&&wR(t.command,t.args):!1}function QH(t){return!Ai(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&SR(t.command[0])&&t.command[1]==="mcp"}function bR(t,e){return TR(t)&&kR(e)||ER(t,e)}function wR(t,e){return SR(t)&&kR(e)}function ER(t,e){return ZH(t)&&Array.isArray(e)&&e.length===2&&eB(e[0])&&e[1]==="mcp"}function TR(t){return typeof t=="string"&&Gg(t)==="lmctl"}function SR(t){return typeof t=="string"&&Gg(t)==="lmctl0"}function ZH(t){if(typeof t!="string")return!1;let e=Gg(t).toLowerCase();return e==="node"||e==="node.exe"}function eB(t){if(typeof t!="string")return!1;let e=t.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function Gg(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(r=>r.length>0).at(-1)??e}function kR(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function Ai(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var _u,vu,jH,Yt,Xg,wu=L(()=>{"use strict";Se();_u="lmctl",vu="lmctl0",jH={existsSync:OH,mkdirSync:LH,readFileSync:MH,writeFileSync:FH,renameSync:PH,unlinkSync:DH},Yt=jH});import{createHash as nB}from"node:crypto";import{accessSync as rB,constants as RR,existsSync as sB,readFileSync as Vg,realpathSync as Kg,statSync as iB,writeFileSync as IR}from"node:fs";import{dirname as Is,resolve as xR}from"node:path";function NR(t){return WE(t,Eu!==void 0?{snapshot:Eu}:{})}function OR(t){return qE(t,Eu!==void 0?{snapshot:Eu}:{})}async function cB(t,e,n){let r=t.filter(i=>i.teamfile===void 0&&i.provider.trim().toLowerCase()==="opencode"&&i.model!==void 0&&i.model.length>0);return(await Promise.all(r.map(async i=>({member:i,result:await lB({cwd:i.sessiondir??e,model:i.model,...i.effort!==void 0?{effort:i.effort}:{},...n!==void 0?{env:n}:{}})})))).flatMap(({member:i,result:o})=>o.status==="rejected"?[`[${i.alias}] ${o.option}="${o.value}" rejected by opencode: ${o.error}`]:[])}function uB(t,e){let n=Is(e),r=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??n,a=xR(o);if(r.has(a))continue;let l=dB(a);l!==void 0&&(r.add(a),s.push(`${i.alias}: sessiondir ${a} is not writable (seed would fail: ${l}) \u2014 fix permissions or set a writable sessiondir`))}return s}function dB(t){try{if(Ni.existsSync(t)){if(!Ni.statSync(t).isDirectory())return"ENOTDIR";Ni.accessSync(t,RR.W_OK);return}let e=pB(t);if(e===void 0)return;if(!Ni.statSync(e).isDirectory())return"ENOTDIR";Ni.accessSync(e,RR.W_OK);return}catch(e){return fB(e)??"permission check failed"}}function mB(t){let e=xR(t);try{return Kg(e)}catch{return e}}function pB(t){let e=t;for(;;){try{if(Ni.existsSync(e))return e}catch{return}let n=Is(e);if(n===e)return;e=n}}function fB(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}async function gB(t,e){let n;try{n=await he(e,l=>Tt(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let r;try{r=Dt(n)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=up(r,Is(n));e.stderr.write(`notice: checking teamfile and models ...
|
|
2313
2313
|
`);let i=Pp(r.members,{agyModelsRunner:AR,codexModelsRunner:CR});i.push(...await NR(r.members)),s.push(...await OR(r.members));let o=Vg(n,"utf8"),a=uR(o,dR({workdir:Is(n),teamfile:n,date:new Date})).unknownNames;a.length>0&&i.push(`unknown template placeholder${a.length===1?"":"s"}: ${a.map(l=>`{{${l}}}`).join(", ")}`),i.push(...$p(r.members,Is(n))),i.push(...uB(r.members,n)),i.push(...await cB(r.members,Is(n),e.env));for(let l of s)e.stderr.write(`error: ${l.field}: ${l.message}
|
|
@@ -2340,46 +2340,46 @@ ${i}`:`${n}
|
|
|
2340
2340
|
${t}`:`${n}
|
|
2341
2341
|
`}function tr(t,e){return t.stderr.write(`error: ${e}
|
|
2342
2342
|
`),1}function zg(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_
|
|
2343
|
-
`)}var Oi,oB,aB,Ni,lB,AR,CR,Eu,hB,yB,PR=L(()=>{"use strict";So();xp();
|
|
2344
|
-
`)||`Seed failed with exit code ${m}`,{seeded:r})}catch(i){return H(nr(i),G(i),{seeded:r})}}function DR(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 FR=L(()=>{"use strict";
|
|
2345
|
-
`);return de({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(nr(r),G(r))}}var $R=L(()=>{"use strict";
|
|
2343
|
+
`)}var Oi,oB,aB,Ni,lB,AR,CR,Eu,hB,yB,PR=L(()=>{"use strict";So();xp();bn();XE();jp();rf();op();yu();Nr();_s();mR();wu();hp();ze();Oi=5,oB={existsSync:sB,statSync:iB,accessSync:rB},aB=async t=>{let{seed:e}=await Promise.resolve().then(()=>(er(),rR)),n=await e(t);return n.success?{sessionId:n.sessionId,warnings:n.warnings,usage:Gn(n)}:{error:n.error??"provider seed failed",errorCode:n.errorCode,usage:Gn(n),sessionId:n.sessionId}},Ni=oB,lB=Rc;hB=/^\[([^\]]+)\]\s+(.*)$/s,yB=/^([^:\s][^:]*):\s+(.*)$/s});function me(t){if(!li(t))return H("invalid_argument","Expected a context created by createLmctlContext");if(t.closed)return H("cancelled","Context is closed")}function nr(t){try{let e=t?.code;return e==="ENOENT"?"missing":e==="EACCES"||e==="EPERM"||e==="EISDIR"?"read":"schema"}catch{return"read"}}function st(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 rr(t){return at.find(e=>e.name===t)?.params.find(e=>e.name==="options")?.keys?.map(e=>e.name)??[]}var Qt=L(()=>{"use strict";pn();zt();tt()});import{existsSync as IB}from"node:fs";import{resolve as pa}from"node:path";function xB(t,e){try{let n=me(t);if(n)return n;if(typeof e!="string"||!e)return H("invalid_argument","Teamfile must be a nonempty string");let r=Dt(pa(t.cwd,e));return de({members:r.members.map(s=>({alias:s.alias,provider:s.provider,model:s.model,sessionid:s.session,sessiondir:s.sessiondir}))})}catch(n){return H(nr(n),G(n))}}function AB(t,e,n){try{let r=me(t);if(r)return r;if(typeof e!="string"||!Co(e)||typeof n!="string"||!_p(n))return H("invalid_argument","Expected a teamfile path and valid alias");let s=Ft(pa(t.cwd,e),n,t.dal);return de({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 Me?r.kind:void 0}catch{}return s==="not_found"&&!G(r).includes("teamfile not found")?{status:"not_found",code:"not_found",error:G(r)}:H(s==="not_found"?"schema":s??nr(r),G(r))}}async function CB(t,e){try{let n=me(t);if(n)return n;if(typeof e!="string"||!e)return H("invalid_argument","Teamfile must be a nonempty string");let r=await LR(pa(t.cwd,e),st(t)),s={errors:r.errors,warnings:r.warnings,counts:r.counts};return r.status==="ok"?de(s):H("schema",r.errors.map(i=>i.message).join("; "),s)}catch(n){let r=G(n);return H(nr(n),r,{errors:[{alias:"",message:r}],warnings:[],counts:{errors:1,warnings:0}})}}async function NB(t,e,n={}){let r=[],s=!1;try{let i=me(t);if(i)return i;if(typeof e!="string"||!e)return H("invalid_argument","Teamfile must be a nonempty string");if(!IB(pa(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=at.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=DR(c),d=st(t,(p,f)=>{f==="stderr"&&u(p)});s=!0;let m=await MR(pa(t.cwd,e),d,{signal:t.signal,...l===void 0?{}:{preamble:l},onSeeded:p=>{r.push({...p})}});return m===0?de({seeded:r}):H("provider",c.join(`
|
|
2344
|
+
`)||`Seed failed with exit code ${m}`,{seeded:r})}catch(i){return H(nr(i),G(i),{seeded:r})}}function DR(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 FR=L(()=>{"use strict";pn();bn();qn();PR();Qt();tt()});import{readFileSync as OB}from"node:fs";import{resolve as LB}from"node:path";function MB(t,e,n={}){try{let r=me(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=at.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=OB(LB(t.cwd,e),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2345
|
+
`);return de({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(nr(r),G(r))}}var $R=L(()=>{"use strict";pn();Qt();tt()});import{join as it}from"node:path";function sr(t){let e=jR.get(t);if(e)return e;let n=t.env.HOME;if(!n)return zn(Zn());let r=t.env.XDG_DATA_HOME||it(n,".local/share"),s=t.env.XDG_CONFIG_HOME||it(n,".config");return e=zn(Zn({museDataHome:r,miniplayerHome:t.env.MINIPLAYER_HOME||it(r,"miniplayer"),claudeDir:it(n,".claude"),codexDir:it(n,".codex"),codeDir:it(n,".code"),geminiDir:it(n,".gemini"),copilotDir:it(n,".copilot"),qwenDir:it(n,".qwen"),opencodeDbPaths:[it(r,"opencode/opencode.db"),it(s,"opencode/opencode.db")],agyDir:it(n,".gemini/antigravity-cli"),dshHome:it(n,".dsh"),hermesHome:t.env.HERMES_HOME??it(n,".hermes"),kimiHome:t.env.KIMI_CODE_HOME??it(n,".kimi-code"),piDir:it(n,".pi/agent/sessions"),lmplayerDbPaths:zp(t.env,n)})),jR.set(t,e),e}var jR,Tu=L(()=>{"use strict";er();Xo();jR=new WeakMap});import{resolve as PB}from"node:path";function UR(t){let e=new Date(t.clock());return[e.getHours(),e.getMinutes(),e.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}async function HR(t,e,n,r,s,i){let o=null,a=!1,l="invalid_argument",c,u,d=new Set,m=(h,y="",b=null,_)=>({status:h,reply:y,error:b,sessionid:o,messageId:null,teamChatLogId:null,..._?{code:_}:{}}),p,f,g={status:"error"};try{let h=me(t);if(h)return m("error","",h.error,h.code);if(!e||typeof e!="object"||Array.isArray(e))throw Error("promptAgent: member must be a map");let y={};for(let S of["provider","alias","model","effort","sessiondir","sessionid"]){let R=e[S];if(R!=null&&(typeof R!="string"||!R.trim()))throw Error(`promptAgent: ${S} must be a nonempty string when supplied`);R!=null&&(y[S]=R)}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(S=>!rr("promptAgent").includes(S)))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=xr(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=st(t);l="provider",E.stderr.write(`agent ${UR(t)}: prompting ${y.alias??y.provider}
|
|
2346
2346
|
`);let I=t.clock(),T=I,k=setInterval(()=>{try{let S=t.clock();S-T>=5e3&&E.stderr.write(`agent ${UR(t)}: still running (${Math.round((S-I)/1e3)}s elapsed)
|
|
2347
2347
|
`)}catch(S){u=S,clearInterval(k)}},5e3);k.unref(),c={poke(){try{T=t.clock()}catch(S){u=S}},stop(){clearInterval(k)}};let N=y.provider,C=PB(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 S,R;try{R=await Ug({provider:N,cwd:C,model:y.model,effort:y.effort,env:{...t.env},signal:t.signal,onDispatch:()=>{S??=Lo(E,{provider:N,cwd:C,modelRequested:y.model??null,sessionId:""},"agent")}}),await S?.finish({status:t.signal.aborted?"cancelled":R.success&&R.sessionId?"ok":"error",sessionId:R.sessionId,usage:Gn(R)})}catch(A){throw await S?.finish(Mo(A,t.signal)),A}for(let A of R.warnings??[])E.stderr.write(`warning: ${A}
|
|
2348
2348
|
`);if(!R.success||!R.sessionId)throw Error(R.error??"promptAgent: provider did not identify the seeded session");o=R.sessionId;let x=JSON.stringify([N,o]);if(p.activeSessions.has(x)||!s&&p.handoffSessions.has(x))return m("busy","","promptAgent: seeded session is already active","busy");p.activeSessions.add(x),d.add(x)}let O=o??"";f=Lo(E,{provider:N,cwd:C,modelRequested:y.model??null,sessionId:O},"agent");let w=await ca({provider:N,cwd:C,sessionId:O,prompt:n,model:y.model,effort:y.effort,alias:y.alias,isLead:!1,permissionMode:b,timeoutMs:_,requireResume:!!O,env:{...t.env},signal:t.signal,onDelta:()=>c?.poke(),onProgress:()=>c?.poke()});if(g={status:t.signal.aborted?"cancelled":w.status??"ok",usage:Gn(w),sessionId:w.sessionId},u!==void 0)throw u;for(let S of w.warnings??[])E.stderr.write(`warning: ${S}
|
|
2349
|
-
`);return O&&w.sessionId!==O?(g.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):(g.status=t.signal.aborted?"cancelled":"error",m("error",w.text,"promptAgent: provider did not return a session ID","provider")))}catch(h){return g=Mo(h,t.signal,g),m("error","",G(h),l)}finally{if(await f?.finish(g),c?.stop(),a&&p){p.activeAgents.delete(e);for(let h of d)p.activeSessions.delete(h)}}}async function BR(t,e,n,r={}){return HR(t,e,n,r,!1)}async function WR(t,e,n,r={},s){return HR(t,e,n,r,!0,s)}var Yg=L(()=>{"use strict";er();zt();Qt();
|
|
2350
|
-
${i}`)}function Mi(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=Li(r,n);return{...t,detail:s,provider_message:s}}var $B,jB,ir=L(()=>{"use strict";$B="https://lmctl.com/schemas/lmratelimit-v1.json";jB=[/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 UB}from"node:child_process";import{readdirSync as HB,readFileSync as BB}from"node:fs";import{join as WB}from"node:path";function QB(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function ZB(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 eW(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 tW(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=eW(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=ft(o/100);n.push(Ut({bucket_id:`${ZB(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:ft(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 ga(t,e,n){return kt("agy","provider_unavailable",t,e,"agy_cli_print")}function nW(t,e,n={}){try{let r=KB(Math.max(t,60)*1e3,QB(e));if(Ht(n,"agy_cli_print",r.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),r.error?.code==="ENOENT")return ga("agy_not_found","the agy CLI is not on PATH",t);if(r.error?.code==="ETIMEDOUT")return ga("cli_timeout","agy -p /usage did not finish in time",t);if(r.error)return ga("cli_failed",r.error.message,t);let s=tW(r.stdout??"");return s.length===0?ga("cli_unparseable",`exit ${r.status??1}; no buckets parsed from CLI output`,t):ze("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(r){return ga("cli_failed",r instanceof Error?r.message:String(r),t)}}function iI(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 rW(t){let e=[],n=new Set,r=(s,i,o)=>{if(!s||!i)return;let a=iI(s);!a||n.has(`${a}\0${i}`)||(n.add(`${a}\0${i}`),e.push([a,i,o]))};r(t[rI],t[sI],-1);try{for(let s of HB("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of BB(WB("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}r(i[rI],i[sI],Number(s))}catch{}}catch{}return e}function sW(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=xn(l.remainingFraction,"fraction");r.push(Ut({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:tI(l.window),used_fraction:c===null?null:ft(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??""))),ze("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:r}))}async function iW(t,e,n={}){try{let s=YB(e).map(([a,l,c])=>[iI(a),l,c]).filter(a=>a[0]!==null);if(s.length===0)return kt("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 zB(`http://${a}${qB}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":l},u);if(Ht(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=sW(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 kt("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 kt("agy","provider_unavailable","connect_failed",r instanceof Error?r.message:String(r),"agy_connect_rpc")}}async function oI(t){let e=await iW(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let n=nW(t.timeoutSeconds,t.env,t);return n.status==="ok"?n:kt("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 rI,sI,qB,XB,GB,JB,VB,KB,zB,YB,aI=L(()=>{"use strict";ir();ir();rI="ANTIGRAVITY_LS_ADDRESS",sI="ANTIGRAVITY_CSRF_TOKEN",qB="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",XB=["-p","/usage"],GB=(t,e)=>{let n=UB("agy",XB,{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}},JB=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()}},VB=t=>rW(t),KB=GB,zB=JB,YB=VB});import{randomUUID as uI}from"node:crypto";import{mkdirSync as oW,readFileSync as Qg,realpathSync as aW,renameSync as lW,rmSync as Zg,statSync as lI,writeFileSync as dI}from"node:fs";import{homedir as cW}from"node:os";import{join as eh}from"node:path";import{setTimeout as uW}from"node:timers/promises";function rh(t){return eh(t.CLAUDE_CONFIG_DIR??eh(t.HOME??cW(),".claude"),".credentials.json")}function th(t){let e=JSON.parse(Qg(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function nh(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function mI(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=rh(t);try{let n=nh(th(e));return typeof n?.accessToken=="string"&&n.accessToken?{oauth:n,path:aW(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 Ru(t){return typeof t.expiresAt=="number"&&Date.now()+pW>=t.expiresAt}function cI(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function fW(t,e){let n=`${t}.lmctl-refresh.lock`,r=eh(n,"owner.json"),s=uI();for(;;){e.throwIfAborted();try{oW(n,{mode:448});try{dI(r,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Zg(n,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(Qg(r,"utf8")).token===s&&Zg(n,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(Qg(r,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-lI(n).mtimeMs>6e4}catch{try{o=Date.now()-lI(n).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await uW(50,void 0,{signal:e})}}}async function pI(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let n=await fW(t.path,e);try{let r=nh(th(t.path));if(!r||typeof r.accessToken!="string")throw new Error("credentials_changed");if(!cI(r,t.oauth)&&!Ru(r))return r;if(typeof r.refreshToken!="string"||!r.refreshToken)throw new Error("no_refresh_token");let s=await fetch(mW,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:r.refreshToken,client_id:dW})});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=th(t.path),l=nh(a);if(!l||!cI(r,l)){if(l&&typeof l.accessToken=="string"&&!Ru(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}.${uI()}.tmp`;try{dI(u,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),lW(u,t.path)}finally{Zg(u,{force:!0})}return c}finally{n()}}var dW,mW,pW,fI=L(()=>{"use strict";dW="9d1c250a-e61b-44d9-88ed-5944d1962f5e",mW="https://console.anthropic.com/v1/oauth/token",pW=3e5});import{spawnSync as yI}from"node:child_process";function yW(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 _I(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function _W(t){try{let e=yI("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:_I(t)}),n=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(n)return`claude-code/${n}`}catch{}return"claude-code/unknown"}function ln(t,e,n,r="claude_oauth_api",s){return kt("claude",t,e,n,r,void 0,s)}function vW(t){let e=t.get("retry-after");if(!e)return;let n=Number.parseInt(e,10);return Number.isFinite(n)?n:void 0}function bW(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 EW(t){let e=[];for(let n of t.split(/\r?\n/)){let r=wW.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(Ut({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:xn(Number(r[2]),"percent"),raw_value:Number(r[2]),raw_scale:"used_percent",resets_at:bW(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 TW(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 SW(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=xn(s?n?.percent:r?.utilization,"percent"),g=s?n?.spend_limit_reached??r?.spend_limit_reached:r?.spend_limit_reached,h={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 g=="boolean"?{reached:g}:{}};return Object.values(h).every(y=>y==null)?void 0:h}async function hI(t,e,n,r={}){try{let s=yI("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(n,60)*1e3,input:"",env:_I(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";Ht(r,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=EW(i);if(!o.length)return;let a=TW(i);return ze("claude",Ye.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 vI({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s=mI(e);if(s.error==="not_claude_ai_subscriber")return ln(Ye.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return ln(Ye.unavailable,"credentials_missing",`credentials file not found: ${rh(e)}`);if(s.error)return ln(Ye.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(gI))return ln(Ye.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${gI} 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 pI({...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 ln(Ye.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(E==="refresh_lock_stale")return ln(Ye.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 I=E==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(E);return ln(I?Ye.expired:Ye.unavailable,I?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${E})${I?"; renew Claude login":"; try again later"}`)}};if(Ru(i)){let v=await b();if(v)return v}let _=()=>fetch(`${gW}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":hW,"Content-Type":"application/json","User-Agent":_W(e)},signal:a.signal});if(c=await _(),u=await c.text(),Ht({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(),Ht({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||ln(Ye.unavailable,"request_failed",`${y instanceof Error?y.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let d=(...y)=>Mi(ln(...y),u,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return d(Ye.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return d(Ye.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let y=vW(c.headers),b=await hI(i,e,t,{debug:n,onRawResponse:r});return b||d(Ye.throttled,"rate_limited",`usage endpoint rate limited${y==null?"":`; retry after ${y}s`}`,"claude_oauth_api",y)}if(c.status!==200)return d(Ye.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let m;try{m=JSON.parse(u)}catch{return ln(Ye.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!m||typeof m!="object"||Array.isArray(m))return ln(Ye.unavailable,"malformed_response","response was not an object");let p=m,f=Array.isArray(p.limits)?p.limits:[],g=f.length?f.flatMap(y=>{if(!y||typeof y!="object")return[];let b=y.kind,_=yW(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[Ut({bucket_id:E,group_name:b==="session"?"session":"weekly",window_type:_,used_fraction:xn(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"?[]:[Ut({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:xn(b.utilization,"percent"),resets_at_iso:b.resets_at,raw_value:b.utilization,raw_scale:"used_percent"})]}),h=SW(p.spend,p.extra_usage);return ze("claude",Ye.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:g.sort((y,b)=>String(y.window_type).localeCompare(String(b.window_type))||String(y.bucket_id).localeCompare(String(b.bucket_id))),...h?{spend_control:h}:{}})}var gW,hW,gI,Ye,wW,bI=L(()=>{"use strict";ir();fI();ir();gW="https://api.anthropic.com",hW="oauth-2025-04-20",gI="user:profile";Ye={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};wW=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/});import{randomUUID as TI}from"node:crypto";import{mkdirSync as kW,readFileSync as sh,realpathSync as RW,renameSync as IW,rmSync as ih,statSync as wI,writeFileSync as SI}from"node:fs";import{homedir as xW}from"node:os";import{join as oh}from"node:path";import{setTimeout as AW}from"node:timers/promises";function ha(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function lh(t){if(t.CODEX_AUTH_PATH)return t.CODEX_AUTH_PATH;let e=t.CODEX_HOME||oh(t.HOME||xW(),".codex");return oh(e,"auth.json")}function ah(t){let e=ha(JSON.parse(sh(t,"utf8")));if(!e)throw new Error("invalid credential document");return e}function kI(t){if(t.CODEX_ACCESS_TOKEN)return{tokens:{access_token:t.CODEX_ACCESS_TOKEN,account_id:t.CODEX_ACCOUNT_ID}};let e=lh(t);try{let n=ha(ah(e).tokens);return typeof n?.access_token=="string"&&n.access_token?{tokens:n,path:RW(e)}:{error:"credentials_missing"}}catch(n){return{error:n.code==="ENOENT"?"credentials_missing":"credentials_unreadable"}}}function EI(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 OW(t,e){let n=`${t}.lmctl-refresh.lock`,r=oh(n,"owner.json"),s=TI();for(;;){e.throwIfAborted();try{kW(n,{mode:448});try{SI(r,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw ih(n,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(sh(r,"utf8")).token===s&&ih(n,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(sh(r,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-wI(n).mtimeMs>6e4}catch{try{o=Date.now()-wI(n).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await AW(50,void 0,{signal:e})}}}async function RI(t,e){if(!t.path||typeof t.tokens?.refresh_token!="string"||!t.tokens.refresh_token)throw new Error("no_refresh_token");let n=await OW(t.path,e);try{let r=ah(t.path),s=ha(r.tokens);if(!s||typeof s.access_token!="string")throw new Error("credentials_changed");if(!EI(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(CW,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:s.refresh_token,client_id:NW})});if(!i.ok)throw new Error(`refresh_http_${i.status}`);let o=ha(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=ah(t.path),l=ha(a.tokens);if(!l||!EI(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}.${TI()}.tmp`;try{SI(d,JSON.stringify(u),{flag:"wx",mode:384}),IW(d,t.path)}finally{ih(d,{force:!0})}return c}finally{n()}}var CW,NW,II=L(()=>{"use strict";CW="https://auth.openai.com/oauth/token",NW="app_EMoamEEZ73f0CkXaXp7hrann"});function An(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xI(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 AI(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function PW(t){if(An(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function DW(t){let e=[],n=An(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=An(n[o])?n[o]:void 0;if(!a)continue;let l=xI(a.limit_window_seconds);e.push(Ut({bucket_id:`codex-${AI(l)}`,group_name:"codex",window_type:l,used_fraction:xn(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(!An(o))continue;let a=An(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=An(a[p])?a[p]:void 0;if(!f)continue;let g=xI(f.limit_window_seconds);e.push(Ut({bucket_id:`${u}-${AI(g)}`,group_name:l||u,window_type:g,used_fraction:xn(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 FW(t){let e=An(t.rate_limit)?t.rate_limit:{},n=typeof e.allowed=="boolean"?e.allowed:void 0,r=An(t.spend_control)?t.spend_control:void 0,s=An(t.credits)?t.credits:void 0;return ze("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...n===void 0?{}:{ordinary_usage_allowed:n},buckets:DW(t),...s?{credits:PW(s)}:{},...r?{spend_control:r}:{}})}async function CI(t){let{timeoutSeconds:e,env:n,debug:r,onRawResponse:s}=t,i=kI(n),o=i.tokens;if(!o||typeof o.access_token!="string")return ze("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:`no access_token in ${lh(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="",g=()=>[...u],h=(I,T)=>Mi(ze("codex",I,T),f,g()),y=!1,b=async()=>{if(!(y||!i.path||typeof o.refresh_token!="string"))try{let I=await RI({...i,tokens:{...o,refresh_token:m}},a.signal);typeof I.access_token=="string"&&(u.add(I.access_token),c=I.access_token),d=typeof I.account_id=="string"?I.account_id:d,typeof I.refresh_token=="string"&&(u.add(I.refresh_token),m=I.refresh_token),typeof I.id_token=="string"&&(u.add(I.id_token),p=I.id_token),y=!0;return}catch(I){let T=I instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(I.message)?I.message:"refresh_failed",k=T==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(T);return ze("codex",k?"auth_expired":"provider_unavailable",{source:"codex_http",reason:k?"oauth_token_expired_or_invalid":"oauth_refresh_failed",detail:`Codex OAuth refresh failed (${T})${k?"; renew Codex login":"; try again later"}`})}},_=()=>{let I={Authorization:`Bearer ${c}`,"User-Agent":MW,"Content-Type":"application/json",Accept:"application/json"};d&&(I["ChatGPT-Account-Id"]=d);let T=(n.CODEX_BASE_URL||LW).replace(/\/$/,"");return fetch(`${T}/wham/usage`,{headers:I,signal:a.signal})},v=await _();if(f=await v.text(),Ht({debug:r,onRawResponse:s},"codex_http",f,g(),v.status),v.status===401&&i.path&&m){let I=await b();if(I)return I;v=await _(),f=await v.text(),Ht({debug:r,onRawResponse:s},"codex_http",f,g(),v.status)}if(v.status===401)return h("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(v.status===429){let I=v.headers.get("retry-after"),T=I===null?void 0:Number.parseInt(I,10);return h("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...T!==void 0&&Number.isFinite(T)&&T>=0?{retry_after_seconds:T}:{}})}if(!v.ok)return h("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(I){return ze("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:Li(String(I),u)})}return An(E)?FW(E):ze("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 ze("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:Li(m,u)})}finally{clearTimeout(l)}}var LW,MW,NI=L(()=>{"use strict";ir();II();ir();LW="https://chatgpt.com/backend-api",MW="codex-cli"});import{createHash as $W,randomUUID as jW}from"node:crypto";import{readFileSync as DI,openSync as UW,fsyncSync as HW,closeSync as BW,mkdirSync as OI,writeFileSync as FI,renameSync as WW,rmSync as qW,rmdirSync as XW,statSync as ch,utimesSync as GW}from"node:fs";import{homedir as JW}from"node:os";import{basename as VW,dirname as KW,join as Iu}from"node:path";import{setTimeout as $I}from"node:timers/promises";function YW(t){let e;try{e=DI(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 xu(t){let e;try{e=JSON.parse(DI(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 jI(t){let e=t.KIMI_CODE_HOME??Iu(t.HOME??JW(),".kimi-code"),n=YW(t.KIMI_CODE_CONFIG_PATH??Iu(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=MI(t.KIMI_CODE_BASE_URL??n.base_url??LI),i=MI(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(r?uh:n["oauth.oauth_host"]??uh)),o=s===LI&&i===uh?"kimi-code":`kimi-code-env-${$W("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??Iu(e,"credentials",`${o}.json`),l=xu(a),c=a,u=VW(a,".json");return{home:e,path:c,lockTarget:Iu(e,"oauth",u),baseUrl:s,oauthHost:i,token:l}}function Au(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 PI(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 QW(t,e){OI(KW(t),{recursive:!0}),FI(t,"",{flag:"a",mode:384});let n=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{OI(n);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-ch(n).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await $I(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let r=ch(n),s=()=>{let o;try{o=ch(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;GW(n,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),XW(n)}catch{}}}}async function UI(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let n=await QW(t.lockTarget,e);try{let r=xu(t.path);if(!PI(r,t.token)&&!Au(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:zW,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 $I(1e3*2**d,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let d=xu(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=xu(t.path);if(!PI(l,r)){if(!Au(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}.${jW()}.tmp`;try{let d=UW(u,"wx",384);try{FI(d,JSON.stringify(c,null,2)+`
|
|
2351
|
-
`),HW(d)}finally{BW(d)}n.assertOwned(),WW(u,t.path)}finally{qW(u,{force:!0})}return c}finally{n.release()}}var LI,uh,zW,MI,HI=L(()=>{"use strict";LI="https://api.kimi.com/coding/v1",uh="https://auth.kimi.com",zW="17e5f671-d194-4dfb-9706-5516cb48c098",MI=t=>t.trim().replace(/\/+$/,"")});function BI(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 WI({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s;try{s=jI(e)}catch(g){let h=g instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(g.message)?g.message:"credentials_unreadable";return kt("kimi",h==="credentials_revoked"?"auth_expired":"provider_unavailable",h,h==="credentials_revoked"?"Kimi login was revoked; run kimi login":h.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let g=!1,h=async()=>{i=await UI({...s,token:i},o.signal),g=!0};Au(i)&&await h();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(),Ht({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!g&&i.refresh_token&&(await h(),l=await y(),c=await l.text(),Ht({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(g){let h=g 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(g.message)?g.message:"request_failed",y=h==="credentials_revoked"||h==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(h),b=h==="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 (${h}); run kimi login`:`Kimi quota request failed (${h})`;return kt("kimi",y?"auth_expired":"provider_unavailable",h,b,"kimi_http")}finally{clearTimeout(a)}let u=(g,h,y)=>Mi(kt("kimi",g,h,h,"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 g=nI(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",g)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return kt("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return kt("kimi","provider_unavailable","malformed_response","response was not an object");let m=[],p=new Set;function f(g){let h=String(g.bucket_id),y=h,b=2;for(;p.has(h);)h=`${y}-${b}`,b++;p.add(h),g.bucket_id=h,m.push(Ut(g))}if(Array.isArray(d.limits))for(let g of d.limits){if(!g||typeof g!="object")continue;let h=g.window,y=g.detail;if(!h||typeof h!="object"||!y||typeof y!="object")continue;let b=0;if(h.timeUnit==="TIME_UNIT_MINUTE")b=Number(h.duration);else if(h.timeUnit==="TIME_UNIT_HOUR")b=Number(h.duration)*60;else if(h.timeUnit==="TIME_UNIT_DAY")b=Number(h.duration)*1440;else if(h.timeUnit==="TIME_UNIT_WEEK")b=Number(h.duration)*10080;else if(h.timeUnit==="TIME_UNIT_MONTH")b=Number(h.duration)*43200;else continue;let _=eI(b),v="window";_==="five_hour"&&(v="5h"),_==="weekly"&&(v="weekly"),_==="monthly"&&(v="monthly");let E=BI(y);if(!E)continue;let{used:I,limit:T,remaining:k}=E;f({bucket_id:`kimi-${v}`,window_type:_,used_fraction:ft(I/T),remaining_fraction:ft(k/T),resets_at_iso:y.resetTime,raw_value:I,raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let g=BI(d.usage);g&&f({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:ft(g.used/g.limit),remaining_fraction:ft(g.remaining/g.limit),resets_at_iso:d.usage.resetTime,raw_value:g.used,raw_scale:"count"})}if(d.usages&&typeof d.usages=="object"){let g=[{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:h,id:y,type:b}of g){let _=d.usages[h];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(Ut({bucket_id:y,window_type:b,used_fraction:ft(v),resets_at_iso:typeof _.reset_time=="string"&&_.reset_time?_.reset_time:null,raw_value:v,raw_scale:"ratio"})))}}return
|
|
2352
|
-
`,"stderr")});return a.status==="ok"?de({readings:a.readings}):H("provider",a.error,{readings:[]})}catch(n){return H("provider",G(n),{readings:[]})}}var VI=L(()=>{"use strict";JI();Qt();
|
|
2349
|
+
`);return O&&w.sessionId!==O?(g.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):(g.status=t.signal.aborted?"cancelled":"error",m("error",w.text,"promptAgent: provider did not return a session ID","provider")))}catch(h){return g=Mo(h,t.signal,g),m("error","",G(h),l)}finally{if(await f?.finish(g),c?.stop(),a&&p){p.activeAgents.delete(e);for(let h of d)p.activeSessions.delete(h)}}}async function BR(t,e,n,r={}){return HR(t,e,n,r,!1)}async function WR(t,e,n,r={},s){return HR(t,e,n,r,!0,s)}var Yg=L(()=>{"use strict";er();zt();Qt();tt();xp()});import{randomUUID as DB}from"node:crypto";import{resolve as FB}from"node:path";function fa(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",G(e))}}function ku(t){return JSON.stringify([t.provider,t.sessionid])}function qR(t,e){try{let n=me(t);if(n)return n;let r=fa(e);if("status"in r)return r;let s=xr(t),i=ku(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"}:de({})}catch(n){return H("invalid_argument",G(n))}}async function XR(t,e,n,r,s={}){let i=e&&typeof e=="object"?Su.get(e):void 0;return!i||i.ctx!==t||xr(t).reservations.get(i.key)!==e?{status:"error",error:"Invalid or released session reservation",code:"invalid_argument",reply:"",sessionid:null,messageId:null,teamChatLogId:null}:WR(t,n,r,s,i.key)}function GR(t,e){try{let n=me(t);if(n)return n;let r=fa(e);if("status"in r)return r;let s=xr(t),i=ku(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:DB()}),a=!1,l=()=>{},c=()=>{a||(a=!0,s.reservations.get(i)===o&&(s.handoffSessions.delete(i),s.reservations.delete(i)),l())};return l=_n(t,{async close(){c()},finalizeSync(){c()}}),Su.set(o,{ctx:t,key:i,release:c}),s.handoffSessions.add(i),s.reservations.set(i,o),de({reservation:o})}catch(n){return H("invalid_argument",G(n))}}function JR(t,e,n=void 0){try{let r=me(t);if(r&&!(r.code==="cancelled"&&n))return r;let s=fa(e);if("status"in s)return s;let i=xr(t),o=ku(s);if(n!==void 0){let l=Su.get(n);return!l||l.ctx!==t||l.key!==o?H("invalid_argument","Reservation target does not match this context and session"):(l.release(),de({}))}let a=i.reservations.get(o);return a&&Su.get(a)?.release(),de({})}catch(r){return H("invalid_argument",G(r))}}async function VR(t,e={}){try{let n=me(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=>!rr("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 Hg({registry:sr(t),provider:r,workspace:i?void 0:FB(t.cwd,s??t.cwd)});return de({sessions:o.map(a=>({provider:a.provider,sessionid:a.sessionId,sessiondir:a.cwd,modifiedAt:a.modifiedAt.toISOString()}))})}catch(n){return H("provider",G(n))}}async function KR(t,e){try{let n=me(t);if(n)return n;let r=fa(e);if("status"in r)return r;let s=await sr(t).getSession(r.sessionid,r.provider);return s?de({messages:s.messages.map(i=>({role:i.role,content:i.content}))}):{status:"not_found",error:null}}catch(n){return H("provider",G(n))}}async function zR(t,e,n){try{let r=me(t);if(r)return r;let s=fa(e);if("status"in s)return s;if(!n||typeof n!="object"||Array.isArray(n)||n.force!==!0||Object.keys(n).some(a=>!rr("deleteSession").includes(a)))return H("invalid_argument","force: true is required because cross-process turns cannot be detected");let i=xr(t),o=ku(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 Bg(s.provider,s.sessionid,sr(t))?"deleted":"not_found",error:null}}finally{i.activeSessions.delete(o)}}catch(r){return H("provider",G(r))}}var Su,YR=L(()=>{"use strict";Tu();Yg();er();zt();Qt();tt();Su=new WeakMap});function ft(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 xn(t,e){if(t==null||typeof t=="boolean")return null;let n=Number(t);return ft(e==="percent"?n/100:n)}function QR(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 ZR(t){if(typeof t!="string"||t.trim()==="")return null;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):null}function eI(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 tI(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 Li(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 jB)n=n.replace(r,"***REDACTED***");return n}function Ut(t){let e=ft(t.used_fraction),n=ft(t.remaining_fraction),r=t.resets_at==null?ZR(t.resets_at_iso):Number(t.resets_at),s=t.resets_at_iso==null?QR(r):QR(ZR(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:ft(1-n)),remaining_fraction:n??(e===null?null:ft(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 Ye(t,e,n={}){let r={$schema:$B,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 kt(t,e,n,r,s,i=[],o){return Ye(t,e,{source:s??null,reason:n,...r==null?{}:{detail:Li(r,i)},...o==null?{}:{retry_after_seconds:o}})}function nI(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 Ht(t,e,n,r=[],s){if(!t.debug&&!t.onRawResponse)return;let i=Li(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:
|
|
2350
|
+
${i}`)}function Mi(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=Li(r,n);return{...t,detail:s,provider_message:s}}var $B,jB,ir=L(()=>{"use strict";$B="https://lmctl.com/schemas/lmratelimit-v1.json";jB=[/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 UB}from"node:child_process";import{readdirSync as HB,readFileSync as BB}from"node:fs";import{join as WB}from"node:path";function QB(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function ZB(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 eW(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 tW(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=eW(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=ft(o/100);n.push(Ut({bucket_id:`${ZB(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:ft(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 ga(t,e,n){return kt("agy","provider_unavailable",t,e,"agy_cli_print")}function nW(t,e,n={}){try{let r=KB(Math.max(t,60)*1e3,QB(e));if(Ht(n,"agy_cli_print",r.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),r.error?.code==="ENOENT")return ga("agy_not_found","the agy CLI is not on PATH",t);if(r.error?.code==="ETIMEDOUT")return ga("cli_timeout","agy -p /usage did not finish in time",t);if(r.error)return ga("cli_failed",r.error.message,t);let s=tW(r.stdout??"");return s.length===0?ga("cli_unparseable",`exit ${r.status??1}; no buckets parsed from CLI output`,t):Ye("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(r){return ga("cli_failed",r instanceof Error?r.message:String(r),t)}}function iI(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 rW(t){let e=[],n=new Set,r=(s,i,o)=>{if(!s||!i)return;let a=iI(s);!a||n.has(`${a}\0${i}`)||(n.add(`${a}\0${i}`),e.push([a,i,o]))};r(t[rI],t[sI],-1);try{for(let s of HB("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of BB(WB("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}r(i[rI],i[sI],Number(s))}catch{}}catch{}return e}function sW(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=xn(l.remainingFraction,"fraction");r.push(Ut({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:tI(l.window),used_fraction:c===null?null:ft(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??""))),Ye("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:r}))}async function iW(t,e,n={}){try{let s=YB(e).map(([a,l,c])=>[iI(a),l,c]).filter(a=>a[0]!==null);if(s.length===0)return kt("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 zB(`http://${a}${qB}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":l},u);if(Ht(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=sW(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 kt("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 kt("agy","provider_unavailable","connect_failed",r instanceof Error?r.message:String(r),"agy_connect_rpc")}}async function oI(t){let e=await iW(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let n=nW(t.timeoutSeconds,t.env,t);return n.status==="ok"?n:kt("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 rI,sI,qB,XB,GB,JB,VB,KB,zB,YB,aI=L(()=>{"use strict";ir();ir();rI="ANTIGRAVITY_LS_ADDRESS",sI="ANTIGRAVITY_CSRF_TOKEN",qB="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",XB=["-p","/usage"],GB=(t,e)=>{let n=UB("agy",XB,{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}},JB=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()}},VB=t=>rW(t),KB=GB,zB=JB,YB=VB});import{randomUUID as uI}from"node:crypto";import{mkdirSync as oW,readFileSync as Qg,realpathSync as aW,renameSync as lW,rmSync as Zg,statSync as lI,writeFileSync as dI}from"node:fs";import{homedir as cW}from"node:os";import{join as eh}from"node:path";import{setTimeout as uW}from"node:timers/promises";function rh(t){return eh(t.CLAUDE_CONFIG_DIR??eh(t.HOME??cW(),".claude"),".credentials.json")}function th(t){let e=JSON.parse(Qg(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function nh(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function mI(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=rh(t);try{let n=nh(th(e));return typeof n?.accessToken=="string"&&n.accessToken?{oauth:n,path:aW(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 Ru(t){return typeof t.expiresAt=="number"&&Date.now()+pW>=t.expiresAt}function cI(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function fW(t,e){let n=`${t}.lmctl-refresh.lock`,r=eh(n,"owner.json"),s=uI();for(;;){e.throwIfAborted();try{oW(n,{mode:448});try{dI(r,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Zg(n,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(Qg(r,"utf8")).token===s&&Zg(n,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(Qg(r,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-lI(n).mtimeMs>6e4}catch{try{o=Date.now()-lI(n).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await uW(50,void 0,{signal:e})}}}async function pI(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let n=await fW(t.path,e);try{let r=nh(th(t.path));if(!r||typeof r.accessToken!="string")throw new Error("credentials_changed");if(!cI(r,t.oauth)&&!Ru(r))return r;if(typeof r.refreshToken!="string"||!r.refreshToken)throw new Error("no_refresh_token");let s=await fetch(mW,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:r.refreshToken,client_id:dW})});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=th(t.path),l=nh(a);if(!l||!cI(r,l)){if(l&&typeof l.accessToken=="string"&&!Ru(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}.${uI()}.tmp`;try{dI(u,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),lW(u,t.path)}finally{Zg(u,{force:!0})}return c}finally{n()}}var dW,mW,pW,fI=L(()=>{"use strict";dW="9d1c250a-e61b-44d9-88ed-5944d1962f5e",mW="https://console.anthropic.com/v1/oauth/token",pW=3e5});import{spawnSync as yI}from"node:child_process";function yW(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 _I(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function _W(t){try{let e=yI("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:_I(t)}),n=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(n)return`claude-code/${n}`}catch{}return"claude-code/unknown"}function cn(t,e,n,r="claude_oauth_api",s){return kt("claude",t,e,n,r,void 0,s)}function vW(t){let e=t.get("retry-after");if(!e)return;let n=Number.parseInt(e,10);return Number.isFinite(n)?n:void 0}function bW(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 EW(t){let e=[];for(let n of t.split(/\r?\n/)){let r=wW.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(Ut({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:xn(Number(r[2]),"percent"),raw_value:Number(r[2]),raw_scale:"used_percent",resets_at:bW(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 TW(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 SW(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=xn(s?n?.percent:r?.utilization,"percent"),g=s?n?.spend_limit_reached??r?.spend_limit_reached:r?.spend_limit_reached,h={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 g=="boolean"?{reached:g}:{}};return Object.values(h).every(y=>y==null)?void 0:h}async function hI(t,e,n,r={}){try{let s=yI("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(n,60)*1e3,input:"",env:_I(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";Ht(r,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=EW(i);if(!o.length)return;let a=TW(i);return Ye("claude",Qe.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 vI({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s=mI(e);if(s.error==="not_claude_ai_subscriber")return cn(Qe.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return cn(Qe.unavailable,"credentials_missing",`credentials file not found: ${rh(e)}`);if(s.error)return cn(Qe.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(gI))return cn(Qe.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${gI} 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 pI({...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 cn(Qe.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(E==="refresh_lock_stale")return cn(Qe.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 I=E==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(E);return cn(I?Qe.expired:Qe.unavailable,I?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${E})${I?"; renew Claude login":"; try again later"}`)}};if(Ru(i)){let v=await b();if(v)return v}let _=()=>fetch(`${gW}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":hW,"Content-Type":"application/json","User-Agent":_W(e)},signal:a.signal});if(c=await _(),u=await c.text(),Ht({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(),Ht({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||cn(Qe.unavailable,"request_failed",`${y instanceof Error?y.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let d=(...y)=>Mi(cn(...y),u,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return d(Qe.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return d(Qe.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let y=vW(c.headers),b=await hI(i,e,t,{debug:n,onRawResponse:r});return b||d(Qe.throttled,"rate_limited",`usage endpoint rate limited${y==null?"":`; retry after ${y}s`}`,"claude_oauth_api",y)}if(c.status!==200)return d(Qe.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let m;try{m=JSON.parse(u)}catch{return cn(Qe.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!m||typeof m!="object"||Array.isArray(m))return cn(Qe.unavailable,"malformed_response","response was not an object");let p=m,f=Array.isArray(p.limits)?p.limits:[],g=f.length?f.flatMap(y=>{if(!y||typeof y!="object")return[];let b=y.kind,_=yW(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[Ut({bucket_id:E,group_name:b==="session"?"session":"weekly",window_type:_,used_fraction:xn(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"?[]:[Ut({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:xn(b.utilization,"percent"),resets_at_iso:b.resets_at,raw_value:b.utilization,raw_scale:"used_percent"})]}),h=SW(p.spend,p.extra_usage);return Ye("claude",Qe.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:g.sort((y,b)=>String(y.window_type).localeCompare(String(b.window_type))||String(y.bucket_id).localeCompare(String(b.bucket_id))),...h?{spend_control:h}:{}})}var gW,hW,gI,Qe,wW,bI=L(()=>{"use strict";ir();fI();ir();gW="https://api.anthropic.com",hW="oauth-2025-04-20",gI="user:profile";Qe={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};wW=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/});import{randomUUID as TI}from"node:crypto";import{mkdirSync as kW,readFileSync as sh,realpathSync as RW,renameSync as IW,rmSync as ih,statSync as wI,writeFileSync as SI}from"node:fs";import{homedir as xW}from"node:os";import{join as oh}from"node:path";import{setTimeout as AW}from"node:timers/promises";function ha(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}function lh(t){if(t.CODEX_AUTH_PATH)return t.CODEX_AUTH_PATH;let e=t.CODEX_HOME||oh(t.HOME||xW(),".codex");return oh(e,"auth.json")}function ah(t){let e=ha(JSON.parse(sh(t,"utf8")));if(!e)throw new Error("invalid credential document");return e}function kI(t){if(t.CODEX_ACCESS_TOKEN)return{tokens:{access_token:t.CODEX_ACCESS_TOKEN,account_id:t.CODEX_ACCOUNT_ID}};let e=lh(t);try{let n=ha(ah(e).tokens);return typeof n?.access_token=="string"&&n.access_token?{tokens:n,path:RW(e)}:{error:"credentials_missing"}}catch(n){return{error:n.code==="ENOENT"?"credentials_missing":"credentials_unreadable"}}}function EI(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 OW(t,e){let n=`${t}.lmctl-refresh.lock`,r=oh(n,"owner.json"),s=TI();for(;;){e.throwIfAborted();try{kW(n,{mode:448});try{SI(r,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw ih(n,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(sh(r,"utf8")).token===s&&ih(n,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(sh(r,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-wI(n).mtimeMs>6e4}catch{try{o=Date.now()-wI(n).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await AW(50,void 0,{signal:e})}}}async function RI(t,e){if(!t.path||typeof t.tokens?.refresh_token!="string"||!t.tokens.refresh_token)throw new Error("no_refresh_token");let n=await OW(t.path,e);try{let r=ah(t.path),s=ha(r.tokens);if(!s||typeof s.access_token!="string")throw new Error("credentials_changed");if(!EI(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(CW,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:s.refresh_token,client_id:NW})});if(!i.ok)throw new Error(`refresh_http_${i.status}`);let o=ha(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=ah(t.path),l=ha(a.tokens);if(!l||!EI(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}.${TI()}.tmp`;try{SI(d,JSON.stringify(u),{flag:"wx",mode:384}),IW(d,t.path)}finally{ih(d,{force:!0})}return c}finally{n()}}var CW,NW,II=L(()=>{"use strict";CW="https://auth.openai.com/oauth/token",NW="app_EMoamEEZ73f0CkXaXp7hrann"});function An(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xI(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 AI(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function PW(t){if(An(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function DW(t){let e=[],n=An(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=An(n[o])?n[o]:void 0;if(!a)continue;let l=xI(a.limit_window_seconds);e.push(Ut({bucket_id:`codex-${AI(l)}`,group_name:"codex",window_type:l,used_fraction:xn(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(!An(o))continue;let a=An(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=An(a[p])?a[p]:void 0;if(!f)continue;let g=xI(f.limit_window_seconds);e.push(Ut({bucket_id:`${u}-${AI(g)}`,group_name:l||u,window_type:g,used_fraction:xn(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 FW(t){let e=An(t.rate_limit)?t.rate_limit:{},n=typeof e.allowed=="boolean"?e.allowed:void 0,r=An(t.spend_control)?t.spend_control:void 0,s=An(t.credits)?t.credits:void 0;return Ye("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...n===void 0?{}:{ordinary_usage_allowed:n},buckets:DW(t),...s?{credits:PW(s)}:{},...r?{spend_control:r}:{}})}async function CI(t){let{timeoutSeconds:e,env:n,debug:r,onRawResponse:s}=t,i=kI(n),o=i.tokens;if(!o||typeof o.access_token!="string")return Ye("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:`no access_token in ${lh(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="",g=()=>[...u],h=(I,T)=>Mi(Ye("codex",I,T),f,g()),y=!1,b=async()=>{if(!(y||!i.path||typeof o.refresh_token!="string"))try{let I=await RI({...i,tokens:{...o,refresh_token:m}},a.signal);typeof I.access_token=="string"&&(u.add(I.access_token),c=I.access_token),d=typeof I.account_id=="string"?I.account_id:d,typeof I.refresh_token=="string"&&(u.add(I.refresh_token),m=I.refresh_token),typeof I.id_token=="string"&&(u.add(I.id_token),p=I.id_token),y=!0;return}catch(I){let T=I instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(I.message)?I.message:"refresh_failed",k=T==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(T);return Ye("codex",k?"auth_expired":"provider_unavailable",{source:"codex_http",reason:k?"oauth_token_expired_or_invalid":"oauth_refresh_failed",detail:`Codex OAuth refresh failed (${T})${k?"; renew Codex login":"; try again later"}`})}},_=()=>{let I={Authorization:`Bearer ${c}`,"User-Agent":MW,"Content-Type":"application/json",Accept:"application/json"};d&&(I["ChatGPT-Account-Id"]=d);let T=(n.CODEX_BASE_URL||LW).replace(/\/$/,"");return fetch(`${T}/wham/usage`,{headers:I,signal:a.signal})},v=await _();if(f=await v.text(),Ht({debug:r,onRawResponse:s},"codex_http",f,g(),v.status),v.status===401&&i.path&&m){let I=await b();if(I)return I;v=await _(),f=await v.text(),Ht({debug:r,onRawResponse:s},"codex_http",f,g(),v.status)}if(v.status===401)return h("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(v.status===429){let I=v.headers.get("retry-after"),T=I===null?void 0:Number.parseInt(I,10);return h("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...T!==void 0&&Number.isFinite(T)&&T>=0?{retry_after_seconds:T}:{}})}if(!v.ok)return h("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(I){return Ye("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:Li(String(I),u)})}return An(E)?FW(E):Ye("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 Ye("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:Li(m,u)})}finally{clearTimeout(l)}}var LW,MW,NI=L(()=>{"use strict";ir();II();ir();LW="https://chatgpt.com/backend-api",MW="codex-cli"});import{createHash as $W,randomUUID as jW}from"node:crypto";import{readFileSync as DI,openSync as UW,fsyncSync as HW,closeSync as BW,mkdirSync as OI,writeFileSync as FI,renameSync as WW,rmSync as qW,rmdirSync as XW,statSync as ch,utimesSync as GW}from"node:fs";import{homedir as JW}from"node:os";import{basename as VW,dirname as KW,join as Iu}from"node:path";import{setTimeout as $I}from"node:timers/promises";function YW(t){let e;try{e=DI(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 xu(t){let e;try{e=JSON.parse(DI(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 jI(t){let e=t.KIMI_CODE_HOME??Iu(t.HOME??JW(),".kimi-code"),n=YW(t.KIMI_CODE_CONFIG_PATH??Iu(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=MI(t.KIMI_CODE_BASE_URL??n.base_url??LI),i=MI(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(r?uh:n["oauth.oauth_host"]??uh)),o=s===LI&&i===uh?"kimi-code":`kimi-code-env-${$W("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??Iu(e,"credentials",`${o}.json`),l=xu(a),c=a,u=VW(a,".json");return{home:e,path:c,lockTarget:Iu(e,"oauth",u),baseUrl:s,oauthHost:i,token:l}}function Au(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 PI(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 QW(t,e){OI(KW(t),{recursive:!0}),FI(t,"",{flag:"a",mode:384});let n=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{OI(n);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-ch(n).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await $I(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let r=ch(n),s=()=>{let o;try{o=ch(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;GW(n,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),XW(n)}catch{}}}}async function UI(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let n=await QW(t.lockTarget,e);try{let r=xu(t.path);if(!PI(r,t.token)&&!Au(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:zW,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 $I(1e3*2**d,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let d=xu(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=xu(t.path);if(!PI(l,r)){if(!Au(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}.${jW()}.tmp`;try{let d=UW(u,"wx",384);try{FI(d,JSON.stringify(c,null,2)+`
|
|
2351
|
+
`),HW(d)}finally{BW(d)}n.assertOwned(),WW(u,t.path)}finally{qW(u,{force:!0})}return c}finally{n.release()}}var LI,uh,zW,MI,HI=L(()=>{"use strict";LI="https://api.kimi.com/coding/v1",uh="https://auth.kimi.com",zW="17e5f671-d194-4dfb-9706-5516cb48c098",MI=t=>t.trim().replace(/\/+$/,"")});function BI(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 WI({timeoutSeconds:t,env:e,debug:n,onRawResponse:r}){let s;try{s=jI(e)}catch(g){let h=g instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(g.message)?g.message:"credentials_unreadable";return kt("kimi",h==="credentials_revoked"?"auth_expired":"provider_unavailable",h,h==="credentials_revoked"?"Kimi login was revoked; run kimi login":h.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let g=!1,h=async()=>{i=await UI({...s,token:i},o.signal),g=!0};Au(i)&&await h();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(),Ht({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!g&&i.refresh_token&&(await h(),l=await y(),c=await l.text(),Ht({debug:n,onRawResponse:r},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(g){let h=g 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(g.message)?g.message:"request_failed",y=h==="credentials_revoked"||h==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(h),b=h==="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 (${h}); run kimi login`:`Kimi quota request failed (${h})`;return kt("kimi",y?"auth_expired":"provider_unavailable",h,b,"kimi_http")}finally{clearTimeout(a)}let u=(g,h,y)=>Mi(kt("kimi",g,h,h,"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 g=nI(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",g)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return kt("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return kt("kimi","provider_unavailable","malformed_response","response was not an object");let m=[],p=new Set;function f(g){let h=String(g.bucket_id),y=h,b=2;for(;p.has(h);)h=`${y}-${b}`,b++;p.add(h),g.bucket_id=h,m.push(Ut(g))}if(Array.isArray(d.limits))for(let g of d.limits){if(!g||typeof g!="object")continue;let h=g.window,y=g.detail;if(!h||typeof h!="object"||!y||typeof y!="object")continue;let b=0;if(h.timeUnit==="TIME_UNIT_MINUTE")b=Number(h.duration);else if(h.timeUnit==="TIME_UNIT_HOUR")b=Number(h.duration)*60;else if(h.timeUnit==="TIME_UNIT_DAY")b=Number(h.duration)*1440;else if(h.timeUnit==="TIME_UNIT_WEEK")b=Number(h.duration)*10080;else if(h.timeUnit==="TIME_UNIT_MONTH")b=Number(h.duration)*43200;else continue;let _=eI(b),v="window";_==="five_hour"&&(v="5h"),_==="weekly"&&(v="weekly"),_==="monthly"&&(v="monthly");let E=BI(y);if(!E)continue;let{used:I,limit:T,remaining:k}=E;f({bucket_id:`kimi-${v}`,window_type:_,used_fraction:ft(I/T),remaining_fraction:ft(k/T),resets_at_iso:y.resetTime,raw_value:I,raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let g=BI(d.usage);g&&f({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:ft(g.used/g.limit),remaining_fraction:ft(g.remaining/g.limit),resets_at_iso:d.usage.resetTime,raw_value:g.used,raw_scale:"count"})}if(d.usages&&typeof d.usages=="object"){let g=[{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:h,id:y,type:b}of g){let _=d.usages[h];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(Ut({bucket_id:y,window_type:b,used_fraction:ft(v),resets_at_iso:typeof _.reset_time=="string"&&_.reset_time?_.reset_time:null,raw_value:v,raw_scale:"ratio"})))}}return Ye("kimi","ok",{source:"kimi_http",buckets:m})}var qI=L(()=>{"use strict";ir();HI();ir()});async function GI(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let a of e)if(!XI.includes(a))return{status:"error",error:`unknown provider: ${a} (valid targets: ${XI.join(", ")})`,readings:[]};let n=t.timeoutSeconds??ZW;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=new Set(e.includes("all")?["codex","agy","claude","kimi"]:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${n}s per provider) ...`);let o=Object.entries({codex:CI,agy:oI,claude:vI,kimi:WI}).filter(([a])=>s.has(a)).map(async([,a])=>{let l=[],c=await a({timeoutSeconds:n,env:r,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:u=>l.push(u)}:{}});return t.includeRaw?{...c,raw_responses:l}:c});try{return{status:"ok",readings:(await Promise.all(o)).filter(Boolean)}}catch(a){return{status:"error",error:String(a),readings:[]}}}var XI,ZW,JI=L(()=>{"use strict";aI();bI();NI();qI();XI=["all","codex","agy","claude","kimi"],ZW=15});async function eq(t,e={}){try{let n=me(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=>!rr("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 GI({providers:o.length?[...o]:["all"],timeoutSeconds:i,env:{...t.env},progress:l=>t.onProgress(l+`
|
|
2352
|
+
`,"stderr")});return a.status==="ok"?de({readings:a.readings}):H("provider",a.error,{readings:[]})}catch(n){return H("provider",G(n),{readings:[]})}}var VI=L(()=>{"use strict";JI();Qt();tt()});import{basename as tq}from"node:path";function YI(t,e){let n=new Date(e.now.getTime()-qr()).toISOString(),r=ex(t,n).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=iq(e.sender,r),i=oq(e.sender,r);i!==null&&i.teamfile===e.root&&!zI(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=>zI(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<nq,d=dh(e.sender,r).length;return{stop:l.length>=1&&u&&d>=rq,chain:aq(a)}}function QI(t,e){let n=new Date(e.now.getTime()-qr()).toISOString(),r=ex(t,n),s=dh(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 qr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return KI;let n=Number(e);return!Number.isFinite(n)||n<=0?KI:n}function ZI(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function sq(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 ex(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(sq).filter(n=>Number.isFinite(n.at)&&new Date(n.at).toISOString()>=e).sort((n,r)=>n.at-r.at)}function iq(t,e,n={}){let r=new Map;for(let a of e)r.set(xs(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([xs(t)]);for(let a=0;a<64;a+=1){let l=r.get(xs(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=xs(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function dh(t,e){let n=xs(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=xs(l.sender),u=xs(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 oq(t,e){let n=dh(t,e);if(n.length===0)return null;let r=n[0];return r.sender.teamfile.startsWith("prompt:")?r.receiver:r.sender}function zI(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function xs(t){return`${t.teamfile}\0${t.alias}`}function aq(t){return t.map(e=>`${tq(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var nq,rq,KI,Cu=L(()=>{"use strict";nq=6e4,rq=2,KI=8*60*60*1e3});function mh(t,e){if(Jl(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 Nu(t,e,n){let r=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
2353
2353
|
FROM tracked_invocation
|
|
2354
2354
|
WHERE target_teamfile = ?
|
|
2355
2355
|
AND target_alias = ?
|
|
2356
|
-
AND status = 'running'`,e,n),s=0;for(let i of r)mh(t,i)!==null&&(s+=1);return s}var Ou=L(()=>{"use strict";qn();nn();
|
|
2356
|
+
AND status = 'running'`,e,n),s=0;for(let i of r)mh(t,i)!==null&&(s+=1);return s}var Ou=L(()=>{"use strict";qn();nn();yn()});function lq(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return tx;let n=Number(e);return!Number.isFinite(n)||n<=0?tx:n}async function cq(t,e,n){try{let r=Ft(e,n,t),s=r.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof r.provider=="string"&&r.provider.trim()!=="")i=r.provider;else{let c=await cR(s);if(c.length!==1)return null;i=c[0]}let o=await da(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function nx(t,e,n,r,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??lq(),o=await cq(t,n,r),a=o!==null&&o>=i;return a&&X({event:"session_idle_reclaim",receiver_teamfile:n,receiver_alias:r,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var tx,rx=L(()=>{"use strict";Se();yu();qn();tx=36e5});function uq(t){return t===null?null:ct(t)?"live":"dead"}function ph(t){let e=t.nowMs??Date.now(),n=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:uq(t.holderPid),since:t.since,idle_ms:Number.isFinite(n)?Math.max(0,e-n):null}}function dq(t){return(0,sx.formatDuration)(t)}function fh(t){let e=[];return t.idle_ms!==null&&e.push(`active ${dq(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}var sx,ix=L(()=>{"use strict";Tr();sx=py(Ep(),1)});import{randomUUID as mq}from"node:crypto";import{hostname as ox,networkInterfaces as pq}from"node:os";function ax(t){let e=(t.now??new Date).toISOString();return{lock_id:mq(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??ox(),holder_ips:t.ips??_q(),started_at:e,last_heartbeat:e}}function lx(t=process.env){return cx(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,fq)}function hq(t=process.env){return cx(t.LMCTL_TERMINAL_LOCK_STALE_MS,gq)}function gh(t,e={}){let n=e.now??new Date,r=e.localHost??ox(),s=e.staleMs??hq();if(t.holder_host===r)return(e.isProcessAlive??yq)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?n.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function As(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function cx(t,e){if(t===void 0||t.trim()==="")return e;let n=t.trim(),r=Number.parseInt(n,10);return!Number.isFinite(r)||r<=0||String(r)!==n?e:r}function yq(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function _q(){let t=new Set;for(let e of Object.values(pq()))for(let n of e??[])n.internal||t.add(n.address);return[...t].sort()}var fq,gq,ya=L(()=>{"use strict";fq=15e3,gq=12e4});function Lu(t,e=process.env,n){let r=n?.db?.name??ai(void 0,e),s=e.LMCTL_DB===r?e:{...e,LMCTL_DB:void 0};return`lmctl ${t}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
2357
2357
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
2358
2358
|
Consulted ${$w(r,s)}
|
|
2359
|
-
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Mu(t,e){let n=vq(t,e);return n.ok?{ok:!0,identity:n.identity,source:"session"}:n}function vq(t,e){let n=t[Wp];if(n===void 0||n.length===0)return{ok:!1,reason:"unset"};let r=[];for(let i of e.listRootTeams()){let o;try{o=mi(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===n&&r.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(r)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}var hh=L(()=>{"use strict";on();ec();_s()});function Pu(t){let e=vp(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var yh=L(()=>{"use strict";qn()});function _h(t,e,n){let r=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=
|
|
2360
|
-
`)}function Tq(t){return`${t.teamfile}:${t.alias}`}var
|
|
2359
|
+
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Mu(t,e){let n=vq(t,e);return n.ok?{ok:!0,identity:n.identity,source:"session"}:n}function vq(t,e){let n=t[Wp];if(n===void 0||n.length===0)return{ok:!1,reason:"unset"};let r=[];for(let i of e.listRootTeams()){let o;try{o=mi(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===n&&r.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(r)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}var hh=L(()=>{"use strict";on();ec();_s()});function Pu(t){let e=vp(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var yh=L(()=>{"use strict";qn()});function _h(t,e,n){let r=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=nt({path:rn(t)})),s),o=()=>{if(s===null)return;let a=s;s=null;try{a.close()}catch{}};return{hasOutstandingWork:()=>i().listAgentInflight().some(a=>a.sender_teamfile===e.teamfile&&a.sender_alias===e.alias&&!(a.receiver_teamfile===e.teamfile&&a.receiver_alias===e.alias)&&a.holder_pid!==null&&ct(a.holder_pid)),pollMs:bq,settleMs:wq,maxHoldMs:Rr(n),onHold:()=>X({event:"delivery_hold_open_started",receiver:r}),onRelease:a=>{o(),!(!a.held&&a.reason==="cleared")&&X({event:"delivery_hold_open_released",receiver:r,elapsed_ms:a.elapsedMs,held:a.held,reason:a.reason})}}}async function ux(t){let e=t.literalPrompt?t.newMessage:Eq(t.newMessage,{newMessageFrom:t.newMessageFrom??Tq(t.sender)});if(e.length===0)throw new Error(`no message to deliver for ${t.sender.teamfile}:${t.sender.alias} -> ${t.receiver.teamfile}:${t.receiver.alias}`);let n=!1,r=Ce(),s=0,i=0,o=0,a={provider:t.receiver.provider,sessionId:t.receiver.sessionId,cwd:t.receiver.cwd,prompt:e,permissionMode:t.permissionMode,env:t.env,onDelta:c=>{n=!0,r&&(s+=1,o=Buffer.byteLength(c,"utf8"),i+=o),t.onDelta?.(c)},onProgress:c=>t.onProgress?.(c)};t.registry&&(a.registry=t.registry),t.signal&&(a.signal=t.signal),t.receiver.model!==void 0&&(a.model=t.receiver.model),t.receiver.effort!==void 0&&(a.effort=t.receiver.effort),a.alias=t.receiver.alias,a.isLead=t.receiver.isLead,t.idleTimeoutMs!==void 0&&(a.timeoutMs=t.idleTimeoutMs),t.requireResume!==void 0&&(a.requireResume=t.requireResume),t.bundleSession!==void 0&&(a.bundleSession=t.bundleSession),a.holdOpen=_h(t.io,t.receiver,t.env),await t.onPromptBuilt?.(e);let l=await ca(a);if(t.requireResume&&l.sessionId!==t.receiver.sessionId)throw Object.assign(new Error(`provider session changed: expected ${t.receiver.sessionId}, received ${l.sessionId??"(missing)"}`),{usage:l.usage,sessionId:l.sessionId});return r&&$t(JSON.stringify({event:"chat_return",alias:t.receiver.alias,provider:t.receiver.provider,streamed:n,blockCount:s,streamedBytes:i,resultTextBytes:Buffer.byteLength(l.text,"utf8"),lastChunkBytes:o,tailPreview:l.text.slice(-200)})),l.status==="stalled"?{status:"stalled",receipt:l.text,sessionId:l.sessionId,...l.usage?{usage:l.usage}:{},prompt:e,wroteDelta:n,durationMs:l.durationMs,stalledAfterMs:l.stalledAfterMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:l.status==="empty"?{status:"empty",receipt:l.text,sessionId:l.sessionId,...l.usage?{usage:l.usage}:{},prompt:e,wroteDelta:n,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:{status:"ok",receipt:l.text,sessionId:l.sessionId,...l.usage?{usage:l.usage}:{},prompt:e,wroteDelta:n,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}}function Eq(t,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,t].join(`
|
|
2360
|
+
`)}function Tq(t){return`${t.teamfile}:${t.alias}`}var Gee,bq,wq,vh=L(()=>{"use strict";er();Se();Nr();nn();Tr();yn();Gee=60*60*1e3,bq=2e3,wq=5e3});async function Pi(t){let e=t.onEvent??(()=>{}),n=Sq(t.io,e),r=null,s=null,i=null,o,a,l=null,c=!1,u=null,d=t.prompt,m,p=()=>{let f=t.signal?.reason;if(i===null||!["SIGINT","SIGTERM","SIGHUP"].includes(f))return;let g;try{g=n.dal??nt({path:rn(n)}),g.finishTrackedInvocation(i,{status:"cancelled",signal:f,exit_code:f==="SIGINT"?130:f==="SIGTERM"?143:129,error:`prompt holder received ${f}`,team_chat_log_id:l}),s!==null&&g.releaseAgentInflight(s.row,s.leaseId)}catch(h){n.stderr.write(`error: failed to record holder ${f}: ${String(h)}
|
|
2361
2361
|
`)}finally{n.dal===void 0&&g?.close()}};t.signal?.addEventListener("abort",p,{once:!0});try{let f=t.resolvedNativeTarget,g=f!==void 0;if(g&&(t.heldLease===void 0||t.conversation===void 0))throw new Me("native session turns require a caller-held lease and conversation");let h=g?f:await he(n,A=>Ft(t.teamfile,t.alias,A));if(t.expectedSession!==void 0&&(h.provider!==t.expectedSession.provider||h.sessionid!==t.expectedSession.sessionid))throw new Me(`session changed for ${h.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${h.provider}:${h.sessionid}`);if(g&&(t.conversation.provider!==h.provider||t.conversation.sessionId!==h.sessionid))throw new Me("native session changed for "+h.alias+"; expected "+h.provider+":"+h.sessionid+", found "+t.conversation.provider+":"+t.conversation.sessionId);let y=h.teamfile,b=await he(n,A=>Pq(A,t.env??process.env)),_=b.sender,v=g?"native:"+h.provider+":"+h.sessionid:await Dq(n,{explicitRoot:t.rootFlag,sender:_,receiverTeamfile:y,operatorOrigin:b.origin==="operator"}),E=t.env??process.env;if(!g){let A=await he(n,M=>M.getRootTeam(v)?.name??null);A!==null&&(E.LMBEE_TEAM_NAME=A)}if(i=await xq(n,{receiverTeamfile:y,receiverAlias:h.alias,sender:_,rootTeamfile:v,provider:h.provider,model:h.model,sessionId:h.sessionid,cwd:h.sessiondir,prompt:t.prompt,origin:b.origin,parentInvocationId:mc(E.LMCTL_INVOCATION_ID)}),o=Oq(n,i),t.signal?.aborted)throw p(),Error("Chat turn cancelled");i!==null&&(E.LMCTL_INVOCATION_ID=String(i));try{g||Ci(n,Dt(y),y)}catch{}r={root_teamfile:v,sender_teamfile:_?.teamfile??null,sender_alias:_?.alias??null,receiver_teamfile:y,receiver_alias:h.alias,receiver_provider:h.provider,receiver_session_id:h.sessionid,origin:b.origin,message_type:t.messageType??null};let I=await yx(n,y,h.alias);if(I!==null){let A=As(I);return Cs(i,r,t.prompt,A,"unavailable"),u=bh(A,null),{status:"busy",message:A,teamChatLogId:null}}let T=!1;if(t.heldLease!==void 0){let A=t.heldLease;if(!await he(n,P=>{let U=P.getAgentInflight(y,h.alias);return U===null||U.sender_teamfile!==A.row.sender_teamfile||U.sender_alias!==A.row.sender_alias||U.started_at!==A.row.started_at||U.holder_pid!==process.pid?!1:P.heartbeatAgentInflight(A.row,A.leaseId,new Date().toISOString())})){let P=`bundle lease lost for ${h.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return Cs(i,r,t.prompt,P,"unavailable"),u=_a(P,null),{status:"error",errorKind:"provider",message:P,teamChatLogId:null,messageId:null}}}else{let A=await kq(n,y,h.alias);if(A.busy){let M=await Rq(n,y,h.alias);return M+=await Iq(n,y,h.alias),Cs(i,r,t.prompt,M,"unavailable"),u=bh(M,null),{status:"busy",message:M,teamChatLogId:null}}T=A.idleReclaim}if(_!==null&&_.teamfile!==y){let A=await he(n,M=>YI(M,{root:v,sender:_,receiverTeamfile:y,receiverAlias:h.alias,now:new Date}));if(A.stop){let M=ZI(A.chain);return Cs(i,r,t.prompt,M,"cycle"),u=_a(M,null),{status:"error",errorKind:"cycle",message:M,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let A=await Fq(n,{receiver_teamfile:y,receiver_alias:h.alias,sender_teamfile:_?.teamfile??y,sender_alias:_?.alias??"operator",...T?{force:!0,reclaimReason:"session-idle"}:{}});if(!A.acquired){let M=_x(y,h.alias,A.current);return M+=` ${fh(ph({holderPid:A.current.holder_pid,since:A.current.started_at}))}`,Cs(i,r,t.prompt,M,"unavailable"),u=bh(M,null),{status:"busy",message:M,teamChatLogId:null}}s={row:A.lease,leaseId:A.leaseId},t.onInflightAcquired?.(s),a=si(M=>he(n,P=>P.heartbeatAgentInflight(s.row,s.leaseId,M)),{intervalMs:gx,onError:M=>{Ce()&&$t(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:M instanceof Error?M.message:String(M)}))}})}if(t.signal?.aborted)throw Error("Chat turn cancelled");m=Hl({provider:h.provider,modelRequested:h.model??null,cwd:h.sessiondir,sessionId:h.sessionid}),r&&(r.started_at=m.startedAt);let k=await ux({sender:_??{teamfile:y,alias:"operator"},receiver:{teamfile:y,alias:h.alias,provider:h.provider,sessionId:h.sessionid,cwd:h.sessiondir,...h.model!==void 0?{model:h.model}:{},...h.effort!==void 0?{effort:h.effort}:{},...h.isLead!==void 0?{isLead:h.isLead}:{}},signal:t.signal,newMessage:t.prompt,newMessageFrom:_===null?"operator":`${_.teamfile}:${_.alias}`,...g?{literalPrompt:!0}:{},io:n,permissionMode:t.permissionMode,...t.expectedSession!==void 0?{requireResume:!0}:{},...t.bundleSession!==void 0?{bundleSession:t.bundleSession}:{},...t.conversation!==void 0?{bundleSession:t.conversation}:{},...t.registry!==void 0?{registry:t.registry}:{},env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:A=>e({kind:"delta",chunk:A}),onProgress:A=>e({kind:"progress",alias:h.alias,event:A}),onPromptBuilt:async A=>{d=A,l===null&&(l=await jq(n,{...r,message:A,usage:m}),l!==null&&(t.onAccepted?.(Bn(l)),i!==null&&await Nq(n,i,l))),i!==null&&await Cq(n,i,A)}});d=k.prompt;let N=k.status==="stalled",C=k.status==="empty",O=null,w=N?`provider stalled${k.stalledAfterMs!==void 0?` after ${k.stalledAfterMs}ms`:""}`:C?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":k.status==="error"?k.error??k.receipt:null,S=N||C||k.status==="error"?"error":"ok",R=await To(m,{status:k.status,sessionId:k.sessionId,usage:k.usage},()=>Rp(n),{db:n.dal?.db,dbPath:rn(n),env:n.env});l!==null?(await px(n,l,{...r,message:d,response:k.receipt,status:S,error_detail:w,usage:R}),c=!0,O=l):O=await fx(n,{...r,message:d,response:k.receipt,status:S,error_detail:w,usage:R});let x=k.status!=="error"?k.warnings:void 0;if(N||C){let A=w;Cs(i,r,d,A,"error"),u=_a(A,O,k.receipt,x)}else u=Lq(k.receipt,O,x);return{status:N?"stalled":C?"empty":"ok",replyText:k.receipt,wroteDelta:k.wroteDelta,teamChatLogId:O,messageId:O===null?null:Bn(O),durationMs:k.durationMs}}catch(f){let g=f instanceof Error?f.message:String(f),h=f,y=m?await To(m,{status:ni(g,!!t.signal?.aborted),usage:h?.usage,sessionId:h?.sessionId},()=>Rp(n),{db:n.dal?.db,dbPath:rn(n),env:n.env}):void 0;return l!==null&&!c&&r!==null&&(await px(n,l,{...r,message:d,response:null,status:"error",error_detail:g,usage:y}),c=!0),l===null&&r!==null&&y&&(l=await fx(n,{...r,message:d,response:null,status:"error",error_detail:g,usage:y})),Cs(i,r,d,g,"error"),u={..._a(g,l),signal:f?.signal??null,exit_code:f?.exitCode??null},{status:"error",errorKind:f instanceof Me?"target":"provider",message:g,teamChatLogId:l,messageId:l===null?null:Bn(l)}}finally{t.signal?.removeEventListener("abort",p),o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await Uq(n,r,Bn(l)),s!==null&&await $q(n,s.row,s.leaseId)&&t.onInflightReleased?.(s.leaseId),i!==null&&await Aq(n,i,u??_a("chat turn exited without a terminal outcome",null))}}function Sq(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:n=>{e({kind:"warning",message:n})}}}}async function kq(t,e,n){let r=await he(t,i=>(Nu(i,e,n),kr(i,e,n)));if(!r.busy)return{busy:!1,idleReclaim:!1};let s=await he(t,i=>nx(i,r,e,n));return{busy:!s,idleReclaim:s}}async function Rq(t,e,n){let r=await yx(t,e,n);if(r!==null)return As(r);let s=await he(t,i=>i.getAgentInflight(e,n));return s!==null?_x(e,n,s):`${n} is busy; wait and retry`}async function Iq(t,e,n){let r=await he(t,s=>s.getAgentInflight(e,n));return r===null?"":` ${fh(ph({holderPid:r.holder_pid,since:r.started_at}))}`}async function xq(t,e){try{return(await he(t,r=>r.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:Mq(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(n){return Ce()&&$t(JSON.stringify({event:"tracked_invocation_start_error",error:n instanceof Error?n.message:String(n)})),null}}async function Aq(t,e,n){try{await he(t,r=>{r.finishTrackedInvocation(e,n)})}catch(r){Ce()&&$t(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:r instanceof Error?r.message:String(r)}))}}async function Cq(t,e,n){try{await he(t,r=>{r.updateTrackedInvocationRequestPayload(e,n)})}catch(r){Ce()&&$t(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:r instanceof Error?r.message:String(r)}))}}async function Nq(t,e,n){try{await he(t,r=>{r.linkTrackedInvocationMessage(e,n)})}catch(r){Ce()&&$t(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:n,error:r instanceof Error?r.message:String(r)}))}}function Oq(t,e){if(e===null)return;let n=setInterval(()=>{he(t,r=>r.heartbeatTrackedInvocation(e)).catch(r=>{Ce()&&$t(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:r instanceof Error?r.message:String(r)}))})},gx);return n.unref?.(),n}function hx(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function Lq(t,e,n){return{status:"done",result_summary:Du(t),error:null,team_chat_log_id:e,...hx(n)}}function bh(t,e){return{status:"busy",result_summary:Du(t),error:t,team_chat_log_id:e}}function _a(t,e,n,r){return{status:"error",result_summary:n===void 0?JE(t,500):Du(n),error:t,team_chat_log_id:e,...hx(r)}}function Du(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function Mq(t,e,n){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(n)}`}function Pq(t,e){let n=Mu(e,t);if(n.ok)return{sender:Pu(n.identity),origin:"agent"};if(n.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Lu("chat",e,t))}async function Dq(t,e){if(e.explicitRoot!==void 0)return await he(t,r=>Tt(e.explicitRoot,r));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let n=e.sender;return await he(t,r=>QI(r,{sender:n,now:new Date})??e.receiverTeamfile)}async function Fq(t,e){return await he(t,n=>{let r=Ce(),s=Sr(n,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:qr(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(r&&$t(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:mx(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(r&&$t(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:mx(s.current)})),{acquired:!1,current:s.current})})}async function yx(t,e,n){return await he(t,r=>{for(let i=0;i<2;i+=1){let o=r.getTerminalLock(e,n);if(o===null)return null;if(gh(o).live)return o;let l=r.getAgentInflight(e,n);if(r.clearTerminalLock(e,n,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&r.clearObservedTerminalAgentInflight(e,n,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=r.getTerminalLock(e,n);return s===null?null:gh(s).live?s:null})}function mx(t){return t===null?null:{sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,holder_pid:t.holder_pid,started_at:t.started_at}}async function $q(t,e,n){try{return await he(t,r=>r.releaseAgentInflight(e,n))}catch(r){t.stderr.write(`warning: failed to release chat in-flight slot: ${r instanceof Error?r.message:String(r)}
|
|
2362
2362
|
`)}return!1}function _x(t,e,n){return`${e} is servicing ${n.sender_alias} (${n.sender_teamfile}) since ${n.started_at} \u2014 wait and retry, or inspect without waking it: lmctl tail "${t}" ${e}`}async function jq(t,e){let n=va(e.message);try{return await he(t,r=>r.beginTeamChatLog({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:null,origin:e.origin,status:"running",error_detail:null,truncated:n.truncated?1:0,message_type:e.message_type??null,created_at:e.started_at??new Date().toISOString()}))}catch(r){return t.stderr.write(`warning: failed to begin chat log: ${r instanceof Error?r.message:String(r)}
|
|
2363
2363
|
`),null}}async function px(t,e,n){let r=va(n.message),s=n.response===null?null:va(n.response);try{await he(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)}
|
|
2364
2364
|
`)}}async function Uq(t,e,n){if(e!==null)try{await he(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)}
|
|
2365
2365
|
`)}}async function fx(t,e){let n=va(e.message),r=e.response===null?null:va(e.response);try{return await he(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)}
|
|
2366
|
-
`),null}}function Cs(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:Du(n)})}function va(t){return t.length<=dx?{text:t,truncated:!1}:{text:t.slice(0,dx),truncated:!0}}var dx,gx,Fu=L(()=>{"use strict";So();Ip();sn();nn();qn();
|
|
2366
|
+
`),null}}function Cs(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:Du(n)})}function va(t){return t.length<=dx?{text:t,truncated:!1}:{text:t.slice(0,dx),truncated:!0}}var dx,gx,Fu=L(()=>{"use strict";So();Ip();sn();nn();qn();bn();wu();_s();Cu();Se();Nr();yn();Ou();rx();ix();ya();hh();yh();vh();zl();dx=256*1024,gx=3e4});function ju(t,e){let n=!1,r=()=>{if(n)return;n=!0;let s=$u.get(t);s||(s={pending:0,timeout:t.db.pragma("busy_timeout",{simple:!0})},$u.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=$u.get(t);if(--s.pending===0){$u.delete(t);try{t.db.pragma("busy_timeout="+s.timeout)}catch{}}}}var $u,wh=L(()=>{"use strict";$u=new WeakMap});import{resolve as Hq}from"node:path";async function vx(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(G(p)),c}finally{i.db.pragma("busy_timeout="+m)}};try{let d=me(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=at.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 g=st(t);Object.defineProperty(g,"dal",{enumerable:!0,get(){return i||(i=s??nt({path:t.dbPath}),o=ju(i,t.signal)),i}}),a=_n(t,{async close(){u()},finalizeSync(){u()}});let h=await Pi({signal:t.signal,onInflightAcquired:y=>{l=y,t.closed&&u()},onInflightReleased:y=>{l?.leaseId===y&&(l=void 0)},teamfile:Hq(t.cwd,m.teamfile),alias:m.alias,prompt:m.prompt,permissionMode:f,idleTimeoutMs:m.idleTimeoutMs,messageType:m.messageType,env:g.env,io:g});return u(),{status:h.status,reply:"replyText"in h?h.replyText:"",error:"message"in h?h.message:null,messageId:"messageId"in h?h.messageId:null,teamChatLogId:h.teamChatLogId}}catch(d){return n(G(d),r)}finally{try{u()}catch{}o(),c||(a(),s||i?.close())}}var bx=L(()=>{"use strict";Fu();Qt();zt();nn();wh();pn();tt()});import{performance as wx}from"node:perf_hooks";import{randomUUID as Bq}from"node:crypto";import{resolve as Wq,join as qq}from"node:path";function Eh(t){let e=Ex.get(t);if(e)return e;let n,r,s=new Promise((i,o)=>{n=i,r=o});Ex.set(t,s);try{Promise.resolve(t.close()).then(n,r)}catch(i){r(i)}return s}function Uu(t){let e=new Date(t.clock());return[e.getHours(),e.getMinutes(),e.getSeconds()].map(n=>String(n).padStart(2,"0")).join(":")}function Sx(t,e){let n=st(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 Xq(t,e){let n=e.provider.trim().toLowerCase(),r=Es(t.env.HOME?qq(t.env.HOME,".lmctl/config.toml"):void 0);return Ic(n,r,hu())}function Gq(t,e){let n=Mu(t,e);if(n.ok)return Pu(n.identity);if(n.reason==="unset")return null;throw Error(Lu("batch",t,e))}function kx(t,e,n=!1){let r=Et(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 Hu(t,e,n=!1){t.rootId===null||t.rootFinished||(kx(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 Th(t,e=!1){t.timer?.stop(),t.timer=void 0;for(let n of["lease","turnLease"]){let r=t[n];r&&(kx(t,s=>{if(!s.releaseAgentInflight(r.row,r.leaseId))throw Error("Batch lease release refused: ownership changed")},e),t[n]=void 0)}}async function ba(t,e,n){if(t.closing)return t.closing;let r,s;t.closing=new Promise((a,l)=>{r=a,s=l});let i=wx.now();t.closed=!0,t.controller.abort();let o=async a=>{let l,c=5e3-(wx.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(Eh(t.bundle))}catch(l){a.push(G(l))}finally{t.bundle=void 0}if(t.turnDone)try{await o(t.turnDone)}catch(l){a.push(G(l))}if(!t.terminal){try{Th(t,!0)}catch(c){a.push(G(c))}let l=(t.failed||a.length)&&e==="done"?"error":e;try{Hu(t,{...t.rootFinish,status:l,exit_code:l==="done"?0:1,error:l==="done"?void 0:n??t.failed??(a.length?a.join(`
|
|
2367
2367
|
`):t.rootFinish.error),result_summary:t.completed+"/"+t.request.promptCount+" prompts completed"},!0)}catch(c){a.push(G(c))}}if(t.criticalFailure&&a.push(t.criticalFailure),a.length)throw Error(a.join(`
|
|
2368
2368
|
`));t.untrack()})().then(r,s),t.closing}function Rx(t,e,n=!0){t.closed=!0,t.terminal=!0;let r=[];try{Th(t,!0)}catch(s){r.push(G(s))}try{Hu(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(G(s))}if(t.controller.abort(e),t.bundle&&Eh(t.bundle).catch(()=>{}),t.bundle=void 0,r.length)throw t.criticalFailure=r.join(`
|
|
2369
|
-
`),Error(t.criticalFailure);t.untrack()}function Ix(t,e){try{let n=Bu(t,e);return n?(Rx(n,"SIGTERM",!1),de({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(n){return H("provider",G(n))}}function Bu(t,e){if(!e||typeof e!="object")return;let n=Tx.get(e);return n?.ctx===t?n:void 0}function xx(t,e){let n=Bu(t,e);return!n||!n.member?H("invalid_argument","Invalid or unmanaged batch handle"):de({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 Ax(t,e){let n;try{let r=me(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=Ft(Wq(t.cwd,s.teamfile),s.alias,t.dal)}catch(m){let p;try{p=m instanceof Me?m.kind:void 0}catch{}return H(p??nr(m),G(m))}let o=Object.freeze({id:`batch-${t.clock()}-${Bq().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;Tx.set(o,a),a.untrack=
|
|
2369
|
+
`),Error(t.criticalFailure);t.untrack()}function Ix(t,e){try{let n=Bu(t,e);return n?(Rx(n,"SIGTERM",!1),de({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(n){return H("provider",G(n))}}function Bu(t,e){if(!e||typeof e!="object")return;let n=Tx.get(e);return n?.ctx===t?n:void 0}function xx(t,e){let n=Bu(t,e);return!n||!n.member?H("invalid_argument","Invalid or unmanaged batch handle"):de({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 Ax(t,e){let n;try{let r=me(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=Ft(Wq(t.cwd,s.teamfile),s.alias,t.dal)}catch(m){let p;try{p=m instanceof Me?m.kind:void 0}catch{}return H(p??nr(m),G(m))}let o=Object.freeze({id:`batch-${t.clock()}-${Bq().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;Tx.set(o,a),a.untrack=_n(t,{close:()=>ba(a,"error","script execution interrupted or terminated without orderly close"),finalizeSync:m=>Rx(a,m)}),a.member=i;let l=Et(t),c=st(t),u=a.member,d=!s.legacy&&s.promptCount>1&&await Xq(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: ${G(m)}
|
|
2370
2370
|
`)}if(a.rootId!==null&&(a.env.LMCTL_INVOCATION_ID=String(a.rootId)),c.stderr.write(`batch ${Uu(t)}: starting ${s.promptCount} prompt${s.promptCount===1?"":"s"} -> ${u.alias} (teamfile=${s.teamfile} input=${s.label})
|
|
2371
2371
|
`),d){Nu(l,u.teamfile,u.alias);let m=kr(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"?As(m.terminalLock):`${u.alias} is busy (interactive terminal); wait and retry`;return Hu(a,{status:"busy",exit_code:1,error:b,result_summary:"0 prompts completed"}),await ba(a,"error"),{status:"busy",error:`cannot start bundle: ${b}`}}let p=Gq(a.env,l),f=Sr(l,{receiver_teamfile:u.teamfile,receiver_alias:u.alias,sender_teamfile:p?.teamfile??u.teamfile,sender_alias:p?.alias??"operator",ttlMs:qr(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 Hu(a,{status:"busy",exit_code:1,error:b,result_summary:"0 prompts completed"}),await ba(a,"error"),{status:"busy",error:`cannot start bundle: ${b}`}}a.lease={row:f.lease,leaseId:f.leaseId};let g=a.lease,h=si(b=>l.heartbeatAgentInflight(g.row,g.leaseId,b),{intervalMs:Gl(a.env)});a.timer={stop:()=>clearInterval(h)};let y=Sx(t,b=>`batch ${Uu(t)}: opening provider session (${b}s elapsed)
|
|
2372
|
-
`);try{let b={...a.env},_=l.getRootTeam(u.teamfile)?.name;_&&(b.LMBEE_TEAM_NAME=_);let v=$g({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:_h(c,{teamfile:u.teamfile,alias:u.alias},b)});v.then(T=>{a.closed&&Eh(T).catch(()=>{})}).catch(()=>{});let E,I=new Promise((T,k)=>{E=()=>k(Error("Context is closed")),t.signal.addEventListener("abort",E,{once:!0}),t.signal.aborted&&E()});try{a.bundle=await Promise.race([v,I])}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:G(b)}),Th(a)}finally{y.stop()}}if(t.closed)throw Error("Context is closed");return a.bundleActive=a.bundle!==void 0,de({batch:o})}catch(r){if(n){n.rootFinish={...n.rootFinish,result_summary:"0 prompts completed"};try{await ba(n,"error",G(r))}catch{}}return H(t?.closed?"cancelled":"provider",G(r))}}async function Cx(t,e,n,r,s){let i=(m,p="invalid_argument")=>({status:"error",error:m,code:p,reply:"",messageId:null,teamChatLogId:null}),o=me(t);if(o)return i(o.error,o.code);let a=Bu(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??
|
|
2372
|
+
`);try{let b={...a.env},_=l.getRootTeam(u.teamfile)?.name;_&&(b.LMBEE_TEAM_NAME=_);let v=$g({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:_h(c,{teamfile:u.teamfile,alias:u.alias},b)});v.then(T=>{a.closed&&Eh(T).catch(()=>{})}).catch(()=>{});let E,I=new Promise((T,k)=>{E=()=>k(Error("Context is closed")),t.signal.addEventListener("abort",E,{once:!0}),t.signal.aborted&&E()});try{a.bundle=await Promise.race([v,I])}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:G(b)}),Th(a)}finally{y.stop()}}if(t.closed)throw Error("Context is closed");return a.bundleActive=a.bundle!==void 0,de({batch:o})}catch(r){if(n){n.rootFinish={...n.rootFinish,result_summary:"0 prompts completed"};try{await ba(n,"error",G(r))}catch{}}return H(t?.closed?"cancelled":"provider",G(r))}}async function Cx(t,e,n,r,s){let i=(m,p="invalid_argument")=>({status:"error",error:m,code:p,reply:"",messageId:null,teamChatLogId:null}),o=me(t);if(o)return i(o.error,o.code);let a=Bu(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??nt({path:t.dbPath});let m={...st(t),dal:c},p=AbortSignal.any([t.signal,a.controller.signal]);u=ju(c,p),m.stderr.write(`batch ${Uu(t)}: prompt ${r}/${s} -> ${a.member.alias}
|
|
2373
2373
|
`),d=Sx(t,h=>`batch ${Uu(t)}: prompt ${r}/${s} still running (${h}s elapsed)
|
|
2374
2374
|
`);let f=await Pi({signal:p,onInflightAcquired:h=>{a.turnLease=h},onInflightReleased:h=>{a.turnLease?.leaseId===h&&(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:h=>{d?.poke(),h.kind==="warning"&&m.stderr.write(h.message)}}),g="replyText"in f?f.replyText.replace(/\n+$/u,""):"";if(f.status!=="ok"){let h=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): ${h}; 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}
|
|
2375
2375
|
`),{status:f.status,error:y,reply:g,messageId:"messageId"in f?f.messageId:null,teamChatLogId:f.teamChatLogId}}return a.completed++,{status:"ok",error:null,reply:g,messageId:f.messageId,teamChatLogId:f.teamChatLogId}}catch(m){let p=`batch: stopped at prompt ${r}/${s} (${r-1} completed): ${G(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{st(t).stderr.write(`error: ${p}
|
|
2376
|
-
`)}catch{}return i(p,"provider")}finally{d?.stop(),a.inFlight=!1,a.turnFinished?.(),a.turnDone=void 0,u(),l||c?.close()}}async function Nx(t,e,n){try{let r=Bu(t,e);return r?!n||!["done","error","cancelled"].includes(n.status)?H("invalid_argument","Invalid batch close status"):(await ba(r,n.status,n.error),de({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(r){return H("provider",G(r))}}var Ex,Tx,Ox=L(()=>{"use strict";wh();nn();hn();Ou();er();Se();Yo();Fu();qn();vh();ya();Cu();hh();yh();zt();Qt();et();Ex=new WeakMap;Tx=new WeakMap});import{readdirSync as Jq}from"node:fs";import{join as Mx,resolve as Vq}from"node:path";import{randomUUID as Kq}from"node:crypto";import{performance as Lx}from"node:perf_hooks";function Rh(t,e){let n=e&&typeof e=="object"?Px.get(e):void 0;return n?.ctx===t?n:void 0}function Ih(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 Jq(a))/\.(?:lmctl|lmc)$/i.test(l)&&s.add(Mx(a,l))}catch(l){if(l.code!=="ENOENT")throw l}let i=new Map;for(let a of s){let l;try{l=mi(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=Ft(a,c.alias,e);u.provider===n.provider&&u.sessionid===n.sessionid&&i.set(JSON.stringify([Tt(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 Sh(t,e){return t.alias+" is servicing "+e.sender_alias+" ("+e.sender_teamfile+") since "+e.started_at+" \u2014 wait and retry"}function Dx(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 kh(t){return t.closing||(t.closed=!0,t.stopHeartbeat(),t.controller.abort(),t.closing=(async()=>{let e=Lx.now(),n;try{let r=(async()=>{await t.conversation?.close(),await t.active})();await Promise.race([r,new Promise((s,i)=>{n=setTimeout(()=>i(Error("Native session cleanup exceeded its 5 second deadline")),Math.max(1,5e3-(Lx.now()-e)))})])}finally{n&&clearTimeout(n),Dx(t,!0),t.untrack()}})()),t.closing}function Fx(t){t.closed=!0,t.stopHeartbeat(),t.controller.abort(),t.conversation&&t.conversation.close().catch(()=>{}),Dx(t,!0),t.untrack()}async function Wu(t,e,n={},r){let s;try{let i=me(t);if(i)return i;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Native session member must be a map");for(let k of["provider","sessionid"])if(typeof e[k]!="string"||!e[k].trim())return H("invalid_argument","Native session requires provider and sessionid");for(let k of["sessiondir","model","effort"])if(e[k]!==void 0&&(typeof e[k]!="string"||!e[k].trim()))return H("invalid_argument","Native session "+k+" must be a nonempty string");if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(k=>!["permissionMode","idleTimeoutMs"].includes(k)))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 o=Et(t),a=Vq(t.cwd,e.sessiondir??t.cwd),l;try{l=Ih(t,o,e,a)}catch(k){return H("invalid_argument",G(k))}let c=sr(t);if(!await c.getSession(e.sessionid,e.provider))return H("not_found","Native session was not found");if(t.closed)return H("cancelled","Context is closed");let d=l.member,m=kr(o,d.teamfile,d.alias);if(m.busy)return{status:"busy",error:m.reason==="in-flight"?Sh(d,m.inFlight):m.source==="terminal-lock"?As(m.terminalLock):d.alias+" is busy (interactive terminal); wait and retry"};let p={receiver_teamfile:d.teamfile,receiver_alias:d.alias,sender_teamfile:d.teamfile,sender_alias:"operator",started_at:new Date().toISOString()},f=o.getAgentInflight(d.teamfile,d.alias),g=f!==null&&(f.native_provider!==null&&f.native_provider!==void 0||f.native_session_id!==null&&f.native_session_id!==void 0);if(g&&!r)return{status:"busy",error:Sh(d,f)};let h=r&&g?o.tryAcquireNativeHolder(p,r):void 0,y=h?h.acquired?{acquired:!0,lease:h.current,leaseId:h.lease_id}:{acquired:!1,current:h.current}:Sr(o,{...p,ttlMs:Rr(t.env),...r?{nativeHolder:r}:{}});if(!y.acquired)return{status:"busy",error:Sh(d,y.current)};let b=Object.freeze({id:"native-session-"+Kq()});s={ctx:t,dal:o,ref:b,member:d,ownerKnown:l.known,options:{...n},lease:{row:y.lease,leaseId:y.leaseId},controller:new AbortController,closed:!1,released:!1,stopHeartbeat(){},untrack(){}};let _=s;_.untrack=yn(t,{close:()=>kh(_),finalizeSync:()=>Fx(_)});let v=si(k=>o.heartbeatAgentInflight(_.lease.row,_.lease.leaseId,k),{intervalMs:Gl(t.env)});_.stopHeartbeat=()=>clearInterval(v);let E=jg({provider:e.provider,sessionId:e.sessionid,cwd:d.sessiondir,env:{...t.env},model:d.model,effort:d.effort,permissionMode:n.permissionMode??"yolo",timeoutMs:n.idleTimeoutMs??0,execution:"auto",requireResume:!0,registry:c,userConfig:Es(t.env.HOME?Mx(t.env.HOME,".lmctl/config.toml"):void 0)});E.then(k=>{_.closed&&k.close().catch(()=>{})}).catch(()=>{});let I,T=new Promise((k,N)=>{I=()=>N(Error("Context is closed")),t.signal.addEventListener("abort",I,{once:!0}),t.signal.aborted&&I()});try{_.conversation=await Promise.race([E,T])}finally{t.signal.removeEventListener("abort",I)}if(t.closed||_.closed)throw Error("Context is closed");return Px.set(b,_),de({session:b})}catch(i){if(s)try{await kh(s)}catch(o){return H("provider",G(i)+"; "+G(o))}return H(t?.closed?"cancelled":"provider",G(i))}}async function qu(t,e,n,r=void 0){let s=(l,c="invalid_argument")=>({status:"error",reply:"",error:l,code:c,messageId:null,teamChatLogId:null}),i=me(t);if(i)return s(i.error,i.code);let o=Rh(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=Ft(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 Pi({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.options.idleTimeoutMs,heldLease:o.lease,conversation:o.conversation,registry:sr(t),onAccepted:r?.onAccepted,env:{...t.env,...r?.attribution},io:{...st(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 Xu(t,e){try{let n=Rh(t,e);return n?(await kh(n),de({})):H("invalid_argument","Invalid native session reference")}catch(n){return H("provider",G(n))}}function $x(t,e){try{let n=Rh(t,e);return n?(Fx(n),de({})):H("invalid_argument","Invalid native session reference")}catch(n){return H("provider",G(n))}}var Px,xh=L(()=>{"use strict";er();Yo();Tu();zt();Qt();qn();_s();hn();ya();et();Fu();Px=new WeakMap});import{spawn as zq}from"node:child_process";import{createConnection as Yq}from"node:net";import{closeSync as Ah,existsSync as Ch,lstatSync as Qq,mkdirSync as Zq,openSync as jx,readFileSync as Ux,rmSync as Gu,writeFileSync as e2}from"node:fs";import{createHash as Wx,randomUUID as t2}from"node:crypto";import{tmpdir as n2}from"node:os";import{join as Di,resolve as Lh}from"node:path";import{fileURLToPath as r2}from"node:url";import{performance as Hx}from"node:perf_hooks";function Xx(t){let e=t.env,n=Es(e.HOME?Di(e.HOME,".lmctl/config.toml"):void 0);return Wx("sha256").update(JSON.stringify({HOME:e.HOME,KIMI_CODE_HOME:e.KIMI_CODE_HOME,XDG_DATA_HOME:e.XDG_DATA_HOME,XDG_CONFIG_HOME:e.XDG_CONFIG_HOME,tools:n.tools})).digest("hex")}function s2(t){let e=Wx("sha256").update(t.dbPath).digest("hex").slice(0,16),n=Di(n2(),"lmctl-native-"+(process.getuid?.()??"user")+"-"+e);Zq(n,{recursive:!0,mode:448});let r=Qq(n);if(!r.isDirectory()||r.isSymbolicLink()||process.getuid&&r.uid!==process.getuid()||r.mode&63)throw Error("Native holder directory must be private and owned by this user");return n}function Gx(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw Error("Native session member must be a map");for(let r of["provider","sessionid"])if(typeof t[r]!="string"||!t[r].trim())throw Error("Native session requires provider and sessionid");for(let r of["sessiondir","model","effort"])if(t[r]!==void 0&&(typeof t[r]!="string"||!t[r].trim()))throw Error("Invalid native session "+r);if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!["permissionMode","idleTimeoutMs"].includes(r)))throw Error("Unknown native session option");if(e.permissionMode!==void 0&&!["plan","yolo"].includes(e.permissionMode))throw Error("permissionMode must be plan or yolo");if(e.idleTimeoutMs!==void 0&&(typeof e.idleTimeoutMs!="number"||!Number.isFinite(e.idleTimeoutMs)||e.idleTimeoutMs<0||e.idleTimeoutMs>2147483647))throw Error("idleTimeoutMs must be a bounded nonnegative number");if(n!==void 0&&(typeof n!="string"||Buffer.byteLength(n)>qx/2))throw Error("Native session prompt is invalid or exceeds the frame limit")}function Oh(t,e){return Et(t).db.prepare("SELECT * FROM agent_inflight WHERE native_provider=? AND native_session_id=?").get(e.provider,e.sessionid)??null}function Jx(t,e){return Et(t).findNativeHolder(e.native_provider,e.native_session_id)?.native_generation===e.native_generation&&!!e.native_boot_id&&lw(e.holder_pid)===e.native_boot_id+":"+e.native_start_time}function Vx(t,e,n,r){let s=JSON.parse(e.native_config_json??"null");return!!s&&s.profile===Xx(t)&&(n.sessiondir===void 0||Lh(t.cwd,n.sessiondir)===s.cwd)&&(n.model===void 0||n.model===s.model)&&(n.effort===void 0||n.effort===s.effort)&&(r.permissionMode===void 0||r.permissionMode===s.permissionMode)&&(r.idleTimeoutMs===void 0||r.idleTimeoutMs===s.idleTimeoutMs)}function i2(t){if(t?.workerPath)return t.workerPath;for(let e of[new URL("../native-holder/worker.js",import.meta.url),new URL("./native-holder-worker.js",import.meta.url),new URL("../../dist/native-holder/worker.js",import.meta.url)]){let n=r2(e);if(Ch(n))return n}throw Error("Native holder spawn failed: packaged worker is missing; rebuild or update lmctl")}async function o2(t,e,n,r){let s=i2(r);if(!Ch(s))return H("provider","Native holder spawn failed: worker entry is missing");let i=s2(t),o=t2(),a=Di(i,o+".json"),l=Di(i,o+".result"),c=Di(i,o+".log"),u,d,m=!1,p=!1,f,g=!1,h=!1;try{d=jx(a,"wx",384),m=!0,e2(d,JSON.stringify({cwd:t.cwd,dbPath:t.dbPath,env:t.env,member:e,options:n,resultFile:l})),Ah(d),d=void 0,u=jx(c,"wx",384),p=!0,f=zq(process.execPath,[s,a],{detached:!0,stdio:["ignore",u,u],env:{...t.env},cwd:t.cwd}),await new Promise((_,v)=>{f.once("spawn",()=>{g=!0,_()}),f.once("error",v)}),f.unref();let y=Hx.now()+Nh;for(;Hx.now()<y;){if(Ch(l)){let _=JSON.parse(Ux(l,"utf8"));return h=_.status==="ok",_}if(f.exitCode!==null||f.signalCode!==null)break;await Bx(10)}let b=Ux(c,"utf8").slice(-4096).trim();return H("provider","Native holder spawn failed: readiness deadline expired"+(b?"; "+b:""))}catch(y){return H("provider","Native holder spawn failed: "+G(y))}finally{d!==void 0&&Ah(d),u!==void 0&&Ah(u),m&&Gu(a,{force:!0}),Gu(l,{force:!0}),Gu(l+".tmp",{force:!0}),p&&Gu(c,{force:!0}),g&&!h&&f&&f.exitCode===null&&f.signalCode===null&&(f.kill("SIGTERM"),await Promise.race([new Promise(y=>f.once("close",()=>y())),Bx(1e3)]))}}async function Kx(t,e,n,r,s,i){let o={kind:s,provider:n.provider,sessionid:n.sessionid,generation:e.native_generation,member:{...n,...n.sessiondir!==void 0?{sessiondir:Lh(t.cwd,n.sessiondir)}:{}},options:r,prompt:i,profile:Xx(t),attribution:{LMCTL_SELF_SESSIONID:t.env.LMCTL_SELF_SESSIONID,LMCTL_INVOCATION_ID:t.env.LMCTL_INVOCATION_ID}};return new Promise(a=>{let l=Yq(e.native_endpoint),c=Buffer.alloc(0),u=!1,d=null,m=!1,p=h=>{u||(u=!0,clearTimeout(g),l.destroy(),a(h))},f=()=>Cn(m?"Native holder reply lost; outcome unknown"+(d?" (message "+d+")":""):"Native holder is unreachable; verify its process before recovery","closed",d),g=setTimeout(()=>p(f()),s==="close"?Nh+2e3:Nh);l.once("connect",()=>{m=!0,l.write(JSON.stringify(o)+`
|
|
2377
|
-
`)}),l.on("data",h=>{if(c=Buffer.concat([c,h]),c.length>qx)return p(Cn("Native holder response exceeds frame limit","closed",d));let y;for(;(y=c.indexOf(10))>=0;){let b=c.subarray(0,y);c=c.subarray(y+1);try{let _=JSON.parse(b.toString());if(_.kind==="accepted")typeof _.messageId=="string"&&(d=_.messageId,clearTimeout(g),g=setTimeout(()=>p(f()),24*60*60*1e3));else return _.kind==="result"?p(_.result):p(Cn("Invalid native holder response"))}catch{return p(Cn("Invalid native holder response"))}}}),l.once("error",()=>p(f())),l.once("close",()=>p(f()))})}async function a2(t,e){let n=sr(t),r=n.getAdapter(e.provider),s=Es(t.env.HOME?Di(t.env.HOME,".lmctl/config.toml"):void 0);if(!r)throw Error("Provider is not registered");if(e.provider==="kimi"&&r.openSession!==void 0&&s.tools[e.provider]?.agent===void 0)return!0;if(r.openSession!==void 0&&s.tools[e.provider]?.agent===void 0)throw Error("Persistent native holder is currently qualified for Kimi only");return!1}async function l2(t,e,n,r={},s){try{let i=me(t);if(i)return Cn(i.error,i.code);if(Gx(e,r,n),!await a2(t,e)){let a=await Wu(t,e,r);if(a.status!=="ok")return a.status==="busy"?{status:"busy",reply:"",error:a.error,messageId:null,teamChatLogId:null}:Cn(a.error,a.code);try{return await qu(t,a.session,n)}finally{await Xu(t,a.session)}}let o=Oh(t,e);if(!o){let a=Ih(t,Et(t),e,Lh(t.cwd,e.sessiondir??t.cwd));if(kr(Et(t),a.member.teamfile,a.member.alias).busy)return{status:"busy",reply:"",error:a.member.alias+" is busy; wait and retry",messageId:null,teamChatLogId:null};let c=await o2(t,e,r,s);if(c.status!=="ok")return c.status==="busy"?{status:"busy",reply:"",error:c.error,messageId:null,teamChatLogId:null}:Cn(c.error,c.code??"provider");o=Oh(t,e)}return!o||!Jx(t,o)?Cn("Native holder ownership is stale or unverified; verify provider shutdown before recovery"):Vx(t,o,e,r)?o.native_phase!=="ready"||!o.native_endpoint?{status:"busy",reply:"",error:e.sessionid+" is busy; wait and retry",messageId:null,teamChatLogId:null}:await Kx(t,o,e,r,"turn",n):Cn("Native holder configuration conflicts with this request","invalid_argument")}catch(i){return Cn(G(i),"invalid_argument")}}async function c2(t,e){try{let n=me(t);if(n)return n;Gx(e,{});let r=Oh(t,e);return r?Jx(t,r)?Vx(t,r,e,{})?r.native_phase!=="ready"||!r.native_endpoint?{status:"busy",error:e.sessionid+" is busy; wait and retry"}:await Kx(t,r,e,{},"close"):H("invalid_argument","Native holder configuration conflicts with this request"):H("closed","Native holder ownership is stale or unverified"):de({})}catch(n){return H("invalid_argument",G(n))}}function zx(t){if(t.status==="ok")return t;let e=t.status==="busy"?"busy":ns.includes(t.code)?t.code:"provider";return{...t,code:e}}async function Yx(t,e,n,r={},s){return zx(await l2(t,e,n,r,s))}async function Qx(t,e){return zx(await c2(t,e))}var qx,Nh,Cn,Bx,Zx=L(()=>{"use strict";
|
|
2376
|
+
`)}catch{}return i(p,"provider")}finally{d?.stop(),a.inFlight=!1,a.turnFinished?.(),a.turnDone=void 0,u(),l||c?.close()}}async function Nx(t,e,n){try{let r=Bu(t,e);return r?!n||!["done","error","cancelled"].includes(n.status)?H("invalid_argument","Invalid batch close status"):(await ba(r,n.status,n.error),de({})):H("invalid_argument","Invalid or unmanaged batch handle")}catch(r){return H("provider",G(r))}}var Ex,Tx,Ox=L(()=>{"use strict";wh();nn();yn();Ou();er();Se();Yo();Fu();qn();vh();ya();Cu();hh();yh();zt();Qt();tt();Ex=new WeakMap;Tx=new WeakMap});import{readdirSync as Jq}from"node:fs";import{join as Mx,resolve as Vq}from"node:path";import{randomUUID as Kq}from"node:crypto";import{performance as Lx}from"node:perf_hooks";function Rh(t,e){let n=e&&typeof e=="object"?Px.get(e):void 0;return n?.ctx===t?n:void 0}function Ih(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 Jq(a))/\.(?:lmctl|lmc)$/i.test(l)&&s.add(Mx(a,l))}catch(l){if(l.code!=="ENOENT")throw l}let i=new Map;for(let a of s){let l;try{l=mi(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=Ft(a,c.alias,e);u.provider===n.provider&&u.sessionid===n.sessionid&&i.set(JSON.stringify([Tt(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 Sh(t,e){return t.alias+" is servicing "+e.sender_alias+" ("+e.sender_teamfile+") since "+e.started_at+" \u2014 wait and retry"}function Dx(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 kh(t){return t.closing||(t.closed=!0,t.stopHeartbeat(),t.controller.abort(),t.closing=(async()=>{let e=Lx.now(),n;try{let r=(async()=>{await t.conversation?.close(),await t.active})();await Promise.race([r,new Promise((s,i)=>{n=setTimeout(()=>i(Error("Native session cleanup exceeded its 5 second deadline")),Math.max(1,5e3-(Lx.now()-e)))})])}finally{n&&clearTimeout(n),Dx(t,!0),t.untrack()}})()),t.closing}function Fx(t){t.closed=!0,t.stopHeartbeat(),t.controller.abort(),t.conversation&&t.conversation.close().catch(()=>{}),Dx(t,!0),t.untrack()}async function Wu(t,e,n={},r){let s;try{let i=me(t);if(i)return i;if(!e||typeof e!="object"||Array.isArray(e))return H("invalid_argument","Native session member must be a map");for(let k of["provider","sessionid"])if(typeof e[k]!="string"||!e[k].trim())return H("invalid_argument","Native session requires provider and sessionid");for(let k of["sessiondir","model","effort"])if(e[k]!==void 0&&(typeof e[k]!="string"||!e[k].trim()))return H("invalid_argument","Native session "+k+" must be a nonempty string");if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(k=>!["permissionMode","idleTimeoutMs"].includes(k)))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 o=Et(t),a=Vq(t.cwd,e.sessiondir??t.cwd),l;try{l=Ih(t,o,e,a)}catch(k){return H("invalid_argument",G(k))}let c=sr(t);if(!await c.getSession(e.sessionid,e.provider))return H("not_found","Native session was not found");if(t.closed)return H("cancelled","Context is closed");let d=l.member,m=kr(o,d.teamfile,d.alias);if(m.busy)return{status:"busy",error:m.reason==="in-flight"?Sh(d,m.inFlight):m.source==="terminal-lock"?As(m.terminalLock):d.alias+" is busy (interactive terminal); wait and retry"};let p={receiver_teamfile:d.teamfile,receiver_alias:d.alias,sender_teamfile:d.teamfile,sender_alias:"operator",started_at:new Date().toISOString()},f=o.getAgentInflight(d.teamfile,d.alias),g=f!==null&&(f.native_provider!==null&&f.native_provider!==void 0||f.native_session_id!==null&&f.native_session_id!==void 0);if(g&&!r)return{status:"busy",error:Sh(d,f)};let h=r&&g?o.tryAcquireNativeHolder(p,r):void 0,y=h?h.acquired?{acquired:!0,lease:h.current,leaseId:h.lease_id}:{acquired:!1,current:h.current}:Sr(o,{...p,ttlMs:Rr(t.env),...r?{nativeHolder:r}:{}});if(!y.acquired)return{status:"busy",error:Sh(d,y.current)};let b=Object.freeze({id:"native-session-"+Kq()});s={ctx:t,dal:o,ref:b,member:d,ownerKnown:l.known,options:{...n},lease:{row:y.lease,leaseId:y.leaseId},controller:new AbortController,closed:!1,released:!1,stopHeartbeat(){},untrack(){}};let _=s;_.untrack=_n(t,{close:()=>kh(_),finalizeSync:()=>Fx(_)});let v=si(k=>o.heartbeatAgentInflight(_.lease.row,_.lease.leaseId,k),{intervalMs:Gl(t.env)});_.stopHeartbeat=()=>clearInterval(v);let E=jg({provider:e.provider,sessionId:e.sessionid,cwd:d.sessiondir,env:{...t.env},model:d.model,effort:d.effort,permissionMode:n.permissionMode??"yolo",timeoutMs:n.idleTimeoutMs??0,execution:"auto",requireResume:!0,registry:c,userConfig:Es(t.env.HOME?Mx(t.env.HOME,".lmctl/config.toml"):void 0)});E.then(k=>{_.closed&&k.close().catch(()=>{})}).catch(()=>{});let I,T=new Promise((k,N)=>{I=()=>N(Error("Context is closed")),t.signal.addEventListener("abort",I,{once:!0}),t.signal.aborted&&I()});try{_.conversation=await Promise.race([E,T])}finally{t.signal.removeEventListener("abort",I)}if(t.closed||_.closed)throw Error("Context is closed");return Px.set(b,_),de({session:b})}catch(i){if(s)try{await kh(s)}catch(o){return H("provider",G(i)+"; "+G(o))}return H(t?.closed?"cancelled":"provider",G(i))}}async function qu(t,e,n,r=void 0){let s=(l,c="invalid_argument")=>({status:"error",reply:"",error:l,code:c,messageId:null,teamChatLogId:null}),i=me(t);if(i)return s(i.error,i.code);let o=Rh(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=Ft(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 Pi({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.options.idleTimeoutMs,heldLease:o.lease,conversation:o.conversation,registry:sr(t),onAccepted:r?.onAccepted,env:{...t.env,...r?.attribution},io:{...st(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 Xu(t,e){try{let n=Rh(t,e);return n?(await kh(n),de({})):H("invalid_argument","Invalid native session reference")}catch(n){return H("provider",G(n))}}function $x(t,e){try{let n=Rh(t,e);return n?(Fx(n),de({})):H("invalid_argument","Invalid native session reference")}catch(n){return H("provider",G(n))}}var Px,xh=L(()=>{"use strict";er();Yo();Tu();zt();Qt();qn();_s();yn();ya();tt();Fu();Px=new WeakMap});import{spawn as zq}from"node:child_process";import{createConnection as Yq}from"node:net";import{closeSync as Ah,existsSync as Ch,lstatSync as Qq,mkdirSync as Zq,openSync as jx,readFileSync as Ux,rmSync as Gu,writeFileSync as e2}from"node:fs";import{createHash as Wx,randomUUID as t2}from"node:crypto";import{tmpdir as n2}from"node:os";import{join as Di,resolve as Lh}from"node:path";import{fileURLToPath as r2}from"node:url";import{performance as Hx}from"node:perf_hooks";function Xx(t){let e=t.env,n=Es(e.HOME?Di(e.HOME,".lmctl/config.toml"):void 0);return Wx("sha256").update(JSON.stringify({HOME:e.HOME,KIMI_CODE_HOME:e.KIMI_CODE_HOME,XDG_DATA_HOME:e.XDG_DATA_HOME,XDG_CONFIG_HOME:e.XDG_CONFIG_HOME,tools:n.tools})).digest("hex")}function s2(t){let e=Wx("sha256").update(t.dbPath).digest("hex").slice(0,16),n=Di(n2(),"lmctl-native-"+(process.getuid?.()??"user")+"-"+e);Zq(n,{recursive:!0,mode:448});let r=Qq(n);if(!r.isDirectory()||r.isSymbolicLink()||process.getuid&&r.uid!==process.getuid()||r.mode&63)throw Error("Native holder directory must be private and owned by this user");return n}function Gx(t,e,n){if(!t||typeof t!="object"||Array.isArray(t))throw Error("Native session member must be a map");for(let r of["provider","sessionid"])if(typeof t[r]!="string"||!t[r].trim())throw Error("Native session requires provider and sessionid");for(let r of["sessiondir","model","effort"])if(t[r]!==void 0&&(typeof t[r]!="string"||!t[r].trim()))throw Error("Invalid native session "+r);if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(r=>!["permissionMode","idleTimeoutMs"].includes(r)))throw Error("Unknown native session option");if(e.permissionMode!==void 0&&!["plan","yolo"].includes(e.permissionMode))throw Error("permissionMode must be plan or yolo");if(e.idleTimeoutMs!==void 0&&(typeof e.idleTimeoutMs!="number"||!Number.isFinite(e.idleTimeoutMs)||e.idleTimeoutMs<0||e.idleTimeoutMs>2147483647))throw Error("idleTimeoutMs must be a bounded nonnegative number");if(n!==void 0&&(typeof n!="string"||Buffer.byteLength(n)>qx/2))throw Error("Native session prompt is invalid or exceeds the frame limit")}function Oh(t,e){return Et(t).db.prepare("SELECT * FROM agent_inflight WHERE native_provider=? AND native_session_id=?").get(e.provider,e.sessionid)??null}function Jx(t,e){return Et(t).findNativeHolder(e.native_provider,e.native_session_id)?.native_generation===e.native_generation&&!!e.native_boot_id&&lw(e.holder_pid)===e.native_boot_id+":"+e.native_start_time}function Vx(t,e,n,r){let s=JSON.parse(e.native_config_json??"null");return!!s&&s.profile===Xx(t)&&(n.sessiondir===void 0||Lh(t.cwd,n.sessiondir)===s.cwd)&&(n.model===void 0||n.model===s.model)&&(n.effort===void 0||n.effort===s.effort)&&(r.permissionMode===void 0||r.permissionMode===s.permissionMode)&&(r.idleTimeoutMs===void 0||r.idleTimeoutMs===s.idleTimeoutMs)}function i2(t){if(t?.workerPath)return t.workerPath;for(let e of[new URL("../native-holder/worker.js",import.meta.url),new URL("./native-holder-worker.js",import.meta.url),new URL("../../dist/native-holder/worker.js",import.meta.url)]){let n=r2(e);if(Ch(n))return n}throw Error("Native holder spawn failed: packaged worker is missing; rebuild or update lmctl")}async function o2(t,e,n,r){let s=i2(r);if(!Ch(s))return H("provider","Native holder spawn failed: worker entry is missing");let i=s2(t),o=t2(),a=Di(i,o+".json"),l=Di(i,o+".result"),c=Di(i,o+".log"),u,d,m=!1,p=!1,f,g=!1,h=!1;try{d=jx(a,"wx",384),m=!0,e2(d,JSON.stringify({cwd:t.cwd,dbPath:t.dbPath,env:t.env,member:e,options:n,resultFile:l})),Ah(d),d=void 0,u=jx(c,"wx",384),p=!0,f=zq(process.execPath,[s,a],{detached:!0,stdio:["ignore",u,u],env:{...t.env},cwd:t.cwd}),await new Promise((_,v)=>{f.once("spawn",()=>{g=!0,_()}),f.once("error",v)}),f.unref();let y=Hx.now()+Nh;for(;Hx.now()<y;){if(Ch(l)){let _=JSON.parse(Ux(l,"utf8"));return h=_.status==="ok",_}if(f.exitCode!==null||f.signalCode!==null)break;await Bx(10)}let b=Ux(c,"utf8").slice(-4096).trim();return H("provider","Native holder spawn failed: readiness deadline expired"+(b?"; "+b:""))}catch(y){return H("provider","Native holder spawn failed: "+G(y))}finally{d!==void 0&&Ah(d),u!==void 0&&Ah(u),m&&Gu(a,{force:!0}),Gu(l,{force:!0}),Gu(l+".tmp",{force:!0}),p&&Gu(c,{force:!0}),g&&!h&&f&&f.exitCode===null&&f.signalCode===null&&(f.kill("SIGTERM"),await Promise.race([new Promise(y=>f.once("close",()=>y())),Bx(1e3)]))}}async function Kx(t,e,n,r,s,i){let o={kind:s,provider:n.provider,sessionid:n.sessionid,generation:e.native_generation,member:{...n,...n.sessiondir!==void 0?{sessiondir:Lh(t.cwd,n.sessiondir)}:{}},options:r,prompt:i,profile:Xx(t),attribution:{LMCTL_SELF_SESSIONID:t.env.LMCTL_SELF_SESSIONID,LMCTL_INVOCATION_ID:t.env.LMCTL_INVOCATION_ID}};return new Promise(a=>{let l=Yq(e.native_endpoint),c=Buffer.alloc(0),u=!1,d=null,m=!1,p=h=>{u||(u=!0,clearTimeout(g),l.destroy(),a(h))},f=()=>Cn(m?"Native holder reply lost; outcome unknown"+(d?" (message "+d+")":""):"Native holder is unreachable; verify its process before recovery","closed",d),g=setTimeout(()=>p(f()),s==="close"?Nh+2e3:Nh);l.once("connect",()=>{m=!0,l.write(JSON.stringify(o)+`
|
|
2377
|
+
`)}),l.on("data",h=>{if(c=Buffer.concat([c,h]),c.length>qx)return p(Cn("Native holder response exceeds frame limit","closed",d));let y;for(;(y=c.indexOf(10))>=0;){let b=c.subarray(0,y);c=c.subarray(y+1);try{let _=JSON.parse(b.toString());if(_.kind==="accepted")typeof _.messageId=="string"&&(d=_.messageId,clearTimeout(g),g=setTimeout(()=>p(f()),24*60*60*1e3));else return _.kind==="result"?p(_.result):p(Cn("Invalid native holder response"))}catch{return p(Cn("Invalid native holder response"))}}}),l.once("error",()=>p(f())),l.once("close",()=>p(f()))})}async function a2(t,e){let n=sr(t),r=n.getAdapter(e.provider),s=Es(t.env.HOME?Di(t.env.HOME,".lmctl/config.toml"):void 0);if(!r)throw Error("Provider is not registered");if(e.provider==="kimi"&&r.openSession!==void 0&&s.tools[e.provider]?.agent===void 0)return!0;if(r.openSession!==void 0&&s.tools[e.provider]?.agent===void 0)throw Error("Persistent native holder is currently qualified for Kimi only");return!1}async function l2(t,e,n,r={},s){try{let i=me(t);if(i)return Cn(i.error,i.code);if(Gx(e,r,n),!await a2(t,e)){let a=await Wu(t,e,r);if(a.status!=="ok")return a.status==="busy"?{status:"busy",reply:"",error:a.error,messageId:null,teamChatLogId:null}:Cn(a.error,a.code);try{return await qu(t,a.session,n)}finally{await Xu(t,a.session)}}let o=Oh(t,e);if(!o){let a=Ih(t,Et(t),e,Lh(t.cwd,e.sessiondir??t.cwd));if(kr(Et(t),a.member.teamfile,a.member.alias).busy)return{status:"busy",reply:"",error:a.member.alias+" is busy; wait and retry",messageId:null,teamChatLogId:null};let c=await o2(t,e,r,s);if(c.status!=="ok")return c.status==="busy"?{status:"busy",reply:"",error:c.error,messageId:null,teamChatLogId:null}:Cn(c.error,c.code??"provider");o=Oh(t,e)}return!o||!Jx(t,o)?Cn("Native holder ownership is stale or unverified; verify provider shutdown before recovery"):Vx(t,o,e,r)?o.native_phase!=="ready"||!o.native_endpoint?{status:"busy",reply:"",error:e.sessionid+" is busy; wait and retry",messageId:null,teamChatLogId:null}:await Kx(t,o,e,r,"turn",n):Cn("Native holder configuration conflicts with this request","invalid_argument")}catch(i){return Cn(G(i),"invalid_argument")}}async function c2(t,e){try{let n=me(t);if(n)return n;Gx(e,{});let r=Oh(t,e);return r?Jx(t,r)?Vx(t,r,e,{})?r.native_phase!=="ready"||!r.native_endpoint?{status:"busy",error:e.sessionid+" is busy; wait and retry"}:await Kx(t,r,e,{},"close"):H("invalid_argument","Native holder configuration conflicts with this request"):H("closed","Native holder ownership is stale or unverified"):de({})}catch(n){return H("invalid_argument",G(n))}}function zx(t){if(t.status==="ok")return t;let e=t.status==="busy"?"busy":ns.includes(t.code)?t.code:"provider";return{...t,code:e}}async function Yx(t,e,n,r={},s){return zx(await l2(t,e,n,r,s))}async function Qx(t,e){return zx(await c2(t,e))}var qx,Nh,Cn,Bx,Zx=L(()=>{"use strict";pn();zt();Qt();xh();yn();Tr();Yo();Tu();tt();qx=1024*1024,Nh=5e3,Cn=(t,e="closed",n=null)=>({status:"error",reply:"",error:t,code:e,messageId:n,teamChatLogId:null}),Bx=t=>new Promise(e=>setTimeout(e,t))});var eA=L(()=>{"use strict";Nr()});var tA=L(()=>{"use strict"});import{constants as u2}from"node:os";import{spawn as d2}from"node:child_process";async function nA(t,e,n,r,s){let i=await m2(t,e,n,r,!1,s);return{code:s.signalObserved?null:i,signal:s.signalObserved??null}}async function m2(t,e,n,r,s,i){let o;try{o=Ft(e,n,r)}catch(S){return S instanceof Me?Cr(t,S.message):AE(t,S)}let a=Sr(r,{receiver_teamfile:o.teamfile,receiver_alias:o.alias,sender_teamfile:o.teamfile,sender_alias:"terminal",ttlMs:qr(i?.env??t.env)});if(!a.acquired){let S=a.current.holder_pid,R=S===null?null:ct(S)?"live":"dead",x=`${o.alias} is busy/held by ${a.current.sender_alias} (${a.current.sender_teamfile}) since ${a.current.started_at} `+(S===null?"(holder_pid=unavailable)":`(holder_pid=${S}, ${R})`);return s?(IE(t,{status:"error",errorKind:"busy",message:x,holder_pid:S,holder_liveness:R}),1):Cr(t,x)}let l=ax({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,g=null,h=!1,y,b,_,v=S=>{c!==null&&(clearInterval(c),c=null);try{let R=r.getTerminalLock(l.teamfile,l.alias);!r.clearTerminalLock(l.teamfile,l.alias,l.lock_id)&&R!==null&&S.push("terminal lock release was not acknowledged")}catch(R){S.push(`terminal lock release: ${R instanceof Error?R.message:String(R)}`)}try{let R=r.getAgentInflight(l.teamfile,l.alias);!r.releaseAgentInflight(a.lease,a.leaseId)&&R!==null&&S.push("inflight release was not acknowledged")}catch(R){S.push(`inflight release: ${R instanceof Error?R.message:String(R)}`)}},E=(S,R)=>{let x=r.db.pragma("busy_timeout",{simple:!0});r.db.pragma("busy_timeout=0");try{S(R)}finally{try{r.db.pragma(`busy_timeout=${x}`)}catch(A){R.push(`busy timeout restore: ${A instanceof Error?A.message:String(A)}`)}}},I=(S,R)=>{if(!(u===null||h))try{if(r.finishTrackedInvocation(u,S)===null){let A=r.getTrackedInvocation(u);A==null||A.status==="running"?R.push("tracked terminal finish was not acknowledged"):h=!0}else h=!0}catch(x){R.push(`tracked terminal finish: ${x instanceof Error?x.message:String(x)}`)}},T=S=>{if(f)return;f=!0;let R=[];try{E(x=>{v(x),I({status:"cancelled",signal:S,exit_code:S==="SIGINT"?130:143,error:`terminal interrupted by ${S}`},x)},R)}catch(x){R.push(x instanceof Error?x.message:String(x))}R.length>0&&(g=Error(R.join("; ")))},k=!i,N=k?new AbortController:void 0,C=()=>N?.abort("SIGINT"),O=()=>N?.abort("SIGTERM");k&&(process.once("SIGINT",C),process.once("SIGTERM",O));let w=i??{env:p,signal:N?.signal};w.env=p;try{if(w.cancel=T,w.cleanupError=()=>g,i&&i.onResource?.({close(){if(b)return b;let x,A;b=new Promise((P,U)=>{x=P,A=U});let M=performance.now();return(async()=>{if(T("SIGTERM"),i.stop?.("SIGTERM"),g)throw g;if(y){let P=5e3-(performance.now()-M),U;try{if(P<=0)throw Error("terminal close deadline exceeded");await Promise.race([y.catch(()=>{}),new Promise((F,ee)=>{U=setTimeout(()=>ee(Error("terminal close deadline exceeded")),P)})])}catch(F){throw g=F instanceof Error?F:Error(String(F)),g}finally{clearTimeout(U)}}})().then(x,A),b},finalizeSync(x){if(T(x),i.stop?.(x),g)throw g}}),f||w.signal?.aborted){let x=w.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM";return T(x),x==="SIGINT"?130:143}r.setTerminalLock(l),u=p2(r,o,p,i?.pid),u!==null&&(p.LMCTL_INVOCATION_ID=String(u));let S=r.getRootTeam(o.teamfile)?.name??null;S!==null&&(p.LMBEE_TEAM_NAME=S),c=setInterval(()=>{try{let x=new Date().toISOString(),A=r.heartbeatTerminalLock(l.teamfile,l.alias,l.lock_id,x);A&&r.heartbeatAgentInflight(a.lease,a.leaseId,x),!A&&c!==null&&(clearInterval(c),c=null)}catch{}},lx(p)),c.unref?.();try{Ci(t,Dt(o.teamfile),o.teamfile)}catch{}let R=w;return y=f2(t,{provider:o.provider,sessionid:o.sessionid,sessiondir:o.sessiondir,...o.model!==void 0?{model:o.model}:{},isLead:o.isLead},x=>{m.push(`${x.provider} terminal ignored model=${x.model}: ${x.reason}`)},R),d=await y,d}catch(S){throw _=S,S}finally{if(k&&(process.removeListener("SIGINT",C),process.removeListener("SIGTERM",O)),!f){f=!0;let S=[];try{E(R=>{v(R),I({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)}:{}},R)},S)}catch(R){S.push(R instanceof Error?R.message:String(R))}S.length>0&&(g=Error(S.join("; ")))}if(g){if(_===void 0)throw g;try{t.stderr.write("error: terminal cleanup: "+g.message+`
|
|
2378
2378
|
`)}catch{}}}}function p2(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:mc(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 f2(t,e,n,r){let{provider:s,sessionid:i,sessiondir:o,model:a}=e;if(!qg(s))return Cr(t,`no resume incantation for provider "${s}"`);if(!iR.test(i))return Cr(t,"refusing to resume: malformed sessionid");let l=oR(s,i,{isLead:e.isLead,model:a,onModelIgnored:f=>{let g=`warning: ${f.provider} terminal ignored model=${f.model}: ${f.reason}`;t.stderr.write(`${g}
|
|
2379
2379
|
`),dt({event:"model_ignored",provider:f.provider,model:f.model,reason:f.reason}),n?.(f)}});if(l===null||l.length===0)return Cr(t,`no resume incantation for provider "${s}"`);let c=je(r?.env??t.env??process.env,o,i,"terminal"),u=await aR(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+`
|
|
2380
2380
|
`),await new Promise(f=>{if(r?.signal?.aborted){let k=r.signal.reason==="SIGINT"?"SIGINT":"SIGTERM";return r.cancel?.(k),f(k==="SIGINT"?130:143)}let g=r?.streams,h=g?[g.stdin,g.stdout,g.stderr].map(k=>k.fd):void 0,y=h?.every(k=>typeof k=="number"),b=d2(p,m,{stdio:g?y?h:["pipe","pipe","pipe"]:"inherit",cwd:o,env:c}),_=g?.stdin?.readableFlowing;g&&!y&&(g.stdin.pipe(b.stdin),b.stdout?.pipe(g.stdout,{end:!1}),b.stderr?.pipe(g.stderr,{end:!1}));let v=!1,E=k=>{if(!v){v=!0;try{r?.cancel?.(k)}catch{}{try{b.kill(k)}catch{}ye(b,{stdinEnd:!1,softDelayMs:0,killDelayMs:100}).catch(()=>{})}}},I=()=>E(r?.signal?.reason==="SIGINT"?"SIGINT":"SIGTERM");r&&(r.stop=E);let T=()=>{r?.signal?.removeEventListener("abort",I),g&&!y&&(g.stdin.unpipe(b.stdin),_||g.stdin.pause(),b.stdout?.unpipe(g.stdout),b.stderr?.unpipe(g.stderr))};r?.signal?.addEventListener("abort",I,{once:!0}),r?.signal?.aborted&&I(),b.stdin?.on("error",()=>{}),b.on("error",k=>{T(),f(Cr(t,`failed to launch ${p}: ${k.message}`))}),b.on("exit",(k,N)=>{T(),r&&(r.signalObserved=N);let C=k??(N?128+(u2.signals[N]??1):1),O=lR(s);O&&C!==0&&C!==130&&C!==143&&!v&&!r?.signal?.aborted&&t.stderr.write(s+" exited with status "+C+". "+O+`
|
|
2381
|
-
`),f(C)})})}var rA=L(()=>{"use strict";bs();nn();yu();Nr();eA();qn();
|
|
2382
|
-
`)||`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 iA=L(()=>{"use strict";rA();zt();Qt();et()});import{isAbsolute as h2,resolve as y2}from"node:path";function Vu(t){return Number.isFinite(t)&&Math.abs(t)<=_2}function v2(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ns.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 Dh(t,e=Date.now()){if(t===void 0)return{windowMs:Ku};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||!Vu(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!Vu(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return Vu(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function Ju(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Ph(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return Mh;let s=e.get(n);if(s===void 0){try{s=Dt(n)}catch{s=null}e.set(n,s)}return s===null?Mh:cc(s,r)?.model??Mh}async function oA(t,e={}){let n=me(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=rr("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=Ku;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!Vu(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=Dh(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=Et(t),o=e?.teamfile!==void 0?h2(e.teamfile)?e.teamfile:y2(t.cwd,e.teamfile):void 0,a=o!==void 0?Tt(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=Jl(_),E=r-new Date(_.started_at).getTime(),I={id:_.id,kind:_.kind,origin:_.origin,from_identity:_.from_identity,target:Ju(_),model:Ph(_,d),started_at:_.started_at,parent_invocation_id:_.parent_invocation_id};if(v==="dead"){if(mh(i,_)!==null)continue;p.push({...I,stale_for_ms:E})}else m.push({...I,running_for_ms:E,holder_liveness:v??"unknown"})}let f=new Set(u.map(Ju).filter(_=>_!==null)),g=new Date(r-s).toISOString(),h=i.listRecentlyFinishedTrackedInvocations(g).filter(c),y=new Set,b=[];for(let _ of h){let v=Ju(_);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:Ph(_,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,g).filter(I=>!_.has(I.id)&&c(I));if(E.length===0)break;v=[];for(let I of E){_.add(I.id),v.push(I.id);let T=Ju(I);b.push({id:I.id,kind:I.kind,origin:I.origin,from_identity:I.from_identity,target:T,model:Ph(I,d),status:I.status,started_at:I.started_at,ended_at:I.ended_at,idle_ms:r-new Date(I.ended_at).getTime(),ran_ms:new Date(I.ended_at).getTime()-new Date(I.started_at).getTime(),error:I.error,parent_invocation_id:I.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:v2(i),running:[],dead:[],idle:[]}}}var Ku,_2,Mh,aA=L(()=>{"use strict";zt();Qt();mn();hn();Ou();vn();_s();Ku=24*60*60*1e3,_2=864e13;Mh="default"});var lA={};On(lA,{DAY_MS:()=>Ku,LMCTL_API_VERSION:()=>LG,LMCTL_ERROR_CODES:()=>ns,LMCTL_OPERATIONS:()=>at,LMCTL_PROFILE_VALUE_NAMES:()=>rO,LMCTL_PROPERTY_KEYS:()=>Qd,LMCTL_PROPERTY_TABLES:()=>sO,LMCTL_REMOVED_GLOBALS:()=>Zd,LMCTL_RESULT_FIELDS:()=>nO,batchTurn:()=>Cx,closeBatch:()=>Nx,closeNativeSession:()=>Xu,createLmctlContext:()=>Ww,deleteSession:()=>zR,fail:()=>H,finalizeBatchSync:()=>Ix,finalizeNativeSessionSync:()=>$x,getSession:()=>KR,inspectBatch:()=>xx,isLmctlContext:()=>li,lintTeam:()=>CB,listMembers:()=>xB,listRunning:()=>oA,listSessions:()=>VR,loadProfile:()=>R0,loadProperties:()=>I0,nativeSessionClose:()=>Qx,nativeSessionRequest:()=>Yx,nativeSessionTurn:()=>qu,ok:()=>de,openNativeSession:()=>Wu,openTeamBatch:()=>Ax,openTerminal:()=>sA,parseRunningSince:()=>Dh,profileValues:()=>k0,promptAgent:()=>BR,promptMember:()=>vx,promptReservedAgent:()=>XR,readPrompts:()=>MB,readRatelimits:()=>eq,releaseSession:()=>JR,reserveSession:()=>GR,resolveMember:()=>AB,resolveProfilePath:()=>sp,seedErrorCollector:()=>DR,seedTeam:()=>NB,sessionAdmission:()=>qR});var cA=L(()=>{"use strict";et();zt();eE();mn();FR();$R();YR();VI();Yg();bx();Ox();xh();Zx();iA();aA()});var fA={};On(fA,{createLmctlHostModule:()=>pA,default:()=>L2});import{AsyncLocalStorage as b2}from"node:async_hooks";import{randomUUID as w2}from"node:crypto";import{types as E2}from"node:util";import{createInterface as T2}from"node:readline";import{Writable as S2}from"node:stream";import{readFileSync as k2}from"node:fs";import{resolve as R2}from"node:path";import{homedir as I2}from"node:os";function uA(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ns.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 N2(t){if(t.name==="lm_log"||t.name==="lm_error")return{...t,arity:{min:2},params:[Fh,...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},Fh],readonly:!0};if(zu.has(t.name)||t.name==="lm_prompt"||t.name==="lm_agent"){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,Fh],readonly:zu.has(t.name)}}return t}function pA(t={}){let e={stdout:t.stdout??(r=>process.stdout.write(r)),stderr:t.stderr??(r=>process.stderr.write(r))},n={name:"lmctl",declarations:O2,async activate(r){let s=t.api??await Promise.resolve().then(()=>(cA(),lA)),i,o=new b2,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=I2());let S=s.createLmctlContext({env:w,cwd:r.cwd,pid:process.pid,onProgress:(R,x)=>a()[x??"stderr"](R),onWarning:R=>a().stderr(R)});if(S.status!=="ok")throw Error(S.error);return i=S,t.onContext?.(i),i},g={},h=()=>{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,S,R={},x)=>{let A=R&&typeof R=="object"&&!Array.isArray(R)?{permissionMode:R.permissionMode??"yolo",idleTimeoutMs:R.idleTimeoutMs??void 0}:R,M=x?await s.promptReservedAgent(f(),x,w,S,A):await s.promptAgent(f(),w,S,A);if(w&&typeof w=="object"&&M.sessionid&&M.status!=="busy"&&(w.sessionid=M.sessionid),w?.sessionid&&M.status!=="busy"){let P=JSON.stringify([w.provider,w.sessionid]),U=m.get(P)??{lines:[],options:{}};U.lines.push(`You: ${S}`),M.reply&&U.lines.push(`Agent: ${M.reply}`),M.error&&U.lines.push(`${M.status}: ${M.error}`),U.options={...R},m.set(P,U)}return{status:M.status,reply:M.reply,error:M.error?`lm_agent: ${M.error}`:null,message_id:null,team_chat_log_id:null}},_=(w,S)=>new Error(`${w}: ${S.error??"operation failed"}`),v=(w,S)=>{if(S.status!=="ok")throw _(w,S);return S},E=(w,S="lm_batch_turn",R=!1)=>{if(w!==null&&typeof w=="object"&&E2.isProxy(w))throw Error("Resource batch id cannot be read from a proxy");let x=w!==null&&typeof w=="object"?Object.getOwnPropertyDescriptor(w,"id"):void 0;if(x&&!("value"in x))throw Error("Resource batch id must be an own data property, not an accessor");let A=typeof w=="string"?w:x?.value,M=typeof A=="string"?d.get(A):void 0,P=Zi();if(!M){if(typeof A=="string"&&/^run-[0-9]+-[0-9]+\//.test(A)&&P&&!A.startsWith(P.runtime.token+"/"))throw Error("Resource batch "+A+" belongs to another run: "+S);return}if(!P)throw Error("Resource batch "+A+" requires an authorized script invocation");return P.runtime.authorizeRaw(M,P.scope,S,R),M},I=w=>{let S=Zi();if(!S)throw Error("lm_batch_open requires an authorized script invocation");w.id=S.runtime.token+"/"+w2(),w.kind="lmctl batch",w.closeDeadlineMs=5e3;let R;return w.close=(x={})=>{if(R)return R;let A,M;return R=new Promise((P,U)=>{A=P,M=U}),(async()=>{let P=l.get(w);if(P){v("lm_batch_close",await s.closeNativeSession(f(),P));return}let U=c.get(w);if(U){U.closed=!0;return}let F=x.explicit??[],ee=x.reason==="cancelled"?"cancelled":F[0]??(w.observedError?"error":x.reason??"done");v("lm_batch_close",await s.closeBatch(f(),u.get(w),{status:ee==="done"?"done":ee==="cancelled"?"cancelled":"error",error:F[1]??x.error}))})().then(A,M),R},w.finalizeSync=()=>{let x=f();if(x.closed){let A=x.finalizeSync("SIGTERM");if(A.errors.length)throw Error(A.errors.join(`
|
|
2381
|
+
`),f(C)})})}var rA=L(()=>{"use strict";bs();nn();yu();Nr();eA();qn();bn();on();wu();yn();Cu();ya();tA();Se();Tr()});import{resolve as g2}from"node:path";async function sA(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=me(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=_n(t,{async close(){try{await a?.close()}catch(f){throw i=!0,f}},finalizeSync(f){try{a?.finalizeSync(f)}catch(g){throw i=!0,g}}});let u=[],d=st(t,(f,g)=>{g==="stderr"&&f.startsWith("error:")&&u.push(f.replace(/^error:\s*/,"").trim())}),m=await nA({...d,stdin:n.stdin},g2(t.cwd,c.teamfile),c.alias,Et(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(`
|
|
2382
|
+
`)||`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 iA=L(()=>{"use strict";rA();zt();Qt();tt()});import{isAbsolute as h2,resolve as y2}from"node:path";function Vu(t){return Number.isFinite(t)&&Math.abs(t)<=_2}function v2(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ns.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 Dh(t,e=Date.now()){if(t===void 0)return{windowMs:Ku};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||!Vu(e-l)?{error:`invalid --since duration: ${t} (cutoff out of representable date range)`}:{windowMs:l}}let r=Date.parse(t);if(!Number.isFinite(r)||!Vu(r))return{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`};let s=Math.max(0,e-r);return Vu(e-s)?{windowMs:s}:{error:`invalid --since value: ${t} (cutoff out of representable date range)`}}function Ju(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Ph(t,e){let n=t.target_teamfile,r=t.target_alias;if(n===null||r===null)return Mh;let s=e.get(n);if(s===void 0){try{s=Dt(n)}catch{s=null}e.set(n,s)}return s===null?Mh:cc(s,r)?.model??Mh}async function oA(t,e={}){let n=me(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=rr("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=Ku;if(e?.since!==void 0)if(typeof e.since=="number"){if(!Number.isFinite(e.since)||e.since<0||!Vu(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=Dh(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=Et(t),o=e?.teamfile!==void 0?h2(e.teamfile)?e.teamfile:y2(t.cwd,e.teamfile):void 0,a=o!==void 0?Tt(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=Jl(_),E=r-new Date(_.started_at).getTime(),I={id:_.id,kind:_.kind,origin:_.origin,from_identity:_.from_identity,target:Ju(_),model:Ph(_,d),started_at:_.started_at,parent_invocation_id:_.parent_invocation_id};if(v==="dead"){if(mh(i,_)!==null)continue;p.push({...I,stale_for_ms:E})}else m.push({...I,running_for_ms:E,holder_liveness:v??"unknown"})}let f=new Set(u.map(Ju).filter(_=>_!==null)),g=new Date(r-s).toISOString(),h=i.listRecentlyFinishedTrackedInvocations(g).filter(c),y=new Set,b=[];for(let _ of h){let v=Ju(_);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:Ph(_,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,g).filter(I=>!_.has(I.id)&&c(I));if(E.length===0)break;v=[];for(let I of E){_.add(I.id),v.push(I.id);let T=Ju(I);b.push({id:I.id,kind:I.kind,origin:I.origin,from_identity:I.from_identity,target:T,model:Ph(I,d),status:I.status,started_at:I.started_at,ended_at:I.ended_at,idle_ms:r-new Date(I.ended_at).getTime(),ran_ms:new Date(I.ended_at).getTime()-new Date(I.started_at).getTime(),error:I.error,parent_invocation_id:I.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:v2(i),running:[],dead:[],idle:[]}}}var Ku,_2,Mh,aA=L(()=>{"use strict";zt();Qt();pn();yn();Ou();bn();_s();Ku=24*60*60*1e3,_2=864e13;Mh="default"});var lA={};On(lA,{DAY_MS:()=>Ku,LMCTL_API_VERSION:()=>LG,LMCTL_ERROR_CODES:()=>ns,LMCTL_OPERATIONS:()=>at,LMCTL_PROFILE_VALUE_NAMES:()=>rO,LMCTL_PROPERTY_KEYS:()=>Qd,LMCTL_PROPERTY_TABLES:()=>sO,LMCTL_REMOVED_GLOBALS:()=>Zd,LMCTL_RESULT_FIELDS:()=>nO,batchTurn:()=>Cx,closeBatch:()=>Nx,closeNativeSession:()=>Xu,createLmctlContext:()=>Ww,deleteSession:()=>zR,fail:()=>H,finalizeBatchSync:()=>Ix,finalizeNativeSessionSync:()=>$x,getSession:()=>KR,inspectBatch:()=>xx,isLmctlContext:()=>li,lintTeam:()=>CB,listMembers:()=>xB,listRunning:()=>oA,listSessions:()=>VR,loadProfile:()=>R0,loadProperties:()=>I0,nativeSessionClose:()=>Qx,nativeSessionRequest:()=>Yx,nativeSessionTurn:()=>qu,ok:()=>de,openNativeSession:()=>Wu,openTeamBatch:()=>Ax,openTerminal:()=>sA,parseRunningSince:()=>Dh,profileValues:()=>k0,promptAgent:()=>BR,promptMember:()=>vx,promptReservedAgent:()=>XR,readPrompts:()=>MB,readRatelimits:()=>eq,releaseSession:()=>JR,reserveSession:()=>GR,resolveMember:()=>AB,resolveProfilePath:()=>sp,seedErrorCollector:()=>DR,seedTeam:()=>NB,sessionAdmission:()=>qR});var cA=L(()=>{"use strict";tt();zt();eE();pn();FR();$R();YR();VI();Yg();bx();Ox();xh();Zx();iA();aA()});var fA={};On(fA,{createLmctlHostModule:()=>pA,default:()=>L2});import{AsyncLocalStorage as b2}from"node:async_hooks";import{randomUUID as w2}from"node:crypto";import{types as E2}from"node:util";import{createInterface as T2}from"node:readline";import{Writable as S2}from"node:stream";import{readFileSync as k2}from"node:fs";import{resolve as R2}from"node:path";import{homedir as I2}from"node:os";function uA(t){if(t&&typeof t=="object"){let e=t.code;if(typeof e=="string"){if(ns.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 N2(t){if(t.name==="lm_log"||t.name==="lm_error")return{...t,arity:{min:2},params:[Fh,...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},Fh],readonly:!0};if(zu.has(t.name)||t.name==="lm_prompt"||t.name==="lm_agent"){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,Fh],readonly:zu.has(t.name)}}return t}function pA(t={}){let e={stdout:t.stdout??(r=>process.stdout.write(r)),stderr:t.stderr??(r=>process.stderr.write(r))},n={name:"lmctl",declarations:O2,async activate(r){let s=t.api??await Promise.resolve().then(()=>(cA(),lA)),i,o=new b2,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=I2());let S=s.createLmctlContext({env:w,cwd:r.cwd,pid:process.pid,onProgress:(R,x)=>a()[x??"stderr"](R),onWarning:R=>a().stderr(R)});if(S.status!=="ok")throw Error(S.error);return i=S,t.onContext?.(i),i},g={},h=()=>{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,S,R={},x)=>{let A=R&&typeof R=="object"&&!Array.isArray(R)?{permissionMode:R.permissionMode??"yolo",idleTimeoutMs:R.idleTimeoutMs??void 0}:R,M=x?await s.promptReservedAgent(f(),x,w,S,A):await s.promptAgent(f(),w,S,A);if(w&&typeof w=="object"&&M.sessionid&&M.status!=="busy"&&(w.sessionid=M.sessionid),w?.sessionid&&M.status!=="busy"){let P=JSON.stringify([w.provider,w.sessionid]),U=m.get(P)??{lines:[],options:{}};U.lines.push(`You: ${S}`),M.reply&&U.lines.push(`Agent: ${M.reply}`),M.error&&U.lines.push(`${M.status}: ${M.error}`),U.options={...R},m.set(P,U)}return{status:M.status,reply:M.reply,error:M.error?`lm_agent: ${M.error}`:null,message_id:null,team_chat_log_id:null}},_=(w,S)=>new Error(`${w}: ${S.error??"operation failed"}`),v=(w,S)=>{if(S.status!=="ok")throw _(w,S);return S},E=(w,S="lm_batch_turn",R=!1)=>{if(w!==null&&typeof w=="object"&&E2.isProxy(w))throw Error("Resource batch id cannot be read from a proxy");let x=w!==null&&typeof w=="object"?Object.getOwnPropertyDescriptor(w,"id"):void 0;if(x&&!("value"in x))throw Error("Resource batch id must be an own data property, not an accessor");let A=typeof w=="string"?w:x?.value,M=typeof A=="string"?d.get(A):void 0,P=Zi();if(!M){if(typeof A=="string"&&/^run-[0-9]+-[0-9]+\//.test(A)&&P&&!A.startsWith(P.runtime.token+"/"))throw Error("Resource batch "+A+" belongs to another run: "+S);return}if(!P)throw Error("Resource batch "+A+" requires an authorized script invocation");return P.runtime.authorizeRaw(M,P.scope,S,R),M},I=w=>{let S=Zi();if(!S)throw Error("lm_batch_open requires an authorized script invocation");w.id=S.runtime.token+"/"+w2(),w.kind="lmctl batch",w.closeDeadlineMs=5e3;let R;return w.close=(x={})=>{if(R)return R;let A,M;return R=new Promise((P,U)=>{A=P,M=U}),(async()=>{let P=l.get(w);if(P){v("lm_batch_close",await s.closeNativeSession(f(),P));return}let U=c.get(w);if(U){U.closed=!0;return}let F=x.explicit??[],ee=x.reason==="cancelled"?"cancelled":F[0]??(w.observedError?"error":x.reason??"done");v("lm_batch_close",await s.closeBatch(f(),u.get(w),{status:ee==="done"?"done":ee==="cancelled"?"cancelled":"error",error:F[1]??x.error}))})().then(A,M),R},w.finalizeSync=()=>{let x=f();if(x.closed){let A=x.finalizeSync("SIGTERM");if(A.errors.length)throw Error(A.errors.join(`
|
|
2383
2383
|
`));return}if(l.has(w))v("lm_batch_close",s.finalizeNativeSessionSync(x,l.get(w)));else if(u.has(w))v("lm_batch_close",s.finalizeBatchSync(x,u.get(w)));else{let A=c.get(w);A&&(A.closed=!0)}},d.set(w.id,w),w},T=w=>w&&typeof w=="object"?u.get(w):void 0,k=w=>{let S=T(w);if(S){let R=v("lm_batch_open",s.inspectBatch(f(),S)),{status:x,error:A,...M}=R;Object.assign(w,{...M,id:w.close?w.id:M.id})}},C={lm_exit:(w=0)=>{let S=Number(w);throw new At(Number.isFinite(S)&&S>=0&&S<=255?Math.floor(S):1)},lm_log:(w,...S)=>{let R=mA(S);return a().stderr(R.endsWith(`
|
|
2384
2384
|
`)?R:R+`
|
|
2385
2385
|
`),R},lm_error:(w,...S)=>{let R=mA(S);return o.getStore()?.errors?.push(R),r.reportRecordedError(R),a().stderr("error: "+R+`
|
|
@@ -2397,7 +2397,7 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
2397
2397
|
`)?W:W+`
|
|
2398
2398
|
`)}),Xe=ae.exitCode??(ae.success&&(ae.errors?.length??0)===0?0:1),Wt=(ae.diagnostics??[]).filter(W=>W.severity==="error"&&!(ae.errors??[]).includes(W.message)),Fe=[...ae.errors??[],...Wt.map(W=>W.message)],B=[...q];for(let W of Fe){let oe=B.indexOf(W);oe>=0?B.splice(oe,1):r.reportRecordedError(W)}ee?.push(...Fe);for(let W of Wt)Y.stderr(`error:${W.file&&W.file!=="<main>"?W.file:x}:${W.line}:${W.column}: ${W.message}
|
|
2399
2399
|
`);return{success:Xe===0,stdout:U,output:ae.output,exit_code:Xe,code:Xe,value:ae.value,errors:[...ae.errors??[],...Wt.map(W=>W.message)]}})},{functions:C,globals:g,loadProperties:h,async dispose(){r.signal?.removeEventListener("abort",y);for(let w of d.values()){let S=c.get(w);S&&(S.closed=!0)}if(i){let w=await i.close();for(let S of d.values())if(T(S))try{k(S),S.closed=!0}catch(R){w.errors.push(R instanceof Error?R.message:String(R))}if(w.errors.length)throw Error(w.errors.join(`
|
|
2400
|
-
`))}}}}};return n}var x2,A2,C2,Fh,zu,dA,O2,Xr,mA,L2,gA=L(()=>{"use strict";mn();$s();M_();x2=[{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_batch_open",arity:{min:1,max:4},returnsResource:at.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}],A2=at.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(", ")+")"}}}),C2={lm_members:"map",lm_member:"map",lm_read_prompts:"map",lm_read_paragraphs:"map",lm_prompt:"map",lm_agent:"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"},Fh={name:"dryrun",type:"boolean",optional:!0},zu=new Set(at.filter(t=>["readPrompts","listMembers"].includes(t.name)&&t.effects.length>0&&t.effects.every(e=>e==="file-read")).map(t=>t.scriptBinding.name));zu.has("lm_read_prompts")&&zu.add("lm_read_paragraphs");dA=()=>({status:"ok",reply:"",error:null,message_id:null,team_chat_log_id:null,dry:!0}),O2={functions:[...A2,...x2].map(N2).map(t=>({...t,returnType:C2[t.name],doc:(()=>{let e=L_.find(n=>n.name===t.name)??("doc"in t?t.doc:void 0);return e?{...e,module:"lmctl"}:void 0})()})),globals:[],properties:{known:Qd,removedGlobals:Zd}},Xr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),mA=t=>t.map(e=>e!==null&&typeof e=="object"?JSON.stringify(e):String(e)).join(" ");L2=pA()});var $h,wa,jh,Uh=L(()=>{"use strict";$h=[{name:"db",type:"string",required:!0},{name:"local_scope",type:"string",required:!0},{name:"conversationid",type:"string",required:!0},{name:"escalationid",type:"string"}],wa=[{name:"lmbee_job_read",description:"Read live parent or child rows, including claimed rows.",keys:[...$h,{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:[...$h,{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:[...$h,{name:"where",type:"map",required:!0},{name:"state",type:"string",required:!0}]}],jh="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 hA}from"node:fs";import{createRequire as M2}from"node:module";import{dirname as P2}from"node:path";function D2(){return Hh===null&&(Hh=M2(import.meta.url)("node:sqlite").DatabaseSync),Hh}function j2(t){return $2[t]??F2[t&255]??`SQLITE_UNKNOWN_${t}`}function Nn(t){if(t!==null&&typeof t=="object"){let e=t;if(typeof e.errcode=="number")throw e.code=j2(e.errcode),t;if(e.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(e.message)))throw new TypeError(U2);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 H2(){let t="unable to open database file";return Object.assign(new Error(t),{code:"SQLITE_CANTOPEN",errcode:14,errstr:t})}function yA(t){return t instanceof Uint8Array&&!Buffer.isBuffer(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):t}function B2(t){if(t==null)return t;if(Array.isArray(t))return t.map(yA);if(typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=yA(r);return e}return t}function W2(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 Yu(t){return t.map((e,n)=>{if(e===void 0)return null;if(n===0&&W2(e)){let r={};for(let[s,i]of Object.entries(e))r[s]=i===void 0?null:i;return r}return e})}function q2(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function X2(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}var Hh,F2,$2,U2,Bh,Wh,qh,Xh=L(()=>{"use strict";Hh=null;F2={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"},$2={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"};U2="SQLite3 can only bind numbers, strings, bigints, buffers, and null";Bh=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(...Yu(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){Nn(n)}}get(...e){try{return this.project(this.handle.get(...Yu(e)))}catch(n){Nn(n)}}all(...e){try{return this.handle.all(...Yu(e)).map(n=>this.project(n))}catch(n){Nn(n)}}*iterate(...e){let n;try{n=this.handle.iterate(...Yu(e))}catch(r){Nn(r)}for(;;){let r;try{r=n.next()}catch(s){Nn(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=B2(e);return this.pluckMode&&Array.isArray(n)?n[0]:n}},Wh=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&&!hA(P2(e)))throw new TypeError("Cannot open database because the directory does not exist");if(n.fileMustExist===!0&&!r&&!hA(e))throw H2();this.name=e,this.memory=r,this.readonly=n.readonly===!0;try{this.handle=new(D2())(e,{readOnly:this.readonly,timeout:n.timeout??5e3,enableForeignKeyConstraints:n.foreignKeys??!0})}catch(s){Nn(s)}}get open(){return this.handle.isOpen}get inTransaction(){return this.handle.isTransaction}prepare(e){try{return new Bh(this.handle.prepare(e))}catch(n){Nn(n)}}exec(e){try{return this.handle.exec(e),this}catch(n){Nn(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){Nn(e)}}close(){if(!this.handle.isOpen)return this;try{return this.handle.close(),this}catch(e){Nn(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(!q2(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(!X2(o))throw o}throw i}}};qh=Wh});import{existsSync as Zre,lstatSync as G2,mkdirSync as ese,readFileSync as tse,realpathSync as _A}from"node:fs";import{basename as J2,dirname as bA,isAbsolute as V2,join as K2,relative as z2,resolve as vA}from"node:path";import{fileURLToPath as Y2}from"node:url";function wA(t){let e=process.env.LMBEE_TEST_DB_ROOT;if(!e||t===":memory:")return;let n=[],r=vA(t);for(;G2(r,{throwIfNoEntry:!1})===void 0;){n.unshift(J2(r));let o=bA(r);if(o===r)throw new Error("Cannot resolve test database path");r=o}let s=vA(_A(r),...n),i=z2(_A(e),s);if(i===".."||i.startsWith("../")||i.startsWith("..\\")||V2(i))throw new Error(`Database path is outside the test database root: ${t}`)}function EA(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 TA(t){let e=t.pragma("user_version",{simple:!0});if(e<=Qu)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)>Qu)r=`schema_meta.min_reader_version=${n} declares a breaking floor above ${Qu}`;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, ${Qu}, 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 sse,Qu,SA=L(()=>{"use strict";Xh();sse=K2(bA(Y2(import.meta.url)),"schema.sql");Qu=62});import{resolve as Q2,isAbsolute as Z2}from"node:path";function Jh(t){t.exec(`CREATE TABLE IF NOT EXISTS workflow_jobs (
|
|
2400
|
+
`))}}}}};return n}var x2,A2,C2,Fh,zu,dA,O2,Xr,mA,L2,gA=L(()=>{"use strict";pn();$s();M_();x2=[{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_batch_open",arity:{min:1,max:4},returnsResource:at.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}],A2=at.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(", ")+")"}}}),C2={lm_members:"map",lm_member:"map",lm_read_prompts:"map",lm_read_paragraphs:"map",lm_prompt:"map",lm_agent:"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"},Fh={name:"dryrun",type:"boolean",optional:!0},zu=new Set(at.filter(t=>["readPrompts","listMembers"].includes(t.name)&&t.effects.length>0&&t.effects.every(e=>e==="file-read")).map(t=>t.scriptBinding.name));zu.has("lm_read_prompts")&&zu.add("lm_read_paragraphs");dA=()=>({status:"ok",reply:"",error:null,message_id:null,team_chat_log_id:null,dry:!0}),O2={functions:[...A2,...x2].map(N2).map(t=>({...t,returnType:C2[t.name],doc:(()=>{let e=L_.find(n=>n.name===t.name)??("doc"in t?t.doc:void 0);return e?{...e,module:"lmctl"}:void 0})()})),globals:[],properties:{known:Qd,removedGlobals:Zd}},Xr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),mA=t=>t.map(e=>e!==null&&typeof e=="object"?JSON.stringify(e):String(e)).join(" ");L2=pA()});var $h,wa,jh,Uh=L(()=>{"use strict";$h=[{name:"db",type:"string",required:!0},{name:"local_scope",type:"string",required:!0},{name:"conversationid",type:"string",required:!0},{name:"escalationid",type:"string"}],wa=[{name:"lmbee_job_read",description:"Read live parent or child rows, including claimed rows.",keys:[...$h,{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:[...$h,{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:[...$h,{name:"where",type:"map",required:!0},{name:"state",type:"string",required:!0}]}],jh="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 hA}from"node:fs";import{createRequire as M2}from"node:module";import{dirname as P2}from"node:path";function D2(){return Hh===null&&(Hh=M2(import.meta.url)("node:sqlite").DatabaseSync),Hh}function j2(t){return $2[t]??F2[t&255]??`SQLITE_UNKNOWN_${t}`}function Nn(t){if(t!==null&&typeof t=="object"){let e=t;if(typeof e.errcode=="number")throw e.code=j2(e.errcode),t;if(e.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(e.message)))throw new TypeError(U2);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 H2(){let t="unable to open database file";return Object.assign(new Error(t),{code:"SQLITE_CANTOPEN",errcode:14,errstr:t})}function yA(t){return t instanceof Uint8Array&&!Buffer.isBuffer(t)?Buffer.from(t.buffer,t.byteOffset,t.byteLength):t}function B2(t){if(t==null)return t;if(Array.isArray(t))return t.map(yA);if(typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=yA(r);return e}return t}function W2(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 Yu(t){return t.map((e,n)=>{if(e===void 0)return null;if(n===0&&W2(e)){let r={};for(let[s,i]of Object.entries(e))r[s]=i===void 0?null:i;return r}return e})}function q2(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function X2(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}var Hh,F2,$2,U2,Bh,Wh,qh,Xh=L(()=>{"use strict";Hh=null;F2={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"},$2={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"};U2="SQLite3 can only bind numbers, strings, bigints, buffers, and null";Bh=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(...Yu(e));return{changes:Number(n.changes),lastInsertRowid:Number(n.lastInsertRowid)}}catch(n){Nn(n)}}get(...e){try{return this.project(this.handle.get(...Yu(e)))}catch(n){Nn(n)}}all(...e){try{return this.handle.all(...Yu(e)).map(n=>this.project(n))}catch(n){Nn(n)}}*iterate(...e){let n;try{n=this.handle.iterate(...Yu(e))}catch(r){Nn(r)}for(;;){let r;try{r=n.next()}catch(s){Nn(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=B2(e);return this.pluckMode&&Array.isArray(n)?n[0]:n}},Wh=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&&!hA(P2(e)))throw new TypeError("Cannot open database because the directory does not exist");if(n.fileMustExist===!0&&!r&&!hA(e))throw H2();this.name=e,this.memory=r,this.readonly=n.readonly===!0;try{this.handle=new(D2())(e,{readOnly:this.readonly,timeout:n.timeout??5e3,enableForeignKeyConstraints:n.foreignKeys??!0})}catch(s){Nn(s)}}get open(){return this.handle.isOpen}get inTransaction(){return this.handle.isTransaction}prepare(e){try{return new Bh(this.handle.prepare(e))}catch(n){Nn(n)}}exec(e){try{return this.handle.exec(e),this}catch(n){Nn(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){Nn(e)}}close(){if(!this.handle.isOpen)return this;try{return this.handle.close(),this}catch(e){Nn(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(!q2(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(!X2(o))throw o}throw i}}};qh=Wh});import{existsSync as ese,lstatSync as G2,mkdirSync as tse,readFileSync as nse,realpathSync as _A}from"node:fs";import{basename as J2,dirname as bA,isAbsolute as V2,join as K2,relative as z2,resolve as vA}from"node:path";import{fileURLToPath as Y2}from"node:url";function wA(t){let e=process.env.LMBEE_TEST_DB_ROOT;if(!e||t===":memory:")return;let n=[],r=vA(t);for(;G2(r,{throwIfNoEntry:!1})===void 0;){n.unshift(J2(r));let o=bA(r);if(o===r)throw new Error("Cannot resolve test database path");r=o}let s=vA(_A(r),...n),i=z2(_A(e),s);if(i===".."||i.startsWith("../")||i.startsWith("..\\")||V2(i))throw new Error(`Database path is outside the test database root: ${t}`)}function EA(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 TA(t){let e=t.pragma("user_version",{simple:!0});if(e<=Qu)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)>Qu)r=`schema_meta.min_reader_version=${n} declares a breaking floor above ${Qu}`;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, ${Qu}, 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 ise,Qu,SA=L(()=>{"use strict";Xh();ise=K2(bA(Y2(import.meta.url)),"schema.sql");Qu=62});import{resolve as Q2,isAbsolute as Z2}from"node:path";function Jh(t){t.exec(`CREATE TABLE IF NOT EXISTS workflow_jobs (
|
|
2401
2401
|
local_scope TEXT NOT NULL, conversationid TEXT NOT NULL, status TEXT NOT NULL,
|
|
2402
2402
|
PRIMARY KEY (local_scope, conversationid)
|
|
2403
2403
|
);
|
|
@@ -2409,9 +2409,9 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
2409
2409
|
FOREIGN KEY (local_scope, conversationid) REFERENCES workflow_jobs(local_scope, conversationid)
|
|
2410
2410
|
)`)}function kA(t,e,n){if(!Gh(t)||n&&!Object.keys(t).length)throw new Ve("Expected a nonempty column map");let r={};for(let[s,i]of Object.entries(t)){if(!eX[e].includes(s))throw new Ve(`Unknown ${e} column: ${s}`);if(s==="payload"){let o;try{o=JSON.stringify(i)}catch{throw new Ve("payload must be JSON")}if(o===void 0)throw new Ve("payload must be JSON");r[s]=o}else if(["pid","claimed_ms","attempts"].includes(s)){if(!(i===null&&s!=="attempts")&&!(typeof i=="number"&&Number.isSafeInteger(i)&&i>=0))throw new Ve(`${s} must be a nonnegative safe integer${s==="attempts"?"":" or null"}`);r[s]=i}else{if(!(typeof i=="string"||s==="answer_text"&&i===null))throw new Ve(`${s} must be a string${s==="answer_text"?" or null":""}`);r[s]=i}}return r}function RA(t){return Object.hasOwn(t,"escalationid")?{...t,payload:JSON.parse(t.payload),answer_present:t.answer_text!==null}:t}function IA(t,e,n){let r,s=!1;try{if(t.signal?.aborted)return Rt("cancelled","cancelled");let i=wa.find(v=>v.name===e);if(!i)throw new Error(`Unknown storage operation: ${e}`);if(!Gh(n))throw new Ve("options must be a map");for(let v of Object.keys(n))if(!i.keys.some(E=>E.name===v))throw new Ve(`Unknown option: ${v}`);for(let v of i.keys){let E=n[v.name];if(!(E===void 0&&!v.required)){if(v.type==="string"?typeof E!="string"||v.name!=="state"&&!E.length:!Gh(E))throw new Ve(`Invalid ${v.name}`);if("values"in v&&v.values&&!v.values.includes(E))throw new Ve(`Invalid ${v.name}`)}}let o=n,a=e==="lmbee_job_claim"?"escalation":o.row;if(a==="job"&&o.escalationid!==void 0)throw new Ve("job selection cannot include escalationid");if(s=e!=="lmbee_job_read",e==="lmbee_job_write"&&a==="escalation"&&!o.escalationid)throw new Ve("child write requires escalationid");let l=e==="lmbee_job_write"?kA(o.values,a,!0):{},c=o.where===void 0?{}:kA(o.where,a,e==="lmbee_job_claim");if(e==="lmbee_job_write"&&o.operation==="insert"){if(o.where!==void 0)throw new Ve("insert does not accept where");for(let v of a==="job"?["status"]:["payload","state"])if(!Object.hasOwn(l,v))throw new Ve(`insert requires ${v}`)}if(o.db.startsWith("~")||o.db===":memory:")throw new Ve("db must select an explicit durable database path");let u=Z2(o.db)?o.db:Q2(t.cwd,o.db);if(wA(u),r=new qh(u,{readonly:!s,fileMustExist:!0}),EA(r),TA(r),s)Jh(r);else if(!r.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workflow_jobs'").get())return Rt("no_rows");let d=r,m=[o.local_scope,o.conversationid],p=a==="job"?"workflow_jobs":"workflow_escalations",f="local_scope = ? AND conversationid = ?"+(o.escalationid?" AND escalationid = ?":""),g=[...m,...o.escalationid?[o.escalationid]:[]],h=()=>d.prepare(`SELECT * FROM ${p} WHERE ${f} ORDER BY ${a==="job"?"conversationid":"escalationid"}`).all(...g).map(RA),y=()=>d.prepare("SELECT 1 FROM workflow_jobs WHERE local_scope = ? AND conversationid = ?").get(...m),b=Object.keys(c).map(v=>`${v} IS ?`).join(" AND "),_=b?` AND ${b}`:"";if(!s){let v=h();return o.escalationid&&!v.length&&y()?Rt("error","selection_failed",[],!1,"No child matches this parent/child pair"):Rt(v.length?"ok":"no_rows",void 0,v)}return d.transaction(()=>{if(t.signal?.aborted)return Rt("cancelled","cancelled");if(a==="escalation"&&!y())return Rt("no_rows");if(e==="lmbee_job_write"&&o.operation==="insert"){let I={local_scope:o.local_scope,conversationid:o.conversationid,...a==="escalation"?{escalationid:o.escalationid}:{},...l};return d.prepare(`INSERT INTO ${p} (${Object.keys(I).join(", ")}) VALUES (${Object.keys(I).map(()=>"?").join(", ")})`).run(...Object.values(I)),Rt("ok","ok",h(),!0)}if(o.escalationid&&!h().length)return Rt("error","selection_failed",[],!1,"No child matches this parent/child pair");if(e==="lmbee_job_write")return d.prepare(`UPDATE ${p} SET ${Object.keys(l).map(T=>`${T} = ?`).join(", ")} WHERE ${f}${_}`).run(...Object.values(l),...g,...Object.values(c)).changes?Rt("ok","ok",h(),!0):Rt(h().length?"not_applied":"no_rows");let v=d.prepare(`SELECT escalationid FROM workflow_escalations WHERE ${f} AND pid IS NULL${_} ORDER BY escalationid LIMIT 1`).get(...g,...Object.values(c));if(!v)return Rt("no_rows");d.prepare("UPDATE workflow_escalations SET pid = ?, claimed_ms = ?, state = ?, attempts = attempts + 1 WHERE local_scope = ? AND conversationid = ? AND escalationid = ?").run(t.pid,t.now(),o.state,...m,v.escalationid);let E=d.prepare("SELECT * FROM workflow_escalations WHERE local_scope = ? AND conversationid = ? AND escalationid = ?").get(...m,v.escalationid);return Rt("ok","ok",[RA(E)],!0)}).immediate()}catch(i){if(i instanceof Ve)return Rt("error","invalid_argument",[],!1,i.message);if(!i.code?.startsWith("SQLITE_")&&!(i instanceof Error&&/Refusing|refus|database/i.test(i.message)))throw i;return Rt("error",s&&r?"write_rejected":"database_unavailable",[],!1,i instanceof Error?i.message:String(i))}finally{r?.close()}}var Ve,Rt,Gh,eX,xA=L(()=>{"use strict";Xh();SA();Uh();Ve=class extends Error{},Rt=(t,e=t,n=[],r=!1,s=null)=>({status:t,code:e,rows:n,applied:r,error:s}),Gh=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),eX={job:["status"],escalation:["payload","answer_text","pid","claimed_ms","state","attempts"]}});var AA={};On(AA,{ensureJobSchema:()=>Jh,jobOperation:()=>IA});var CA=L(()=>{"use strict";xA()});var NA={};On(NA,{createLmbeeHostModule:()=>tX});function tX(){return{name:"lmbee",declarations:{globals:[],functions:wa.map(t=>({name:t.name,arity:1,params:[{name:"options",type:"map",keys:t.keys}],doc:{name:t.name,module:"lmbee",category:"Storage",signature:`${t.name}(options)`,description:`${t.description} ${jh}`,returns:{type:"map",description:jh}}}))},async activate(t){let{jobOperation:e}=await Promise.resolve().then(()=>(CA(),AA)),n={cwd:t.cwd,env:t.env,signal:t.signal,pid:process.pid,now:Date.now};return{globals:{},functions:Object.fromEntries(wa.map(r=>[r.name,s=>e(n,r.name,s)])),dispose(){}}}}}var OA=L(()=>{"use strict";Uh()});function It(t){return LA.has(t)}var LA,Ea=L(()=>{LA=new Set(["__proto__","constructor","prototype"])});function Ns(t){return t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Vh(t){return t.replace(/-([a-z0-9])/g,(e,n)=>n.toUpperCase())}function Zu(t){return t.occurs==="1"||t.occurs==="+"||t.occurs===void 0}function Kh(t){let e=`--${Ns(t.name)}`,n=t.type==="array"?t.items??"string":t.type,r=t.type==="boolean"?"":` <${n}${t.items?` of ${t.items}`:""}>`,s=t.enum&&t.enum.length>0?` one of: ${t.enum.join(", ")}`:"";return`${e}${r}${s}`}function Ta(t,e){let n=[];e&&n.push(e),n.push(t.name);for(let r of t.params)r.positional===!0&&n.push(`[<${r.name}>]`);return n.push("[flags]"),n.join(" ")}var Os=L(()=>{});function PA(t,e){let n=Array.from({length:e.length+1},(r,s)=>s);for(let r=1;r<=t.length;r++){let s=n[0];n[0]=r;for(let i=1;i<=e.length;i++){let o=n[i];n[i]=Math.min(n[i]+1,n[i-1]+1,s+(t[r-1]===e[i-1]?0:1)),s=o}}return n[e.length]}function nX(t,e){let n=Vh(t.replace(/^--/,"")),r,s=3;for(let i of e){let o=PA(n,i.name),a=PA(Ns(n),Ns(i.name)),l=Math.min(o,a);l<s&&(s=l,r=i.name)}return r}function FA(t){if(Array.isArray(t))return t;if(typeof t=="string"){let e=t.trim();if(e.startsWith("[")&&e.endsWith("]"))try{let n=JSON.parse(e);if(Array.isArray(n))return n}catch{}return[t]}if(typeof t=="number"||typeof t=="boolean")return[t]}function DA(t,e){switch(t){case"boolean":return typeof e=="boolean"?{ok:!0,value:e}:e==="true"?{ok:!0,value:!0}:e==="false"?{ok:!0,value:!1}:{ok:!1,received:e};case"number":{if(typeof e=="number")return Number.isFinite(e)?{ok:!0,value:e}:{ok:!1,received:e};if(typeof e=="string"){if(e.trim()==="")return{ok:!1,received:e};if(/^-?\d+$/.test(e))return{ok:!0,value:Number.parseInt(e,10)};if(/^-?(?:\d+\.?\d*|\d*\.\d+)(?:[eE][+-]?\d+)?$/.test(e)){let n=Number(e);if(Number.isFinite(n))return{ok:!0,value:n}}}return{ok:!1,received:e}}case"string":return typeof e=="string"?{ok:!0,value:e}:typeof e=="number"||typeof e=="boolean"?{ok:!0,value:String(e)}:{ok:!1,received:e};case"object":{if(e!==null&&typeof e=="object"&&!Array.isArray(e))return{ok:!0,value:e};if(typeof e=="string")try{let n=JSON.parse(e);if(n!==null&&typeof n=="object"&&!Array.isArray(n))return{ok:!0,value:n}}catch{}return{ok:!1,received:e}}case"json":return{ok:!0,value:e};default:return{ok:!0,value:e}}}function zh(t,e,n){let r=[],s=Object.create(null),i=Ta(t);It(t.name)&&r.push({code:"RESERVED_NAME",message:`operation name "${t.name}" is a reserved name. Expected: ${i}`,op:t.name,synopsis:i,usage:i});for(let a of t.params)if(It(a.name)&&r.push({code:"RESERVED_NAME",message:`param "${a.name}" is a reserved name. Expected: ${i}`,op:t.name,param:a.name,synopsis:i,usage:i}),a.aliases)for(let l of a.aliases)It(l)&&r.push({code:"RESERVED_NAME",message:`param "${a.name}" alias "${l}" is a reserved name. Expected: ${i}`,op:t.name,param:l,synopsis:i,usage:i});let o=new Map;for(let a of t.params){It(a.name)||o.set(a.name,a);for(let l of a.aliases??[])It(l)||o.set(l,a)}for(let a of Object.keys(e))if(a.startsWith("--")||!o.has(a))if(!a.startsWith("--")&&t.additionalParams===!0&&!It(a))s[a]=e[a];else{let l=nX(a,t.params);r.push({code:"UNKNOWN_PARAM",message:`unknown param: ${a}. Expected: ${i}`,param:a,synopsis:i,usage:i,received:e[a],...l!==void 0?{suggestion:l}:{}})}for(let a of t.params){if(It(a.name))continue;let l=Kh(a),c,u=MA(e,a.name);if(u&&(c=e[a.name]),(!u||c===void 0)&&a.aliases){for(let f of a.aliases)if(MA(e,f)&&e[f]!==void 0){c=e[f],u=!0;break}}let d=Zu(a);if(n?.form&&c!==void 0){if(a.cliOnly===!0&&(n.form==="json"||n.form==="graphql")){r.push({code:"FORM_NOT_ALLOWED",message:`param "${a.name}" is CLI-only and not allowed in ${n.form} form. Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:c});continue}if(a.docOnly===!0&&n.form==="flags"){r.push({code:"FORM_NOT_ALLOWED",message:`param "${a.name}" is doc-only and not allowed in flags form. Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:c});continue}}if(c===null)if(d){r.push({code:"TYPE_MISMATCH",message:`expected ${a.type} for param "${a.name}", received null. Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:null});continue}else c=void 0;if(c===void 0){if(a.default!==void 0){s[a.name]=a.default;continue}d&&r.push({code:"MISSING_REQUIRED",message:`missing required param: ${a.name}. Expected: ${l}`,param:a.name,synopsis:l,usage:i});continue}if(a.occurs==="+"||a.occurs==="*"||a.type==="array"){let f=FA(c);if(f===void 0){r.push({code:"TYPE_MISMATCH",message:`expected array for param "${a.name}". Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:c});continue}if(a.occurs==="+"&&f.length===0){r.push({code:"MISSING_REQUIRED",message:`param "${a.name}" requires at least one item. Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:c});continue}if(f.length===0){s[a.name]=[];continue}let g=a.type==="array"?a.items??"string":a.type,h=[],y=!1;for(let b of f){let _=DA(g,b);if(!_.ok){r.push({code:"TYPE_MISMATCH",message:`expected ${g} item for param "${a.name}". Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:b}),y=!0;break}if(a.enum&&a.enum.length>0&&!a.enum.includes(_.value)){r.push({code:"ENUM_VIOLATION",message:`invalid value for param "${a.name}": ${JSON.stringify(_.value)}; allowed: ${a.enum.join(", ")}. Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:_.value,allowed:a.enum}),y=!0;break}h.push(_.value)}y||(s[a.name]=h);continue}let p=DA(a.type,c);if(!p.ok){r.push({code:"TYPE_MISMATCH",message:`expected ${a.type} for param "${a.name}". Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:c});continue}if(a.enum&&a.enum.length>0&&!a.enum.includes(p.value)){r.push({code:"ENUM_VIOLATION",message:`invalid value for param "${a.name}": ${JSON.stringify(p.value)}; allowed: ${a.enum.join(", ")}. Expected: ${l}`,param:a.name,synopsis:l,usage:i,received:p.value,allowed:a.enum});continue}s[a.name]=p.value}return r.length>0?{ok:!1,issues:r}:{ok:!0,value:s}}var MA,Sa=L(()=>{Ea();Os();MA=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)});var jA=L(()=>{Sa();Os();Ea()});var UA=L(()=>{Sa();Os()});function HA(t){if(typeof t!="string")return!1;let e=t.trim().split(/\s+/).filter(Boolean);if(e.length===0||e.length>4)return!1;for(let n of e)if(!iX.test(n))return!1;return!0}function qA(t){if(typeof t!="string"||t.length>200)return-1;try{let n=new RegExp(t+"|()").exec("");return n?n.length-2:-1}catch{return-1}}var iX,BA,WA,Yh=L(()=>{iX=/^(>=|>|<=|<|=)(\d+\.\d+\.\d+)$/;BA=/^[a-z][a-z0-9_.-]{0,63}$/,WA=/^[a-z][a-z0-9_.-]*$/});function lX(t,e,n,r,s){if(t===void 0)return!0;let i=o=>!s||s.length===0||s.includes(o);if(r==="+"||r==="*"||e==="array"){if(!Array.isArray(t))return!1;let o=n??(e==="array"?"string":e);return t.every(a=>i(a)&&YA(a,o))}return i(t)&&YA(t,e)}function YA(t,e){switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!Number.isNaN(t);case"boolean":return typeof t=="boolean";case"object":return typeof t=="object"&&t!==null&&!Array.isArray(t);case"array":return Array.isArray(t);case"json":return t!==void 0;default:return!1}}function ka(t){let e=[],n=(o,a,l={})=>{let c=l.usage??(l.op?`${l.op} [flags]`:"<unknown> [flags]"),u=l.synopsis??c;e.push({code:o,message:`${a}. Expected: ${u}`,...l.op?{op:l.op}:{},...l.param?{param:l.param}:{},synopsis:u,usage:c,...l.received!==void 0?{received:l.received}:{},...l.allowed!==void 0?{allowed:l.allowed}:{}})};if(t===null||typeof t!="object"||Array.isArray(t))return n("DOCUMENT_PARSE","cli.schema.v1: document must be an object",{received:t}),{ok:!1,issues:e};let r=t;r.schema!=="cli.schema.v1"&&n("DOCUMENT_PARSE",`cli.schema.v1: unsupported schema tag: ${JSON.stringify(r.schema)}`,{received:r.schema,allowed:["cli.schema.v1"]});let s=r.tool;if(typeof s!="string"||!KA.test(s)?n("DOCUMENT_PARSE",`cli.schema.v1: tool must be a string matching ^[a-z][a-z0-9_]*$, received ${JSON.stringify(s)}`,{received:s}):It(s)&&n("RESERVED_NAME",`cli.schema.v1: tool cannot be named "${s}" (reserved name)`,{received:s}),r.version!==void 0&&typeof r.version!="string"&&n("TYPE_MISMATCH",`cli.schema.v1: version must be a string, received ${typeof r.version}`,{received:r.version}),r.policy!==void 0)if(r.policy===null||typeof r.policy!="object"||Array.isArray(r.policy))n("TYPE_MISMATCH","cli.schema.v1: policy must be an object",{received:r.policy});else{let o=r.policy;(typeof o.dryrun!="boolean"||typeof o.readonly!="boolean")&&n("TYPE_MISMATCH","cli.schema.v1: policy must contain boolean dryrun and readonly properties",{received:r.policy})}if(r.inputs!==void 0)if(!Array.isArray(r.inputs))n("TYPE_MISMATCH","cli.schema.v1: inputs must be an array",{received:r.inputs});else for(let o of r.inputs)["flags","json","graphql"].includes(o)||n("ENUM_VIOLATION",`cli.schema.v1: inputs contains unsupported form "${String(o)}"`,{received:o,allowed:["flags","json","graphql"]});let i=(o,a,l=!1)=>{if(o===null||typeof o!="object"||Array.isArray(o)){n("TYPE_MISMATCH",`cli.schema.v1: param${a?` in "${a}"`:""} must be an object`,{op:a,received:o});return}let c=o,u=c.name;if(typeof u!="string"){n("TYPE_MISMATCH",`cli.schema.v1: param${a?` in "${a}"`:""} needs a string name`,{op:a,received:u});return}for(let y of Object.keys(c))zA.has(y)||n("UNKNOWN_PARAM",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} has unknown property "${y}"`,{op:a,param:u,received:y,allowed:Array.from(zA)});(l?aX:oX).test(u)?It(u)&&n("RESERVED_NAME",`cli.schema.v1: ${l?"global ":""}param "${u}"${a?` in "${a}"`:""} is a reserved name`,{op:a,param:u,received:u}):n("DOCUMENT_PARSE",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} name must match ${l?"^[A-Za-z_][A-Za-z0-9_-]*$":"^[A-Za-z_]\\w*$"}`,{op:a,param:u,received:u}),!l&&u==="dryrun"&&n("DOCUMENT_PARSE",'cli.schema.v1: param cannot be named "dryrun" (reserved global policy flag)',{op:a,param:u,received:u});let m=c.aliases;if(m!==void 0&&Array.isArray(m))for(let y of m)typeof y=="string"&&It(y)&&n("RESERVED_NAME",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} alias "${y}" is a reserved name`,{op:a,param:u,received:y});let p=c.type;(typeof p!="string"||!Qh.has(p))&&n("ENUM_VIOLATION",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} has invalid type: ${JSON.stringify(p)}`,{op:a,param:u,received:p,allowed:Array.from(Qh)});let f=c.occurs;f!==void 0&&!XA.has(f)&&n("ENUM_VIOLATION",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} has invalid occurs: ${JSON.stringify(f)}`,{op:a,param:u,received:f,allowed:Array.from(XA)});let g=c.enum;g!==void 0&&(!Array.isArray(g)||!g.every(y=>typeof y=="string"||typeof y=="number"))&&n("TYPE_MISMATCH",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} enum must be an array of strings or numbers`,{op:a,param:u,received:g});let h=c.items;if(h!==void 0&&!GA.has(h)&&n("ENUM_VIOLATION",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} has invalid items type: ${JSON.stringify(h)}`,{op:a,param:u,received:h,allowed:Array.from(GA)}),c.default!==void 0&&Qh.has(p)){let y=Array.isArray(g)?g:void 0;lX(c.default,p,h,f,y)||n("TYPE_MISMATCH",`cli.schema.v1: param "${u}"${a?` in "${a}"`:""} default value does not match declared type "${p}"`,{op:a,param:u,received:c.default})}};if(r.globals!==void 0)if(!Array.isArray(r.globals))n("TYPE_MISMATCH","cli.schema.v1: globals must be an array",{received:r.globals});else for(let o of r.globals)i(o,void 0,!0);if(!Array.isArray(r.operations))n("DOCUMENT_PARSE","cli.schema.v1: operations must be an array",{received:r.operations});else{let o=new Set;for(let a of r.operations){if(a===null||typeof a!="object"||Array.isArray(a)){n("DOCUMENT_PARSE","cli.schema.v1: every operation must be an object",{received:a});continue}let l=a,c=l.name;if(typeof c!="string"){n("DOCUMENT_PARSE","cli.schema.v1: every operation needs a string name",{received:c});continue}if(KA.test(c)?It(c)&&n("RESERVED_NAME",`cli.schema.v1: operation cannot be named "${c}" (reserved name)`,{op:c,received:c}):n("DOCUMENT_PARSE",`cli.schema.v1: operation name "${c}" must match ^[a-z][a-z0-9_]*$`,{op:c,received:c}),o.has(c)&&n("DOCUMENT_PARSE",`cli.schema.v1: duplicate operation name "${c}"`,{op:c}),o.add(c),l.access!==void 0&&(JA.has(l.access)||n("ENUM_VIOLATION",`cli.schema.v1: operation "${c}" has invalid access: ${JSON.stringify(l.access)}`,{op:c,received:l.access,allowed:Array.from(JA)})),l.returns!==void 0&&(VA.has(l.returns)||n("ENUM_VIOLATION",`cli.schema.v1: operation "${c}" has invalid returns: ${JSON.stringify(l.returns)}`,{op:c,received:l.returns,allowed:Array.from(VA)})),!Array.isArray(l.params))n("DOCUMENT_PARSE",`cli.schema.v1: operation "${c}" needs a params array`,{op:c,received:l.params});else for(let u of l.params)i(u,c,!1)}}if(r.product!==void 0){let o=r.product;if(o===null||typeof o!="object"||Array.isArray(o))n("TYPE_MISMATCH","cli.schema.v1: product must be an object",{received:o});else{let a=o,l=new Set(["name","supported","detect"]);for(let d of Object.keys(a))l.has(d)||n("UNKNOWN_PARAM",`cli.schema.v1: unknown product property "${d}"`,{received:d,allowed:Array.from(l)});let c=a.name;typeof c!="string"?n("TYPE_MISMATCH","cli.schema.v1: product.name must be a string",{received:c}):BA.test(c)||n("DOCUMENT_PARSE",`cli.schema.v1: product.name must match ^[a-z][a-z0-9_.-]{0,63}$, received ${JSON.stringify(c)}`,{received:c});let u=a.supported;if(typeof u!="string"?n("TYPE_MISMATCH","cli.schema.v1: product.supported must be a string",{received:u}):HA(u)||n("DOCUMENT_PARSE",`cli.schema.v1: product.supported must be a conjunction of 1 to 4 comparators (>=, >, <=, <, = followed by numeric x.y.z), received ${JSON.stringify(u)}`,{received:u}),a.detect!==void 0){let d=a.detect;if(d===null||typeof d!="object"||Array.isArray(d))n("TYPE_MISMATCH","cli.schema.v1: product.detect must be an object",{received:d});else{let m=d,p=new Set(["argv","pattern"]);for(let h of Object.keys(m))p.has(h)||n("UNKNOWN_PARAM",`cli.schema.v1: unknown product.detect property "${h}"`,{received:h,allowed:Array.from(p)});let f=m.argv;if(!Array.isArray(f)||f.length<1||f.length>8||!f.every(h=>typeof h=="string"&&h.length>0))n("DOCUMENT_PARSE","cli.schema.v1: product.detect.argv must be an array of 1 to 8 non-empty strings",{received:f});else{let h=f[0];WA.test(h)||n("DOCUMENT_PARSE",`cli.schema.v1: product.detect.argv[0] must match ^[a-z][a-z0-9_.-]*$ (no slashes), received ${JSON.stringify(h)}`,{received:h})}let g=m.pattern;if(typeof g!="string")n("TYPE_MISMATCH","cli.schema.v1: product.detect.pattern must be a string",{received:g});else if(g.length>200)n("DOCUMENT_PARSE",`cli.schema.v1: product.detect.pattern exceeds maximum length of 200 characters (${g.length})`,{received:g});else{let h=qA(g);h!==1&&n("DOCUMENT_PARSE",`cli.schema.v1: product.detect.pattern must be a valid RegExp with exactly one capture group, found ${h}`,{received:g})}}}}}return e.length>0?{ok:!1,issues:e}:{ok:!0,value:t}}var Qh,XA,GA,JA,VA,KA,oX,aX,zA,Zh=L(()=>{Ea();Sa();Yh();Qh=new Set(["string","number","boolean","object","array","json"]),XA=new Set(["1","?","+","*"]),GA=new Set(["string","number","boolean","object"]),JA=new Set(["read","write","dynamic"]),VA=new Set(["object","array","string","number","boolean","null"]),KA=/^[a-z][a-z0-9_]*$/,oX=/^[A-Za-z_]\w*$/,aX=/^[A-Za-z_][A-Za-z0-9_-]*$/,zA=new Set(["name","type","occurs","default","enum","positional","items","description","aliases","cliOnly","docOnly","derived"])});var QA=L(()=>{Os();Os()});function ZA(t,e){let n=Object.create(null);for(let[r,s]of Object.entries(e))s!==void 0&&(n[r]=s);return JSON.stringify({op:t.name,params:n})}var eC=L(()=>{});var tC=L(()=>{Ea();Os();Sa();jA();UA();Zh();QA();eC();Yh()});var lC={};On(lC,{INLINE_DOCUMENT_LIMIT:()=>sC,createSchemaModule:()=>aC,createSchemaModuleFactory:()=>vX,parseSchemaDocument:()=>ey,schemaToDeclarations:()=>oC});import{mkdtempSync as cX,writeFileSync as uX,rmSync as dX}from"node:fs";import{tmpdir as mX}from"node:os";import{join as nC}from"node:path";function ey(t){let e;try{e=JSON.parse(t)}catch(s){throw Error("not valid JSON: "+(s instanceof Error?s.message:String(s)))}let n=ka(e);if(!n.ok){let s=n.issues[0];throw Error(s.message+(n.issues.length>1?` (and ${n.issues.length-1} more issue${n.issues.length>2?"s":""})`:""))}let r=n.value;for(let s of r.operations)for(let i of s.params)if(ty.includes(i.name))throw Error(`${r.tool} ${s.name}: param '${i.name}' collides with a runner global`);return r}function ed(t){return gX(t)?"list":{string:"string",number:"number",boolean:"boolean",object:"map",array:"list",json:"any"}[t.type]??"any"}function iC(t,e){let n=e.params.filter(a=>!a.cliOnly),r=n.filter(a=>a.positional===!0),s=n.filter(a=>a.positional!==!0),i=s.some(Jr),o=r.findIndex(a=>!Jr(a));if(o>=0&&(r.slice(o).some(Jr)||i))throw Error(`${t} ${e.name}: a required argument follows an optional positional`);return{positionals:r,options:s,optsRequired:i}}function yX(t){let e=[t.default!==void 0?"default: "+JSON.stringify(t.default):"",t.enum?.length?"one of: "+t.enum.join(", "):"",t.derived?"loosely typed":""].filter(Boolean),n=t.occurs==="+"?"+":t.occurs==="*"?"*":Jr(t)?"":"?";return ed(t)+n+(t.description?" \u2014 "+t.description:"")+(e.length?" ("+e.join("; ")+")":"")}function oC(t,e=t.tool){return{functions:t.operations.map(r=>{let s=e+"."+r.name,{positionals:i,options:o,optsRequired:a}=iC(t.tool,r),l=[...o.map(m=>({name:m.name,type:ed(m),...Jr(m)?{required:!0}:{},...m.enum?.length?{values:[...m.enum]}:{}})),...ty.map(m=>({name:m,type:"boolean"}))],c=[...i.map(m=>({name:m.name,type:ed(m),checkLiteral:!0,...m.enum?.length?{values:[...m.enum]}:{},...Jr(m)?{}:{optional:!0}})),{name:"opts",type:"map",keys:l,...r.additionalParams?{open:!0}:{},...a?{}:{optional:!0}},{name:"dryrun",type:"boolean",optional:!0}],u=i.filter(Jr).length+(a?1:0),d={name:s,module:e,category:hX[r.access??"write"]??"Write operations",signature:s+"(...)",description:(r.description??`${t.tool} ${r.name}`)+(r.params.some(m=>m.derived)?" (derived schema: params loosely typed)":""),parameters:[...i,...o].map(m=>({name:m.name,type:ed(m)+(Jr(m)?"":"?"),description:yX(m)})).concat([{name:"readonly",type:"boolean?",description:`boolean? \u2014 pass --readonly to ${t.tool}`},{name:"confirm",type:"boolean?",description:`boolean? \u2014 pass --confirm to ${t.tool} (attests a dangerous write)`}]),returns:{type:"map",description:`{status:"ok", result} with the parsed JSON of ${t.tool} ${r.name}; {status:"error", error:{code, message}}; {status:"simulated"} in the dry pass`}};return{name:s,arity:{min:u,max:i.length+2},params:c,returnType:"map",readonly:!1,doc:d}}),globals:[]}}function rC(t){return t.trimEnd().split(`
|
|
2411
2411
|
`).slice(-fX).join(`
|
|
2412
|
-
`)}function _X(t){return t.map(e=>`${e.code}${e.param?` '${e.param}'`:""}${e.suggestion?` (did you mean '${e.suggestion}'?)`:""}: ${e.message}`).join("; ")}function aC(t,e={}){let n=ey(t.text),r=t.alias??n.tool;if(!pX.test(r))throw Error(`namespace ${JSON.stringify(r)} is not an identifier`);let s=e.timeoutMs??0,i=oC(n,r);return{name:"schema:"+r,nativeNamespace:r,declarations:i,async activate(o){let a=ey(t.text),l={};for(let c of a.operations){let u=r+"."+c.name,{positionals:d}=iC(a.tool,c);l[u]=async(...m)=>{let p=m[d.length+1]===!0,f=m[d.length]??{};if(!Ra(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 g=[],h=Object.create(null);for(let[C,O]of d.entries())m[C]!==void 0&&(h[O.name]=m[C]);for(let[C,O]of Object.entries(f)){if(ty.includes(C)){if(typeof O!="boolean")throw Error(`${u}: option '${C}' must be boolean`);O&&g.push("--"+C);continue}if(Object.hasOwn(h,C))throw Error(`${u}: '${C}' given both positionally and as an option`);h[C]=O}if(p)return{status:"simulated",simulated:u};let y=zh(c,h,{form:"json"});if(!y.ok)return Gr({code:"validation",message:`${u}: ${_X(y.issues)}`,issues:[...y.issues]});let b=o.platform??process.platform,_=a.tool,v=ZA(c,h),E=()=>{},I,T;try{let C=[_,c.name,"--input-json",v,...g];if(Buffer.byteLength(v)>sC){let O=cX(nC(mX(),"lmscript-"+a.tool+"-")),w=nC(O,"input.json");E=()=>dX(O,{recursive:!0,force:!0}),uX(w,v,{mode:384}),C=[_,c.name,"--input-file",w,...g]}T=await Qa(C,s,b,o.signal,{cwd:o.cwd,env:o.env},{maxOutputBytes:e.maxOutputBytes??0})}catch(C){let O=C;if(O?.code==="ERR_OUTPUT_LIMIT")return Gr({code:"output_limit",message:`${u}: ${a.tool} ${O.message}`});if(O?.message==="Aborted")throw C;return Gr({code:"launch",message:`${u}: cannot run ${a.tool}: ${O?.message??String(C)}`})}finally{try{E()}catch(C){I=C}}if(T.timed_out)return Gr({code:"timeout",message:`${u}: ${a.tool} timed out after ${s} ms`,...T.stderr.trim()?{stderr_tail:rC(T.stderr)}:{}});let k,N=!1;try{k=JSON.parse(T.stdout),N=!0}catch{}if(N&&Ra(k)&&k.success===!1&&Ra(k.error)){let C=k.error,O=Ra(C.data)?C.data:{},w=Ra(O.details)?O.details:O,S=Array.isArray(w.issues)?[...w.issues]:[],R=C.code==="VALIDATION_ERROR"?` (the input passed client validation; schema ${a.version??"unversioned"} may be stale)`:"";return Gr({code:"envelope",message:`${u}: ${String(C.code??"ERROR")}: ${String(C.message??"")}${R}`,tool_code:String(C.code??"ERROR"),...S.length?{issues:S}:{},exit:T.code})}return T.code!==0||T.signal!==null?Gr({code:"exit",message:`${u}: ${a.tool} exit ${T.code??"none"}${T.signal?` (signal ${T.signal})`:""}`,exit:T.code,signal:T.signal,...T.stderr.trim()?{stderr_tail:rC(T.stderr)}:{}}):N?I!==void 0?Gr({code:"launch",message:`${u}: cannot remove temporary input: ${I instanceof Error?I.message:String(I)}`}):{status:"ok",result:k}:Gr({code:"parse",message:`${u}: ${a.tool} ${c.name} printed invalid JSON${T.stdout.trim()?": "+T.stdout.trim().slice(0,200):" (empty stdout)"}`})}}return{functions:l,globals:{},dispose(){}}}}}function vX(t={}){return e=>aC(e,t)}var ty,pX,fX,sC,Jr,gX,hX,Ra,Gr,cC=L(()=>{"use strict";tC();$s();ty=["readonly","confirm"],pX=/^[A-Za-z_]\w*$/,fX=12,sC=100*1024;Jr=t=>t.default===void 0&&(t.occurs===void 0||t.occurs==="1"||t.occurs==="+"),gX=t=>t.type==="array"||t.occurs==="+"||t.occurs==="*";hX={read:"Read operations",write:"Write operations",dynamic:"Dynamic operations"};Ra=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Gr=t=>({status:"error",error:t})});function Re(t){return{ok:!0,value:t}}function
|
|
2412
|
+
`)}function _X(t){return t.map(e=>`${e.code}${e.param?` '${e.param}'`:""}${e.suggestion?` (did you mean '${e.suggestion}'?)`:""}: ${e.message}`).join("; ")}function aC(t,e={}){let n=ey(t.text),r=t.alias??n.tool;if(!pX.test(r))throw Error(`namespace ${JSON.stringify(r)} is not an identifier`);let s=e.timeoutMs??0,i=oC(n,r);return{name:"schema:"+r,nativeNamespace:r,declarations:i,async activate(o){let a=ey(t.text),l={};for(let c of a.operations){let u=r+"."+c.name,{positionals:d}=iC(a.tool,c);l[u]=async(...m)=>{let p=m[d.length+1]===!0,f=m[d.length]??{};if(!Ra(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 g=[],h=Object.create(null);for(let[C,O]of d.entries())m[C]!==void 0&&(h[O.name]=m[C]);for(let[C,O]of Object.entries(f)){if(ty.includes(C)){if(typeof O!="boolean")throw Error(`${u}: option '${C}' must be boolean`);O&&g.push("--"+C);continue}if(Object.hasOwn(h,C))throw Error(`${u}: '${C}' given both positionally and as an option`);h[C]=O}if(p)return{status:"simulated",simulated:u};let y=zh(c,h,{form:"json"});if(!y.ok)return Gr({code:"validation",message:`${u}: ${_X(y.issues)}`,issues:[...y.issues]});let b=o.platform??process.platform,_=a.tool,v=ZA(c,h),E=()=>{},I,T;try{let C=[_,c.name,"--input-json",v,...g];if(Buffer.byteLength(v)>sC){let O=cX(nC(mX(),"lmscript-"+a.tool+"-")),w=nC(O,"input.json");E=()=>dX(O,{recursive:!0,force:!0}),uX(w,v,{mode:384}),C=[_,c.name,"--input-file",w,...g]}T=await Qa(C,s,b,o.signal,{cwd:o.cwd,env:o.env},{maxOutputBytes:e.maxOutputBytes??0})}catch(C){let O=C;if(O?.code==="ERR_OUTPUT_LIMIT")return Gr({code:"output_limit",message:`${u}: ${a.tool} ${O.message}`});if(O?.message==="Aborted")throw C;return Gr({code:"launch",message:`${u}: cannot run ${a.tool}: ${O?.message??String(C)}`})}finally{try{E()}catch(C){I=C}}if(T.timed_out)return Gr({code:"timeout",message:`${u}: ${a.tool} timed out after ${s} ms`,...T.stderr.trim()?{stderr_tail:rC(T.stderr)}:{}});let k,N=!1;try{k=JSON.parse(T.stdout),N=!0}catch{}if(N&&Ra(k)&&k.success===!1&&Ra(k.error)){let C=k.error,O=Ra(C.data)?C.data:{},w=Ra(O.details)?O.details:O,S=Array.isArray(w.issues)?[...w.issues]:[],R=C.code==="VALIDATION_ERROR"?` (the input passed client validation; schema ${a.version??"unversioned"} may be stale)`:"";return Gr({code:"envelope",message:`${u}: ${String(C.code??"ERROR")}: ${String(C.message??"")}${R}`,tool_code:String(C.code??"ERROR"),...S.length?{issues:S}:{},exit:T.code})}return T.code!==0||T.signal!==null?Gr({code:"exit",message:`${u}: ${a.tool} exit ${T.code??"none"}${T.signal?` (signal ${T.signal})`:""}`,exit:T.code,signal:T.signal,...T.stderr.trim()?{stderr_tail:rC(T.stderr)}:{}}):N?I!==void 0?Gr({code:"launch",message:`${u}: cannot remove temporary input: ${I instanceof Error?I.message:String(I)}`}):{status:"ok",result:k}:Gr({code:"parse",message:`${u}: ${a.tool} ${c.name} printed invalid JSON${T.stdout.trim()?": "+T.stdout.trim().slice(0,200):" (empty stdout)"}`})}}return{functions:l,globals:{},dispose(){}}}}}function vX(t={}){return e=>aC(e,t)}var ty,pX,fX,sC,Jr,gX,hX,Ra,Gr,cC=L(()=>{"use strict";tC();$s();ty=["readonly","confirm"],pX=/^[A-Za-z_]\w*$/,fX=12,sC=100*1024;Jr=t=>t.default===void 0&&(t.occurs===void 0||t.occurs==="1"||t.occurs==="+"),gX=t=>t.type==="array"||t.occurs==="+"||t.occurs==="*";hX={read:"Read operations",write:"Write operations",dynamic:"Dynamic operations"};Ra=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Gr=t=>({status:"error",error:t})});function Re(t){return{ok:!0,value:t}}function ue(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 td=L(()=>{});function Ia(t){if(typeof t!="string"||t.trim()==="")return ue("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=uC.exec(a);if(!c)return ue("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 ue("SPEC_SYNTAX",`Invalid owner or repo name: "${t}"`);if(l!=="latest"&&l!=="dev")return ue("SPEC_CHANNEL","only the latest and dev channels are supported");let m=l,p=`@${u}/${d}#${m}`;return Re({owner:u,repo:d,channel:m,key:p,requested:t})}let n=uC.exec(t);if(!n)return ue("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 ue("SPEC_SYNTAX",`Invalid owner or repo name: "${t}"`);let i="latest",o=`@${r}/${s}#${i}`;return Re({owner:r,repo:s,channel:i,key:o,requested:t})}var uC,ny=L(()=>{td();uC=/^@([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9][A-Za-z0-9._-]*)$/});import{homedir as bX}from"node:os";import{isAbsolute as dC,join as mC,relative as pC,resolve as ry}from"node:path";function Fi(t=process.env){let e=t.LMCTL_HOME&&t.LMCTL_HOME.trim()!==""?t.LMCTL_HOME:mC(t.HOME??bX(),".lmctl");return mC(e,"modules")}function sy(t,e){let n=ry(t),r=ry(n,"github.com"),s=ry(r,e.owner,e.repo,e.channel),i=pC(n,s),o=pC(r,s);if(i.startsWith("..")||dC(i)||o.startsWith("..")||dC(o))throw new Error(`Path traversal detected: entry directory "${s}" escapes cache root "${n}"`);return s}function nd(t){return`cli.schema.${t}.json`}var iy=L(()=>{});import{createHash as gC,randomUUID as rd}from"node:crypto";import{existsSync as sd,promises as Bt}from"node:fs";import{dirname as oie,isAbsolute as aie,join as un,relative as lie,resolve as cie}from"node:path";async function TX(t){let e=un(t,yC);if(!sd(e))return Re(t);try{let n=(await Bt.readFile(e,"utf8")).trim();if(!wX.test(n)||n==="."||n==="..")return ue("CACHE_CORRUPT",`Invalid ${e}`);let r=un(t,"generations",n);return sd(r)?Re(r):ue("CACHE_CORRUPT",`Missing cache generation ${n}`)}catch(n){return ue("CACHE_CORRUPT",`Failed to read ${e}: ${n?.message??String(n)}`)}}function ly(t){return typeof t=="string"?Ia(t):Re(t)}async function Ls(t,e){let n=ly(t);if(!n.ok)return ue(n.code,n.message);let r=n.value,s=e?.root??Fi(),i;try{i=sy(s,r)}catch(h){return ue("PATH_TRAVERSAL",h?.message??String(h))}let o=nd(r.channel),a=await TX(i);if(!a.ok)return a;let l=a.value,c=un(l,o),u=un(l,"meta.json");if(!sd(c)||!sd(u))return ue(l===i?"NOT_INSTALLED":"CACHE_CORRUPT",`Module ${r.key} is missing cache files`);let d,m;try{d=await Bt.readFile(c)}catch(h){return ue("CACHE_CORRUPT",`Failed to read ${c}: ${h?.message??String(h)}; run: lmbee module install ${r.key} --force`,{file:c})}try{let h=await Bt.readFile(u,"utf-8");m=JSON.parse(h)}catch(h){return ue("CACHE_CORRUPT",`Failed to read or parse ${u}: ${h?.message??String(h)}; run: lmbee module install ${r.key} --force`,{file:u})}let p=gC("sha256").update(d).digest("hex");if(p!==m.sha256)return ue("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(h){return ue("BAD_JSON",`Failed to parse ${c} as JSON: ${h?.message??String(h)}`,{file:c})}let g=ka(f);return g.ok?Re({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:g.value.tool,version:g.value.version,document:g.value}):ue("INVALID_SCHEMA",`Cached schema in ${c} is invalid: ${g.issues[0]?.message}`,{file:c,issues:g.issues})}async function _C(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 ue("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 ue("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"?ue("FETCH_FAILED",`Fetch timed out after ${n}ms for ${t}`):ue("FETCH_FAILED",`Network error fetching ${t}: ${o?.message??String(o)}`)}return Re(i)}async function vC(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(),ue("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 ue("OUTPUT_LIMIT",`Schema exceeds maximum size limit of ${e} bytes`);o=Buffer.from(u)}}catch(u){return u?.name==="TimeoutError"||u?.name==="AbortError"?ue("FETCH_FAILED",`Fetch stream timed out after ${n}ms`):ue("FETCH_FAILED",`Error reading response stream: ${u?.message??String(u)}`)}let a;try{a=JSON.parse(o.toString("utf-8"))}catch(u){return ue("BAD_JSON",`Failed to parse ${s} from ${i} as JSON: ${u?.message??String(u)}`)}let l=ka(a);if(!l.ok){let u=l.issues[0]?.message??"Schema validation failed";return ue("INVALID_SCHEMA",`Invalid schema for ${r}: ${u}`,{issues:l.issues})}let c=gC("sha256").update(o).digest("hex");return Re({buffer:o,sha256:c,schema:l.value})}async function ay(t,e,n,r){let s=`gen-${Date.now()}-${rd()}`,i=un(t,"generations",s),o=un(i,`.tmp.schema.${rd()}`),a=un(i,`.tmp.meta.${rd()}`),l=un(i,e),c=un(i,"meta.json"),u=un(t,`.tmp.current.${rd()}`);try{await Bt.mkdir(i,{recursive:!0,mode:448}),await Bt.writeFile(o,n,{mode:384}),await Bt.rename(o,l),await fC(l,384),await Bt.writeFile(a,JSON.stringify(r,null,2)+`
|
|
2413
2413
|
`,{mode:384}),await Bt.rename(a,c),await fC(c,384),await Bt.writeFile(u,s+`
|
|
2414
|
-
`,{mode:384}),await Bt.rename(u,
|
|
2414
|
+
`,{mode:384}),await Bt.rename(u,un(t,yC))}catch(d){return await oy(o),await oy(a),await oy(u),ue("ATOMIC_WRITE_FAILED",`Failed to write cached module files: ${d?.message??String(d)}`)}return Re(void 0)}async function bC(t,e){let n=ly(t);if(!n.ok)return ue(n.code,n.message);let r=n.value,s=e?.root??Fi(),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 Ls(r,{root:s});if(!m.ok){if(m.code==="CACHE_CORRUPT")return m;if(m.code==="NOT_INSTALLED"){if(!l)return ue("NOT_INSTALLED",`Module ${r.key} is not installed; run: lmbee module install ${r.key}`);let P=await SX(r,{root:s,fetchImpl:a,now:o,timeoutMs:u,maxBytes:d});return P.ok?Re({module:P.value.entry,source:"installed"}):ue(P.code,P.message,{file:P.file,issues:P.issues,details:P.details})}return m}let p=m.value,f=o().getTime(),g=p.lastChecked?new Date(p.lastChecked).getTime():NaN,h=!isNaN(g)&&g>f,y=isNaN(g),b=f-g;if(!y&&!h&&b>=0&&b<i||!c)return Re({module:p,source:"cache"});let v=nd(r.channel),E=`${hC}/${r.owner}/${r.repo}/HEAD/${v}`,I=await _C(E,{timeoutMs:u,fetchImpl:a,etag:p.etag});if(!I.ok)return Re({module:p,source:"stale-cache",warning:I.message});let T=I.value;if(T.status===304){let P=o().toISOString(),U=T.headers.get("etag")??T.headers.get("ETag")??p.etag,F;try{F=await Bt.readFile(p.path)}catch(te){return Re({module:p,source:"stale-cache",warning:`Failed to read cached schema: ${te?.message??String(te)}`})}let ee={spec:r.key,url:E,sha256:p.sha256,fetched_at:p.fetchedAt,last_checked:P,etag:U,channel:r.channel,tool:p.tool,version:p.version,bytes:F.length},q=await ay(p.dir,v,F,ee);if(!q.ok)return Re({module:p,source:"stale-cache",warning:q.message});let Y=await Ls(r,{root:s});return Y.ok?Re({module:Y.value,source:"network"}):Re({module:p,source:"stale-cache",warning:Y.message})}if(T.status!==200)return Re({module:p,source:"stale-cache",warning:`Failed to refresh ${r.key}: HTTP ${T.status} ${T.statusText}`});let k=await vC(T,d,u,r.key,v,E);if(!k.ok)return Re({module:p,source:"stale-cache",warning:k.message});let{buffer:N,sha256:C,schema:O}=k.value,w=T.headers.get("etag")??T.headers.get("ETag")??void 0,S=o().toISOString(),R=S,x={spec:r.key,url:E,sha256:C,fetched_at:S,last_checked:R,etag:w,channel:r.channel,tool:O.tool,version:O.version??"unknown",bytes:N.length},A=await ay(p.dir,v,N,x);if(!A.ok)return Re({module:p,source:"stale-cache",warning:A.message});let M=await Ls(r,{root:s});return M.ok?Re({module:M.value,source:"network"}):Re({module:p,source:"stale-cache",warning:M.message})}async function SX(t,e){let n=ly(t);if(!n.ok)return ue(n.code,n.message);let r=n.value,s=e?.root??Fi(),i=e?.fetchImpl??globalThis.fetch,o=e?.now??(()=>new Date),a=e?.timeoutMs??1e4,l=e?.maxBytes??EX,c=e?.force??!1,u;try{u=sy(s,r)}catch(C){return ue("PATH_TRAVERSAL",C?.message??String(C))}let d=nd(r.channel),m=`${hC}/${r.owner}/${r.repo}/HEAD/${d}`,p=await Ls(r,{root:s});if(!c&&p.ok)return Re({action:"unchanged",entry:p.value});let f=await _C(m,{timeoutMs:a,fetchImpl:i});if(!f.ok)return f;let g=f.value;if(g.status===404)return ue("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(!g.ok)return ue("FETCH_FAILED",`Failed to fetch ${m}: HTTP ${g.status} ${g.statusText}`,{details:{status:g.status,url:m}});let h=await vC(g,l,a,r.key,d,m);if(!h.ok)return h;let{buffer:y,sha256:b,schema:_}=h.value;if(!c&&p.ok&&p.value.sha256===b)return Re({action:"unchanged",entry:p.value});let v=g.headers.get("etag")??g.headers.get("ETag")??void 0,E=o().toISOString(),I=E,T={spec:r.key,url:m,sha256:b,fetched_at:E,last_checked:I,etag:v,channel:r.channel,tool:_.tool,version:_.version??"unknown",bytes:y.length},k=await ay(u,d,y,T);if(!k.ok)return k;let N=await Ls(r,{root:s});return N.ok?Re({action:p.ok?"replaced":"installed",entry:N.value}):N}async function fC(t,e){try{await Bt.chmod(t,e)}catch{}}async function oy(t){try{await Bt.unlink(t)}catch{}}var hC,wX,EX,yC,wC=L(()=>{Zh();iy();ny();td();hC="https://raw.githubusercontent.com",wX=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,EX=2*1024*1024,yC="CURRENT"});var EC=L(()=>{td();ny();iy();wC()});var RC={};On(RC,{createModuleResolver:()=>xX,isModuleSpecifier:()=>IX,normalizeModuleSpec:()=>SC,parseModuleOverrides:()=>kC});import{readFileSync as kX}from"node:fs";import{resolve as RX}from"node:path";function IX(t){return t.startsWith("@")}function SC(t){let e=Ia(t);if(!e.ok)throw Error(`${t}: ${e.message}`);return e.value.key}function kC(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(SC(r.slice(0,s)),RX(e,r.slice(s+1)))}return n}function TC(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 xX(t){let e=kC(t.overrides??[],t.cwd??process.cwd()),n=t.root??Fi({...t.env}),r=new Map;return{resolve:async i=>{let o=Ia(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=kX(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 Ls(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,TC(u.value,"cache")),{key:a,source:JSON.stringify(u.value.document)}}let c=await bC(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,TC(c.value.module,c.value.source,c.value.warning)),{key:a,source:JSON.stringify(c.value.module.document)}},provenance:r}}var IC=L(()=>{"use strict";EC()});var u_={};On(u_,{runCli:()=>uy,stableDiagnostic:()=>Aa});import{readFileSync as xC,fstatSync as AC,writeSync as AX}from"node:fs";import{Socket as CX}from"node:net";import{resolve as xa,dirname as NX}from"node:path";function Aa(t,e="<inline>"){return`${t.severity}:${t.file&&t.file!=="<main>"?t.file:e}:${t.line}:${t.column}: ${t.message}
|
|
2415
2415
|
`}function OX(t){let e=Buffer.from(t),n=0,r;for(;n<e.length;)try{let s=AX(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 uy(t,e={}){if(t.length===1&&["--version","-v"].includes(t[0]))return(e.stdout??($=>process.stdout.write($)))("lmscript "+c_()+`
|
|
2416
2416
|
`),0;let n=[...t],r=e.cwd??process.cwd(),s={...e.env??process.env},i=e.stdout??($=>process.stdout.write($)),o=e.stderr??OX,a=new Set,l=[],c=$=>{$.startsWith("error: ")&&l.push($);let K=$.match(/^error:.*:[0-9]+:[0-9]+: ([^\n]+)/);K&&a.add(K[1]),o($)},u,d=!1,m=!1,p,f,g=!1,h=!1,y,b,_="text",v,E=new Set,I=new Set(["--base-dir","--source-name","--resumepoint","--pref","--dry-loop-limit","--dryrun-timeout","--plan-format","--module"]),T=[],k=new Set(["--check","--dry-run","--lint","--check-files","--no-preflight",...I]);for(;n.length&&k.has(n[0]);){let $=n.shift();if(E.has($)&&$!=="--module")return c("error: "+$+` may be specified only once
|
|
2417
2417
|
`),$==="--resumepoint"?2:1;E.add($);let K;if(I.has($)){if(K=n[0],K===void 0||$==="--pref"&&K===""||K.startsWith("-"))return c("error: "+$+($==="--resumepoint"||$==="--pref"?` requires a path
|
|
@@ -2439,11 +2439,11 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
2439
2439
|
`+K),0)}for(let $ of te.diagnostics)c(Aa($,x));if(te.diagnostics.some($=>$.severity==="error"))return 2;if(d)return 0;let ae={currentPath:null};Y.recoveryProbe=ae;let Xe=!1,Wt=()=>{let $=ae.firstFailure?.path;Xe||$==null||(Xe=!0,W("resumepoint: "+$+" (rerun with --resumepoint "+$+`)
|
|
2440
2440
|
`))},Fe,B,W=$=>{try{c($)}catch{}},oe=$=>{for(let K of P)try{let ke=K.finalizeSync($);for(let Ca of ke.errors)W("error: resource critical finalization: "+Ca+`
|
|
2441
2441
|
`)}catch(ke){W("error: resource critical finalization: "+String(ke)+`
|
|
2442
|
-
`)}A.terminateResourceRuns()},ve=($,K=$==="SIGINT"?130:143)=>{Fe===void 0&&(Fe=K,ae.firstFailure??={path:ae.currentPath},oe($),M.abort($),B=setTimeout(()=>{Wt(),process.exit(Fe)},250))},gt=()=>ve("SIGINT"),Vr=()=>ve("SIGTERM"),Ms=()=>ve("SIGTERM",129);if(e.installSignals!==!1&&!e.stdout&&!CC&&(CC=!0,process.stdout.on("error",$=>{if($.code!=="EPIPE")throw $;oe("SIGTERM"),process.exit(0)})),e.installSignals!==!1){process.on("SIGINT",gt),process.on("SIGTERM",Vr),process.on("SIGHUP",Ms);let $=Number(s.LMSCRIPT_LIFELINE_FD);if(delete s.LMSCRIPT_LIFELINE_FD,e.env||delete process.env.LMSCRIPT_LIFELINE_FD,Number.isInteger($)&&$>2)try{if(AC($).isFIFO()||AC($).isSocket()){let K=new CX({fd:$,readable:!0,writable:!1});K.on("error",()=>{}),K.on("end",Vr),K.on("close",Vr),K.resume(),K.unref()}}catch{}}Y.signal=M.signal;try{let $=new Set(te.diagnostics.map(He=>JSON.stringify(He))),K=He=>{if(!(Fe!==void 0||!g))for(let
|
|
2443
|
-
`),Fe??He.exitCode)}Y.onPreflight=K;let ke=await A.runAsync(w,Y);for(let He of ke.diagnostics)$.has(JSON.stringify(He))||c(Aa(He,x));let Ca=He=>{let
|
|
2444
|
-
`);return
|
|
2442
|
+
`)}A.terminateResourceRuns()},ve=($,K=$==="SIGINT"?130:143)=>{Fe===void 0&&(Fe=K,ae.firstFailure??={path:ae.currentPath},oe($),M.abort($),B=setTimeout(()=>{Wt(),process.exit(Fe)},250))},gt=()=>ve("SIGINT"),Vr=()=>ve("SIGTERM"),Ms=()=>ve("SIGTERM",129);if(e.installSignals!==!1&&!e.stdout&&!CC&&(CC=!0,process.stdout.on("error",$=>{if($.code!=="EPIPE")throw $;oe("SIGTERM"),process.exit(0)})),e.installSignals!==!1){process.on("SIGINT",gt),process.on("SIGTERM",Vr),process.on("SIGHUP",Ms);let $=Number(s.LMSCRIPT_LIFELINE_FD);if(delete s.LMSCRIPT_LIFELINE_FD,e.env||delete process.env.LMSCRIPT_LIFELINE_FD,Number.isInteger($)&&$>2)try{if(AC($).isFIFO()||AC($).isSocket()){let K=new CX({fd:$,readable:!0,writable:!1});K.on("error",()=>{}),K.on("end",Vr),K.on("close",Vr),K.resume(),K.unref()}}catch{}}Y.signal=M.signal;try{let $=new Set(te.diagnostics.map(He=>JSON.stringify(He))),K=He=>{if(!(Fe!==void 0||!g))for(let dn of He.diagnostics)$.has(JSON.stringify(dn))||(c(Aa(dn,x)),$.add(JSON.stringify(dn)))};if(g){let He=await A.dryRunAsync(w,Y);return Fe!==void 0?(c(Aa({severity:"error",message:"Execution aborted",line:1,column:1},x)),Fe):(K(He),i(s_(He,_)+`
|
|
2443
|
+
`),Fe??He.exitCode)}Y.onPreflight=K;let ke=await A.runAsync(w,Y);for(let He of ke.diagnostics)$.has(JSON.stringify(He))||c(Aa(He,x));let Ca=He=>{let dn=l.findIndex(my=>my==="error: "+He||my==="error: "+He+`
|
|
2444
|
+
`);return dn<0?Number.MAX_SAFE_INTEGER:dn},Na=[...new Set(ke.errors??[])].filter(He=>!a.has(He)).sort((He,dn)=>Ca(He)-Ca(dn));if(Na.length){c(`
|
|
2445
2445
|
=== LMScript Error Summary (${Na.length} error${Na.length===1?"":"s"}) ===
|
|
2446
|
-
`);for(let[He,
|
|
2446
|
+
`);for(let[He,dn]of Na.entries())c(` ${He+1}. ${dn}
|
|
2447
2447
|
`);c(`==========================================
|
|
2448
2448
|
`)}let dy=Fe??(ke.exitCode!==void 0?ke.exitCode:ke.success&&!ke.errors?.length?0:1);return dy!==0&&Wt(),dy}catch($){return $?.code==="EPIPE"?Fe??0:(c(`error:${x}:1:1: ${$ instanceof Error?$.message:String($)}
|
|
2449
|
-
`),Wt(),Fe??1)}finally{Fe===void 0&&(clearTimeout(B),process.removeListener("SIGINT",gt),process.removeListener("SIGTERM",Vr),process.removeListener("SIGHUP",Ms));for(let $ of P)await $.close()}}var CC,cy,Bd=L(()=>{"use strict";gy();p_();E_();$s();CC=!1,cy="Usage: lmscript [--check|--dry-run|--lint] [--no-preflight] [--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...]"});Bd();async function
|
|
2449
|
+
`),Wt(),Fe??1)}finally{Fe===void 0&&(clearTimeout(B),process.removeListener("SIGINT",gt),process.removeListener("SIGTERM",Vr),process.removeListener("SIGHUP",Ms));for(let $ of P)await $.close()}}var CC,cy,Bd=L(()=>{"use strict";gy();p_();E_();$s();CC=!1,cy="Usage: lmscript [--check|--dry-run|--lint] [--no-preflight] [--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...]"});Bd();async function Lie(){process.exitCode=await uy(process.argv.slice(2))}export{Lie as main};
|