@lmctl-ai/lmctl 0.2.11 → 0.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +331 -331
- package/dist/cli/script.js +182 -182
- package/package.json +1 -1
package/dist/cli/script.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
var zd=Object.create;var to=Object.defineProperty;var Qd=Object.getOwnPropertyDescriptor;var Zd=Object.getOwnPropertyNames;var eu=Object.getPrototypeOf,tu=Object.prototype.hasOwnProperty;var ru=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var nu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zd(e))!tu.call(r,s)&&s!==t&&to(r,s,{get:()=>e[s],enumerable:!(n=Qd(e,s))||n.enumerable});return r};var ro=(r,e,t)=>(t=r!=null?zd(eu(r)):{},nu(e||!r||!r.__esModule?to(t,"default",{value:r,enumerable:!0}):t,r));var bs=ru(me=>{"use strict";function Qr(r){if(!Array.isArray(r))throw new TypeError("Each row and headers must be an array of cells");return Array.from(r,e=>{let t=e==null?"":String(e);if(/[\x00-\x1f\x7f-\x9f]/u.test(t))throw new TypeError("Cells must be single-line text without terminal control characters");return t})}function Mf(r){if(r===void 0)return[];if(!Array.isArray(r))throw new TypeError('align must be an array of "left" or "right" per column');return r.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function
|
|
2
|
-
`);return
|
|
1
|
+
var zd=Object.create;var to=Object.defineProperty;var Qd=Object.getOwnPropertyDescriptor;var Zd=Object.getOwnPropertyNames;var eu=Object.getPrototypeOf,tu=Object.prototype.hasOwnProperty;var ru=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var nu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zd(e))!tu.call(r,s)&&s!==t&&to(r,s,{get:()=>e[s],enumerable:!(n=Qd(e,s))||n.enumerable});return r};var ro=(r,e,t)=>(t=r!=null?zd(eu(r)):{},nu(e||!r||!r.__esModule?to(t,"default",{value:r,enumerable:!0}):t,r));var bs=ru(me=>{"use strict";function Qr(r){if(!Array.isArray(r))throw new TypeError("Each row and headers must be an array of cells");return Array.from(r,e=>{let t=e==null?"":String(e);if(/[\x00-\x1f\x7f-\x9f]/u.test(t))throw new TypeError("Cells must be single-line text without terminal control characters");return t})}function Mf(r){if(r===void 0)return[];if(!Array.isArray(r))throw new TypeError('align must be an array of "left" or "right" per column');return r.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function Je(r){let e=0;for(let t of r){let n=t.codePointAt(0);if(!(n>=768&&n<=879||n>=6832&&n<=6911||n>=7616&&n<=7679||n>=8400&&n<=8447||n>=65024&&n<=65039||n>=65056&&n<=65071||n===8203||n>=917760&&n<=917999)){if(n>=4352&&n<=4447||n>=11904&&n<=12350||n>=12353&&n<=13311||n>=13312&&n<=19903||n>=19968&&n<=40959||n>=40960&&n<=42191||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65072&&n<=65135||n>=65280&&n<=65376||n>=65504&&n<=65510||n>=9728&&n<=10175||n>=126976&&n<=129791||n>=131072&&n<=262141){e+=2;continue}e+=1}}return e}function ja(r,e,t){let n=" ".repeat(Math.max(0,e-Je(r)));return t?n+r:r+n}function Ff(r){if(Array.isArray(r))return{rows:r};if(r!==null&&typeof r=="object"&&Array.isArray(r.rows))return r;throw new TypeError("each grid must be a rows array or { rows, headers }")}function Pf(r){if(r===void 0)return"\u2026";if(typeof r!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(r))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return r}function Uf(r,e,t="\u2026"){if(Je(r)<=e)return r;let n=Je(t)>e?"\u2026":t,s=Je(n);if(e<=s)return n;let i="",o=0;for(let a of r){let l=Je(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function $f(r){if(r===void 0)return[];if(!Array.isArray(r))throw new TypeError("max must be an array of per-column width caps");return r.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 Wa(r,{max:e}={}){if(!Array.isArray(r))throw new TypeError("grids must be an array of grids");let t=$f(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of r){let o=Ff(i);o.headers!==void 0&&Qr(o.headers).forEach((a,l)=>{s(l,Je(a))});for(let a of o.rows.map(Qr))a.forEach((l,c)=>{s(c,Je(l))})}return n.map((i,o)=>{let a=t[o];return a===void 0?i:Math.min(i,a)})}me.measureColumns=Wa;function jf(r){if(r===void 0)return"";if(typeof r=="number"&&Number.isInteger(r)&&r>=0)return" ".repeat(r);if(typeof r=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(r))return r;throw new TypeError("margin must be a number of spaces or a single-line string")}function Ha(r,{widths:e,headers:t,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(r))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 c=jf(o),u=Mf(n),d=Pf(l),m=e??Wa([{rows:r,headers:t}],{max:a}),h=r.map(Qr);t!==void 0&&h.unshift(Qr(t));let f=h.map(T=>{let _=T.length-1;for(;_>=0&&T[_]==="";)_--;return T.slice(0,_+1).map((p,g)=>{let E=m[g]||0,w=s&&E>0&&(g!==_||i)?Uf(p,E,d):p;return u[g]==="right"?ja(w,E,!0):g===_?w:ja(w,E,!1)}).join(" ")}).join(`
|
|
2
|
+
`);return f===""||c===""?f:`${c}${f.split(`
|
|
3
3
|
`).join(`
|
|
4
4
|
${c}`)}`}me.renderGrid=Ha;function Xa(r,{headers:e,align:t,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a}={}){return Ha(r,{headers:e,align:t,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a})}function Bf(r,{headers:e,align:t,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,stream:l=process.stdout}={}){let c=Xa(r,{headers:e,align:t,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a});c&&l.write(`${c}
|
|
5
|
-
`)}me.formatTable=Xa;me.printTable=Bf;function Ba(r){return r instanceof Date?r.getTime():typeof r=="number"?r:typeof r=="string"&&r.trim()?Date.parse(r):NaN}function Wf(r,{now:e=Date.now()}={}){let t=Ba(e);if(!Number.isFinite(t))throw new TypeError("now must be a valid timestamp");let n=Ba(r);if(!Number.isFinite(n))return"unknown";let s=n-t,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":""}`}me.formatRelativeTime=Wf;function Hf(r){if(typeof r!="number"||!Number.isFinite(r))return"unknown";let e=r<0?"-":"",t=Math.abs(r);if(t<1e3)return String(r);let n=Math.round(t/1e3);return n<1e3?`${e}${n}K`:`${e}${(t/1e6).toFixed(1)}M`}me.formatCount=Hf;var As=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function Xf(r,{maxUnit:e="w",style:t="spaced"}={}){if(typeof r!="number"||!Number.isFinite(r))return"unknown";let n=As.findIndex(([a])=>a===e);if(n===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(t!=="spaced"&&t!=="compact")throw new TypeError('style must be "spaced" or "compact"');let s=Math.floor(Math.max(0,r)/1e3);if(t==="compact"){let a=As.slice(n).filter(([d])=>d!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,u=!1;for(let[d,
|
|
6
|
-
`?"\\n":t===" "?"\\t":t==="\r"?"\\r":`\\x${t.codePointAt(0).toString(16).padStart(2,"0")}`)}me.escapeCell=Kf});import{spawn as no,spawnSync as Qn}from"node:child_process";import{randomUUID as su}from"node:crypto";import{tmpdir as iu}from"node:os";import*as O from"node:fs";import*as se from"node:path";import*as uo from"node:readline";import{fileURLToPath as mo}from"node:url";var
|
|
5
|
+
`)}me.formatTable=Xa;me.printTable=Bf;function Ba(r){return r instanceof Date?r.getTime():typeof r=="number"?r:typeof r=="string"&&r.trim()?Date.parse(r):NaN}function Wf(r,{now:e=Date.now()}={}){let t=Ba(e);if(!Number.isFinite(t))throw new TypeError("now must be a valid timestamp");let n=Ba(r);if(!Number.isFinite(n))return"unknown";let s=n-t,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":""}`}me.formatRelativeTime=Wf;function Hf(r){if(typeof r!="number"||!Number.isFinite(r))return"unknown";let e=r<0?"-":"",t=Math.abs(r);if(t<1e3)return String(r);let n=Math.round(t/1e3);return n<1e3?`${e}${n}K`:`${e}${(t/1e6).toFixed(1)}M`}me.formatCount=Hf;var As=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function Xf(r,{maxUnit:e="w",style:t="spaced"}={}){if(typeof r!="number"||!Number.isFinite(r))return"unknown";let n=As.findIndex(([a])=>a===e);if(n===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(t!=="spaced"&&t!=="compact")throw new TypeError('style must be "spaced" or "compact"');let s=Math.floor(Math.max(0,r)/1e3);if(t==="compact"){let a=As.slice(n).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 h=Math.floor(c/m);if(c-=h*m,h>0&&!u){let f=d==="d"||d==="w"?`${h}${d}`:`${Le(h)}${d}`;l.push({text:f,zero:!1}),u=!0}else u&&l.push({text:`${Le(h)}${d}`,zero:h===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 As.slice(n))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(" ")}me.formatDuration=Xf;function qa(r){return r===void 0?new Date:r instanceof Date?r:typeof r=="number"||typeof r=="string"?new Date(r):new Date(NaN)}function Le(r){return String(r).padStart(2,"0")}function Ga(r){let e=qa(r);return Number.isNaN(e.getTime())?"unknown":`${Le(e.getHours())}:${Le(e.getMinutes())}:${Le(e.getSeconds())}`}me.formatClock=Ga;function qf(r){let e=qa(r);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${Le(e.getMonth()+1)}-${Le(e.getDate())}`} ${Ga(e)}`}me.formatLocalTimestamp=qf;function Gf(r){return typeof r=="number"&&Number.isFinite(r)?`${Math.round(r*100)}%`:"?%"}me.formatPercent=Gf;function Jf(r,{width:e=10,fill:t="#",empty:n=" ",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",t],["empty",n],["unknown",s]])if(typeof a!="string"||[...a].length!==1||/[\x00-\x1f\x7f-\x9f]/u.test(a)||Je(a)!==1)throw new TypeError(`${o} must be a single character with terminal display width 1`);if(typeof r!="number"||!Number.isFinite(r))return s.repeat(e);let i=Math.min(e,Math.max(0,Math.round(r*e)));return`${t.repeat(i)}${n.repeat(e-i)}`}me.formatBar=Jf;function Vf(r){if(typeof r!="number"||!Number.isFinite(r))return"unknown";let e=Math.floor(Math.max(0,r)/1e3),t=Math.floor(e/86400);e-=t*86400;let n=Math.floor(e/3600);e-=n*3600;let s=Math.floor(e/60);e-=s*60;let i=`${Le(n)}:${Le(s)}:${Le(e)}`;return t>0?`${t}d ${i}`:i}me.formatTimer=Vf;function Kf(r){return(r==null?"":String(r)).replace(/[\x00-\x1f\x7f-\x9f]/gu,t=>t===`
|
|
6
|
+
`?"\\n":t===" "?"\\t":t==="\r"?"\\r":`\\x${t.codePointAt(0).toString(16).padStart(2,"0")}`)}me.escapeCell=Kf});import{spawn as no,spawnSync as Qn}from"node:child_process";import{randomUUID as su}from"node:crypto";import{tmpdir as iu}from"node:os";import*as O from"node:fs";import*as se from"node:path";import*as uo from"node:readline";import{fileURLToPath as mo}from"node:url";var L=class extends Error{message;line;column;stage;file;constructor(e,t,n,s,i){let o=i&&i!=="<main>"?`${i}:${t}:${n}`:`${t}:${n}`;super(`[${s} Error at ${o}] ${e}`),this.name="LMScriptError",this.message=e,this.line=t,this.column=n,this.stage=s,this.file=i}},he=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};function fo(r,e){let t=r.file&&r.file!=="<main>"?`${r.file}:${r.line}:${r.column}`:`${r.line}:${r.column}`,n=e;if(r.file&&(!n||n&&r.file!=="<main>"&&r.file!=="<std>"))try{O.existsSync(r.file)&&O.statSync(r.file).isFile()&&(n=O.readFileSync(r.file,"utf-8"))}catch{}if(!n)return`[${r.severity.toUpperCase()} at ${t}] ${r.message}`;let s=n.split(`
|
|
7
7
|
`),i=String(r.line),o=r.line-1,a=s[o]??"",l=" | ",c=` ${i.padStart(4," ")} | `,u=" ".repeat(Math.max(0,r.column-1));return`[${r.severity.toUpperCase()} at ${t}] ${r.message}
|
|
8
8
|
`+l+`
|
|
9
9
|
${c}${a}
|
|
10
|
-
${l}${u}^`}function po(r){if(typeof r!="string"||r.length!==1||/["\r\n]/.test(r))throw new Error("CSV delimiter must be one character other than a quote or newline")}function
|
|
10
|
+
${l}${u}^`}function po(r){if(typeof r!="string"||r.length!==1||/["\r\n]/.test(r))throw new Error("CSV delimiter must be one character other than a quote or newline")}function Re(r,e){return r!=null&&Object.hasOwn(r,e)?r[e]:void 0}function Be(r,e,t){String(e)==="__proto__"?Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0}):r[e]=t}var Zn=10*1024*1024;function ho(r){if(typeof r!="string"||!r.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(r)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let t=`
|
|
11
11
|
const target = process.argv[1];
|
|
12
12
|
const maxBytes = ${Zn};
|
|
13
13
|
const controller = new AbortController();
|
|
@@ -35,30 +35,30 @@ try {
|
|
|
35
35
|
} finally {
|
|
36
36
|
clearTimeout(timer);
|
|
37
37
|
}
|
|
38
|
-
`,n=Qn(process.execPath,["--input-type=module","-e",t,r],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:Zn+4096,windowsHide:!0});if(n.error)throw n.error.code==="ETIMEDOUT"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${n.error.message}`);if(n.status!==0)throw new Error(`urlget() failed: ${String(n.stderr||"child process exited")}`.trim());return String(n.stdout||"")}async function ou(r){if(typeof r!="string"||!r.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(r)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),s;try{let i=await fetch(e.toString(),{method:"GET",redirect:"follow",signal:t.signal});if(!i.ok)throw t.abort(),new Error("HTTP "+i.status+" "+i.statusText);s=i.body?.getReader();let o=[],a=0;if(s)for(;;){let l=await s.read();if(l.done)break;if(a+=l.value.byteLength,a>Zn)throw await s.cancel().catch(()=>{}),t.abort(),new Error("response exceeds 10 MiB limit");o.push(l.value)}return Buffer.concat(o).toString("utf-8")}catch(i){if(t.abort(),s)try{await s.cancel().catch(()=>{})}catch{}throw i.name==="AbortError"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${i?.message||String(i)}`)}finally{clearTimeout(n)}}var Rr=new Set,Ar=1e3;process.on("exit",()=>{for(let r of Rr)try{process.platform!=="win32"&&r.pid?process.kill(-r.pid,"SIGKILL"):r.kill("SIGKILL")}catch{}Rr.clear()});function Nr(r,e,t,n=null,s=!1,i=0,o=null){return{stdout:r,stderr:e,code:t,signal:n,timed_out:s,duration_ms:i,pid:o}}function go(r){let e=String(r);return e.length>0&&/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function _o(r,e=6e4){if(!Number.isSafeInteger(e)||e<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");let t=performance.now(),n;if(Array.isArray(r)){if(r.length===0)throw new Error("system() argv array must not be empty");let u=String(r[0]),d=r.slice(1).map(String);n=Qn(u,d,{shell:!1,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"})}else n=Qn(r,{shell:!0,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"});let s=Math.max(0,Math.round(performance.now()-t)),i=typeof n.pid=="number"?n.pid:null;if(n.error){if(n.error.code==="ETIMEDOUT"){let u=n.stdout!=null?String(n.stdout):"",d=n.stderr!=null?String(n.stderr):"";return Nr(u,d,null,n.signal||"SIGKILL",!0,s,i)}throw n.error}let o=n.stdout!=null?String(n.stdout):"",a=n.stderr!=null?String(n.stderr):"",l=n.status!==null?n.status:null,c=n.signal!==null?String(n.signal):null;return Nr(o,a,l,c,!1,s,i)}function Eo(r,e=6e4){return new Promise((t,n)=>{if(!Number.isSafeInteger(e)||e<0){n(new Error("system() timeout must be a non-negative safe integer in milliseconds"));return}let s=performance.now();try{let i=process.platform!=="win32",o;if(Array.isArray(r)){if(r.length===0){n(new Error("system() argv array must not be empty"));return}let
|
|
38
|
+
`,n=Qn(process.execPath,["--input-type=module","-e",t,r],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:Zn+4096,windowsHide:!0});if(n.error)throw n.error.code==="ETIMEDOUT"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${n.error.message}`);if(n.status!==0)throw new Error(`urlget() failed: ${String(n.stderr||"child process exited")}`.trim());return String(n.stdout||"")}async function ou(r){if(typeof r!="string"||!r.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(r)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let t=new AbortController,n=setTimeout(()=>t.abort(),3e4),s;try{let i=await fetch(e.toString(),{method:"GET",redirect:"follow",signal:t.signal});if(!i.ok)throw t.abort(),new Error("HTTP "+i.status+" "+i.statusText);s=i.body?.getReader();let o=[],a=0;if(s)for(;;){let l=await s.read();if(l.done)break;if(a+=l.value.byteLength,a>Zn)throw await s.cancel().catch(()=>{}),t.abort(),new Error("response exceeds 10 MiB limit");o.push(l.value)}return Buffer.concat(o).toString("utf-8")}catch(i){if(t.abort(),s)try{await s.cancel().catch(()=>{})}catch{}throw i.name==="AbortError"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${i?.message||String(i)}`)}finally{clearTimeout(n)}}var Rr=new Set,Ar=1e3;process.on("exit",()=>{for(let r of Rr)try{process.platform!=="win32"&&r.pid?process.kill(-r.pid,"SIGKILL"):r.kill("SIGKILL")}catch{}Rr.clear()});function Nr(r,e,t,n=null,s=!1,i=0,o=null){return{stdout:r,stderr:e,code:t,signal:n,timed_out:s,duration_ms:i,pid:o}}function go(r){let e=String(r);return e.length>0&&/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function _o(r,e=6e4){if(!Number.isSafeInteger(e)||e<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");let t=performance.now(),n;if(Array.isArray(r)){if(r.length===0)throw new Error("system() argv array must not be empty");let u=String(r[0]),d=r.slice(1).map(String);n=Qn(u,d,{shell:!1,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"})}else n=Qn(r,{shell:!0,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"});let s=Math.max(0,Math.round(performance.now()-t)),i=typeof n.pid=="number"?n.pid:null;if(n.error){if(n.error.code==="ETIMEDOUT"){let u=n.stdout!=null?String(n.stdout):"",d=n.stderr!=null?String(n.stderr):"";return Nr(u,d,null,n.signal||"SIGKILL",!0,s,i)}throw n.error}let o=n.stdout!=null?String(n.stdout):"",a=n.stderr!=null?String(n.stderr):"",l=n.status!==null?n.status:null,c=n.signal!==null?String(n.signal):null;return Nr(o,a,l,c,!1,s,i)}function Eo(r,e=6e4){return new Promise((t,n)=>{if(!Number.isSafeInteger(e)||e<0){n(new Error("system() timeout must be a non-negative safe integer in milliseconds"));return}let s=performance.now();try{let i=process.platform!=="win32",o;if(Array.isArray(r)){if(r.length===0){n(new Error("system() argv array must not be empty"));return}let E=String(r[0]),w=r.slice(1).map(String);o=no(E,w,{shell:!1,detached:i,stdio:["ignore","pipe","pipe"]})}else o=no(r,{shell:!0,detached:i,stdio:["ignore","pipe","pipe"]});Rr.add(o);let a="",l="",c=null,u=null,d=0,m=!1,h=!1,f,T=!1,_,p=()=>{if(T)return;T=!0,Rr.delete(o),_&&clearTimeout(_);try{o.stdout?.destroy(),o.stderr?.destroy()}catch{}let E=Math.max(0,Math.round(performance.now()-s)),w=typeof o.pid=="number"?o.pid:null;if(f){n(f);return}if(h){t(Nr(a,l,null,u||"SIGKILL",!0,E,w));return}t(Nr(a,l,c,u,!1,E,w))};e>0&&(_=setTimeout(()=>{h=!0,u="SIGKILL";try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}p()},e));let g=10*1024*1024;o.stdout?.setEncoding("utf-8"),o.stderr?.setEncoding("utf-8"),o.stdout?.on("data",E=>{let w=Buffer.byteLength(E,"utf-8");if(d+w>g){if(!m){m=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
39
39
|
`)?`
|
|
40
|
-
`:"")+"system() output exceeds 10 MiB limit",
|
|
40
|
+
`:"")+"system() output exceeds 10 MiB limit",f=new Error("system() output exceeds 10 MiB limit"),p()}return}d+=w,a+=E}),o.stderr?.on("data",E=>{let w=Buffer.byteLength(E,"utf-8");if(d+w>g){if(!m){m=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
41
41
|
`)?`
|
|
42
|
-
`:"")+"system() output exceeds 10 MiB limit",
|
|
43
|
-
`)return t.endsWith("\r")&&(t=t.slice(0,-1)),t;t+=s}}catch{return null}}function qt(r,e=typeof process<"u"?process.stdin:null,t=typeof process<"u"?process.stdout:null){return new Promise(n=>{if(!e||typeof e.on!="function"){n(null);return}if(e.destroyed||e.readableEnded){n(null);return}if(e.isTTY===!1||typeof process<"u"&&e===process.stdin&&!process.stdin.isTTY){n(null);return}r!=null&&t&&typeof t.write=="function"&&t.write(String(r));let s=uo.createInterface({input:e,output:t,terminal:!!e.isTTY}),i=!1,o=()=>{s.close()};s.question("",a=>{i||(i=!0,o(),n(a))}),s.on("close",()=>{i||(i=!0,n(null))}),s.on("error",()=>{i||(i=!0,o(),n(null))})})}function so(r,e=!0,t=","){po(t);let n=[],s=[],i="",o=!1,a=!1,l=!1;for(let d=0;d<r.length;d++){let
|
|
44
|
-
`)throw new Error("Invalid CSV: unexpected character after closing quote");if(
|
|
45
|
-
`&&d++,s.push(i),n.push(s),s=[],i="",a=!1,l=!1):
|
|
46
|
-
`?(s.push(i),n.push(s),s=[],i="",a=!1,l=!1):i+=
|
|
47
|
-
`);if(typeof t=="object"&&t!==null){let n=Object.keys(t),s=n.map(o=>br(o,e)).join(e),i=r.map(o=>n.map(a=>br(
|
|
42
|
+
`:"")+"system() output exceeds 10 MiB limit",f=new Error("system() output exceeds 10 MiB limit"),p()}return}d+=w,l+=E}),o.on("error",E=>{f||(f=E)}),o.on("close",(E,w)=>{E!==null?(c=E,u=null):(c=null,u=w?String(w):null),p()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function au(r,e=null){if(typeof r!="string")return r??e;let t=r.trim();if(t.length===0)return e;try{return JSON.parse(t)}catch{}let n=t.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(n&&n[1])try{return JSON.parse(n[1].trim())}catch{}let s=t.indexOf("{"),i=t.lastIndexOf("}");if(s!==-1&&i>s)try{return JSON.parse(t.slice(s,i+1))}catch{}let o=t.indexOf("["),a=t.lastIndexOf("]");if(o!==-1&&a>o)try{return JSON.parse(t.slice(o,a+1))}catch{}return e}function Xt(r){if(typeof process>"u"||!process.stdin||!process.stdin.isTTY)return null;r!=null&&process.stdout&&typeof process.stdout.write=="function"&&process.stdout.write(String(r));try{let e=Buffer.alloc(1024),t="";for(;;){let n=0;try{n=O.readSync(0,e,0,1,null)}catch{return t.length>0?t:null}if(n===0)return t.length>0?t:null;let s=e.toString("utf-8",0,n);if(s===`
|
|
43
|
+
`)return t.endsWith("\r")&&(t=t.slice(0,-1)),t;t+=s}}catch{return null}}function qt(r,e=typeof process<"u"?process.stdin:null,t=typeof process<"u"?process.stdout:null){return new Promise(n=>{if(!e||typeof e.on!="function"){n(null);return}if(e.destroyed||e.readableEnded){n(null);return}if(e.isTTY===!1||typeof process<"u"&&e===process.stdin&&!process.stdin.isTTY){n(null);return}r!=null&&t&&typeof t.write=="function"&&t.write(String(r));let s=uo.createInterface({input:e,output:t,terminal:!!e.isTTY}),i=!1,o=()=>{s.close()};s.question("",a=>{i||(i=!0,o(),n(a))}),s.on("close",()=>{i||(i=!0,n(null))}),s.on("error",()=>{i||(i=!0,o(),n(null))})})}function so(r,e=!0,t=","){po(t);let n=[],s=[],i="",o=!1,a=!1,l=!1;for(let d=0;d<r.length;d++){let m=r[d],h=r[d+1];if(l=!0,o)m==='"'?h==='"'?(i+='"',d++):(o=!1,a=!0):i+=m;else{if(a&&m!==t&&m!=="\r"&&m!==`
|
|
44
|
+
`)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===t?(a=!1,s.push(i),i=""):m==="\r"?(h===`
|
|
45
|
+
`&&d++,s.push(i),n.push(s),s=[],i="",a=!1,l=!1):m===`
|
|
46
|
+
`?(s.push(i),n.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),n.push(s)),!e)return n.map(d=>d.map(io));if(n.length===0)return[];let c=n[0].map(d=>d.trim()),u=[];for(let d=1;d<n.length;d++){let m=n[d],h={};for(let f=0;f<c.length;f++)Be(h,c[f],f<m.length?io(m[f]):null);u.push(h)}return u}function io(r){let e=r.trim();if(e==="")return"";if(/^-?\d+$/.test(e)){let t=Number(e);if(!Number.isNaN(t))return t}if(/^-?\d+\.\d+$/.test(e)){let t=Number(e);if(!Number.isNaN(t))return t}return e.toLowerCase()==="true"?!0:e.toLowerCase()==="false"?!1:e.toLowerCase()==="null"?null:r}function oo(r,e=","){if(po(e),!Array.isArray(r)||r.length===0)return"";let t=r[0];if(Array.isArray(t))return r.map(n=>n.map(s=>br(s,e)).join(e)).join(`
|
|
47
|
+
`);if(typeof t=="object"&&t!==null){let n=Object.keys(t),s=n.map(o=>br(o,e)).join(e),i=r.map(o=>n.map(a=>br(Re(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
48
48
|
`)}return r.map(n=>br(n,e)).join(`
|
|
49
49
|
`)}function br(r,e){let t=r==null?"":String(r);return t===""||t.includes(e)||t.includes('"')||t.includes(`
|
|
50
|
-
`)||t.includes("\r")?`"${t.replaceAll('"','""')}"`:t}var ao={fn:"FN",function:"FN",let:"LET",if:"IF",else:"ELSE",while:"WHILE",for:"FOR",return:"RETURN",break:"BREAK",continue:"CONTINUE",true:"TRUE",false:"FALSE",null:"NULL",parallel:"PARALLEL",sync:"SYNC",import:"IMPORT"},Bt=class{source;length;file;pos=0;line=1;column=1;constructor(e,t){this.source=e,this.length=e.length,this.file=t}tokenize(){let e=[];for(;this.pos<this.length&&(this.skipWhitespaceAndComments(),!(this.pos>=this.length));){let t=this.line,n=this.column,s=this.peek();if(this.isDigit(s)||s==="."&&this.isDigit(this.peekNext())){e.push(this.readNumber(t,n));continue}if(s==='"'||s==="'"){e.push(this.readString(s,t,n));continue}if(s==="<"&&this.peekNext()==="<"){let i=this.tryReadHeredoc(t,n);if(i){e.push(i);continue}}if(this.isAlpha(s)){e.push(this.readIdentifier(t,n));continue}switch(this.advance(),s){case".":e.push({type:"DOT",value:".",line:t,column:n});break;case":":e.push({type:"COLON",value:":",line:t,column:n});break;case"(":e.push({type:"LPAREN",value:"(",line:t,column:n});break;case")":e.push({type:"RPAREN",value:")",line:t,column:n});break;case"{":e.push({type:"LBRACE",value:"{",line:t,column:n});break;case"}":e.push({type:"RBRACE",value:"}",line:t,column:n});break;case"[":e.push({type:"LBRACKET",value:"[",line:t,column:n});break;case"]":e.push({type:"RBRACKET",value:"]",line:t,column:n});break;case",":e.push({type:"COMMA",value:",",line:t,column:n});break;case";":e.push({type:"SEMICOLON",value:";",line:t,column:n});break;case"+":e.push({type:"PLUS",value:"+",line:t,column:n});break;case"-":e.push({type:"MINUS",value:"-",line:t,column:n});break;case"*":e.push({type:"STAR",value:"*",line:t,column:n});break;case"/":e.push({type:"SLASH",value:"/",line:t,column:n});break;case"%":e.push({type:"PERCENT",value:"%",line:t,column:n});break;case"=":this.match("=")?e.push({type:"EQUAL",value:"==",line:t,column:n}):e.push({type:"ASSIGN",value:"=",line:t,column:n});break;case"!":this.match("=")?e.push({type:"NOT_EQUAL",value:"!=",line:t,column:n}):e.push({type:"NOT",value:"!",line:t,column:n});break;case"<":this.match("=")?e.push({type:"LESS_EQUAL",value:"<=",line:t,column:n}):e.push({type:"LESS",value:"<",line:t,column:n});break;case">":this.match("=")?e.push({type:"GREATER_EQUAL",value:">=",line:t,column:n}):e.push({type:"GREATER",value:">",line:t,column:n});break;case"&":if(this.match("&"))e.push({type:"AND",value:"&&",line:t,column:n});else throw new
|
|
50
|
+
`)||t.includes("\r")?`"${t.replaceAll('"','""')}"`:t}var ao={fn:"FN",function:"FN",let:"LET",if:"IF",else:"ELSE",while:"WHILE",for:"FOR",return:"RETURN",break:"BREAK",continue:"CONTINUE",true:"TRUE",false:"FALSE",null:"NULL",parallel:"PARALLEL",sync:"SYNC",import:"IMPORT"},Bt=class{source;length;file;pos=0;line=1;column=1;constructor(e,t){this.source=e,this.length=e.length,this.file=t}tokenize(){let e=[];for(;this.pos<this.length&&(this.skipWhitespaceAndComments(),!(this.pos>=this.length));){let t=this.line,n=this.column,s=this.peek();if(this.isDigit(s)||s==="."&&this.isDigit(this.peekNext())){e.push(this.readNumber(t,n));continue}if(s==='"'||s==="'"){e.push(this.readString(s,t,n));continue}if(s==="<"&&this.peekNext()==="<"){let i=this.tryReadHeredoc(t,n);if(i){e.push(i);continue}}if(this.isAlpha(s)){e.push(this.readIdentifier(t,n));continue}switch(this.advance(),s){case".":e.push({type:"DOT",value:".",line:t,column:n});break;case":":e.push({type:"COLON",value:":",line:t,column:n});break;case"(":e.push({type:"LPAREN",value:"(",line:t,column:n});break;case")":e.push({type:"RPAREN",value:")",line:t,column:n});break;case"{":e.push({type:"LBRACE",value:"{",line:t,column:n});break;case"}":e.push({type:"RBRACE",value:"}",line:t,column:n});break;case"[":e.push({type:"LBRACKET",value:"[",line:t,column:n});break;case"]":e.push({type:"RBRACKET",value:"]",line:t,column:n});break;case",":e.push({type:"COMMA",value:",",line:t,column:n});break;case";":e.push({type:"SEMICOLON",value:";",line:t,column:n});break;case"+":e.push({type:"PLUS",value:"+",line:t,column:n});break;case"-":e.push({type:"MINUS",value:"-",line:t,column:n});break;case"*":e.push({type:"STAR",value:"*",line:t,column:n});break;case"/":e.push({type:"SLASH",value:"/",line:t,column:n});break;case"%":e.push({type:"PERCENT",value:"%",line:t,column:n});break;case"=":this.match("=")?e.push({type:"EQUAL",value:"==",line:t,column:n}):e.push({type:"ASSIGN",value:"=",line:t,column:n});break;case"!":this.match("=")?e.push({type:"NOT_EQUAL",value:"!=",line:t,column:n}):e.push({type:"NOT",value:"!",line:t,column:n});break;case"<":this.match("=")?e.push({type:"LESS_EQUAL",value:"<=",line:t,column:n}):e.push({type:"LESS",value:"<",line:t,column:n});break;case">":this.match("=")?e.push({type:"GREATER_EQUAL",value:">=",line:t,column:n}):e.push({type:"GREATER",value:">",line:t,column:n});break;case"&":if(this.match("&"))e.push({type:"AND",value:"&&",line:t,column:n});else throw new L("Unexpected character '&'. Did you mean '&&'?",t,n,"LEXER",this.file);break;case"|":if(this.match("|"))e.push({type:"OR",value:"||",line:t,column:n});else throw new L("Unexpected character '|'. Did you mean '||'?",t,n,"LEXER",this.file);break;default:throw new L(`Unexpected character: '${s}'`,t,n,"LEXER",this.file)}}return e.push({type:"EOF",value:"",line:this.line,column:this.column}),e}peek(){return this.source[this.pos]||""}peekNext(){return this.source[this.pos+1]||""}advance(){let e=this.source[this.pos++];return e===`
|
|
51
51
|
`?(this.line++,this.column=1):this.column++,e}match(e){return this.pos>=this.length||this.source[this.pos]!==e?!1:(this.advance(),!0)}isDigit(e){return e>="0"&&e<="9"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}skipWhitespaceAndComments(){for(;this.pos<this.length;){let e=this.peek();if(e===" "||e===" "||e==="\r"||e===`
|
|
52
52
|
`)this.advance();else if(e==="/"&&this.peekNext()==="/"||e==="#")for(;this.pos<this.length&&this.peek()!==`
|
|
53
|
-
`;)this.advance();else if(e==="/"&&this.peekNext()==="*"){let t=this.line,n=this.column;this.advance(),this.advance();let s=!1;for(;this.pos<this.length;){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance(),s=!0;break}this.advance()}if(!s)throw new
|
|
54
|
-
`)throw new
|
|
55
|
-
`;break;case"t":s+=" ";break;case"r":s+="\r";break;case"\\":s+="\\";break;case'"':s+='"';break;case"'":s+="'";break;default:s+=i;break}}else s+=this.advance()}if(this.pos>=this.length)throw new
|
|
53
|
+
`;)this.advance();else if(e==="/"&&this.peekNext()==="*"){let t=this.line,n=this.column;this.advance(),this.advance();let s=!1;for(;this.pos<this.length;){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance(),s=!0;break}this.advance()}if(!s)throw new L("Unterminated block comment",t,n,"LEXER",this.file)}else break}}readNumber(e,t){let n="";for(;this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(n+=this.advance();this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();return{type:"NUMBER",value:n,literal:parseFloat(n),line:e,column:t}}readString(e,t,n){this.advance();let s="";for(;this.pos<this.length&&this.peek()!==e;){if(this.peek()===`
|
|
54
|
+
`)throw new L("Unterminated string literal across newline",t,n,"LEXER",this.file);if(this.peek()==="\\"){this.advance();let i=this.advance();switch(i){case"n":s+=`
|
|
55
|
+
`;break;case"t":s+=" ";break;case"r":s+="\r";break;case"\\":s+="\\";break;case'"':s+='"';break;case"'":s+="'";break;default:s+=i;break}}else s+=this.advance()}if(this.pos>=this.length)throw new L("Unterminated string literal at end of file",t,n,"LEXER",this.file);return this.advance(),{type:"STRING",value:s,literal:s,line:t,column:n}}tryReadHeredoc(e,t){let n=this.pos+2;if(!this.isAlpha(this.source[n]))return;for(n++;n<this.length&&this.isAlphaNumeric(this.source[n]);)n++;let s=this.source.slice(this.pos+2,n),i=this.source[n]==="\r"&&this.source[n+1]===`
|
|
56
56
|
`?2:this.source[n]===`
|
|
57
57
|
`?1:0;if(i===0)return;let o=n+i-this.pos;for(let l=0;l<o;l++)this.advance();let a=this.pos;for(;this.pos<this.length;){let l=this.pos,c=this.pos;for(;c<this.length&&this.source[c]!=="\r"&&this.source[c]!==`
|
|
58
|
-
`;)c++;let u=this.source.slice(l,c),d=u===`${s};`;if(u===s||d){let
|
|
58
|
+
`;)c++;let u=this.source.slice(l,c),d=u===`${s};`;if(u===s||d){let f=this.source[c]==="\r"&&this.source[c+1]===`
|
|
59
59
|
`?2:this.source[c]===`
|
|
60
|
-
`||this.source[c]==="\r"?1:0,
|
|
61
|
-
`?2:c<this.length?1:0,m=c+p-this.pos;for(let h=0;h<m;h++)this.advance()}throw new k(`Unterminated heredoc; expected closing marker '${s}'`,e,t,"LEXER",this.file)}readIdentifier(e,t){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(ao,n)?ao[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:t}}return{type:"IDENTIFIER",value:n,line:e,column:t}}};function es(r,e){if(!(!r||typeof r!="object")){"line"in r&&"column"in r&&!r.file&&(r.file=e);for(let t of Object.keys(r)){let n=r[t];if(Array.isArray(n))for(let s of n)es(s,e);else n&&typeof n=="object"&&es(n,e)}}}var Wt=class{tokens;current=0;file;constructor(e,t){this.tokens=e,this.file=t}parse(){let e=[],t=this.peek();for(;!this.isAtEnd();)e.push(this.parseDeclaration(!0));let n={kind:"Program",statements:e,line:t.line,column:t.column,file:this.file};return this.file&&es(n,this.file),n}parseDeclaration(e=!1){try{if(this.match("FN"))return this.parseFunctionDecl();if(this.match("LET"))return this.parseVarDecl();if(this.match("IMPORT")){if(!e)throw new k("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.parseImportStmt()}return this.parseStatement()}catch(t){throw t instanceof k?t:new k(t instanceof Error?t.message:String(t),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),t=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:t.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),t=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:t.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let t=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:t.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new k("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.match("SYNC")?this.parseSyncStatement():this.match("IF")?this.parseIfStatement():this.match("WHILE")?this.parseWhileStatement():this.match("FOR")?this.parseForStatement():this.match("RETURN")?this.parseReturnStatement():this.match("BREAK")?this.parseBreakStatement():this.match("CONTINUE")?this.parseContinueStatement():this.match("LBRACE")?this.parseBlockBody(this.previous()):this.parseExpressionStatement()}parseSyncStatement(){let e=this.previous(),t=this.parseExpression();if(this.consumeOptionalSemicolon(),t.kind==="AssignExpr")return{kind:"SyncAssignStmt",target:t.target,value:t.value,line:e.line,column:e.column};if(t.kind==="IndexAssignExpr")return{kind:"SyncIndexAssignStmt",target:t.target,index:t.index,value:t.value,line:e.line,column:e.column};if(t.kind==="CallExpr")return{kind:"SyncCallStmt",call:t,line:e.line,column:e.column};throw new k("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let t=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:t,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let t=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:t,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let t;if(this.match("SEMICOLON"))t=void 0;else if(this.match("LET"))t=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),t={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:t,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),t;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(t=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:t,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let t=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)t.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:t,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let t=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:t.line,column:t.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:t.line,column:t.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new k("Destructuring assignment target must be an identifier",i.line,i.column,"PARSER",this.file);s.push(i.name)}return{kind:"TupleAssignExpr",targets:s,value:n,line:t.line,column:t.column}}throw new k("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let t=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:t.line,column:t.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let t=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:t.line,column:t.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let t=this.previous(),n=t.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let t=this.previous(),n=t.type==="LESS"?"<":t.type==="LESS_EQUAL"?"<=":t.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let t=this.previous(),n=t.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let t=this.previous(),n=t.type==="STAR"?"*":t.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),t=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:t,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new k("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let t=[];if(!this.check("RPAREN"))do t.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:t,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let t=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:t,line:e.line,column:e.column}}else if(this.match("DOT")){let t=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:t.value,line:t.line,column:t.column},line:t.line,column:t.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let t=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new k("Each task in parallel([...]) must be a direct function call expression",s.line,s.column,"PARSER",this.file);n.push(s)}while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' closing array in 'parallel([ ... ])'"),this.consume("RPAREN","Expected ')' closing 'parallel(...)'"),{kind:"ParallelExpr",tasks:n,line:t.line,column:t.column}}if(this.match("IDENTIFIER"))return{kind:"IdentifierExpr",name:this.previous().value,line:e.line,column:e.column};if(this.match("LPAREN")){let t=this.previous(),n=[],s=!1;if(!this.check("RPAREN"))do if(n.push(this.parseExpression()),this.match("COMMA"))s=!0;else break;while(!this.check("RPAREN")&&!this.isAtEnd());return this.consume("RPAREN","Expected ')' after expression"),n.length===1&&!s?{kind:"GroupingExpr",expression:n[0],line:t.line,column:t.column}:{kind:"TupleExpr",elements:n,line:t.line,column:t.column}}if(this.match("LBRACKET")){let t=[];if(!this.check("RBRACKET"))do t.push(this.parseExpression());while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' after array elements"),{kind:"ArrayExpr",elements:t,line:e.line,column:e.column}}if(this.match("LBRACE")){let t=this.previous(),n=[];if(!this.check("RBRACE"))do{let s="";if(this.match("IDENTIFIER","STRING"))s=this.previous().value;else throw new k("Expected object key (identifier or string)",this.peek().line,this.peek().column,"PARSER",this.file);this.consume("COLON","Expected ':' after object key");let i=this.parseExpression();n.push({key:s,value:i})}while(this.match("COMMA"));return this.consume("RBRACE","Expected '}' after object literal"),{kind:"ObjectExpr",properties:n,line:t.line,column:t.column}}throw new k(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let t of e)if(this.check(t))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,t){if(this.check(e))return this.advance();let n=this.peek();throw new k(t,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},lu=`# LMScript Standard Library (std.lms)
|
|
60
|
+
`||this.source[c]==="\r"?1:0,T=this.source.slice(a,l),p=s.length+(d?0:f);for(let g=0;g<p;g++)this.advance();return{type:"STRING",value:T,literal:T,line:e,column:t}}let m=this.source[c]==="\r"&&this.source[c+1]===`
|
|
61
|
+
`?2:c<this.length?1:0,h=c+m-this.pos;for(let f=0;f<h;f++)this.advance()}throw new L(`Unterminated heredoc; expected closing marker '${s}'`,e,t,"LEXER",this.file)}readIdentifier(e,t){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(ao,n)?ao[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:t}}return{type:"IDENTIFIER",value:n,line:e,column:t}}};function es(r,e){if(!(!r||typeof r!="object")){"line"in r&&"column"in r&&!r.file&&(r.file=e);for(let t of Object.keys(r)){let n=r[t];if(Array.isArray(n))for(let s of n)es(s,e);else n&&typeof n=="object"&&es(n,e)}}}var Wt=class{tokens;current=0;file;constructor(e,t){this.tokens=e,this.file=t}parse(){let e=[],t=this.peek();for(;!this.isAtEnd();)e.push(this.parseDeclaration(!0));let n={kind:"Program",statements:e,line:t.line,column:t.column,file:this.file};return this.file&&es(n,this.file),n}parseDeclaration(e=!1){try{if(this.match("FN"))return this.parseFunctionDecl();if(this.match("LET"))return this.parseVarDecl();if(this.match("IMPORT")){if(!e)throw new L("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.parseImportStmt()}return this.parseStatement()}catch(t){throw t instanceof L?t:new L(t instanceof Error?t.message:String(t),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),t=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:t.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),t=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:t.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let t=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:t.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new L("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.match("SYNC")?this.parseSyncStatement():this.match("IF")?this.parseIfStatement():this.match("WHILE")?this.parseWhileStatement():this.match("FOR")?this.parseForStatement():this.match("RETURN")?this.parseReturnStatement():this.match("BREAK")?this.parseBreakStatement():this.match("CONTINUE")?this.parseContinueStatement():this.match("LBRACE")?this.parseBlockBody(this.previous()):this.parseExpressionStatement()}parseSyncStatement(){let e=this.previous(),t=this.parseExpression();if(this.consumeOptionalSemicolon(),t.kind==="AssignExpr")return{kind:"SyncAssignStmt",target:t.target,value:t.value,line:e.line,column:e.column};if(t.kind==="IndexAssignExpr")return{kind:"SyncIndexAssignStmt",target:t.target,index:t.index,value:t.value,line:e.line,column:e.column};if(t.kind==="CallExpr")return{kind:"SyncCallStmt",call:t,line:e.line,column:e.column};throw new L("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let t=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:t,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let t=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:t,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let t;if(this.match("SEMICOLON"))t=void 0;else if(this.match("LET"))t=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),t={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:t,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),t;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(t=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:t,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let t=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)t.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:t,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let t=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:t.line,column:t.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:t.line,column:t.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new L("Destructuring assignment target must be an identifier",i.line,i.column,"PARSER",this.file);s.push(i.name)}return{kind:"TupleAssignExpr",targets:s,value:n,line:t.line,column:t.column}}throw new L("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let t=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:t.line,column:t.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let t=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:t.line,column:t.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let t=this.previous(),n=t.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let t=this.previous(),n=t.type==="LESS"?"<":t.type==="LESS_EQUAL"?"<=":t.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let t=this.previous(),n=t.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let t=this.previous(),n=t.type==="STAR"?"*":t.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:t.line,column:t.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),t=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:t,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new L("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let t=[];if(!this.check("RPAREN"))do t.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:t,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let t=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:t,line:e.line,column:e.column}}else if(this.match("DOT")){let t=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:t.value,line:t.line,column:t.column},line:t.line,column:t.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let t=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new L("Each task in parallel([...]) must be a direct function call expression",s.line,s.column,"PARSER",this.file);n.push(s)}while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' closing array in 'parallel([ ... ])'"),this.consume("RPAREN","Expected ')' closing 'parallel(...)'"),{kind:"ParallelExpr",tasks:n,line:t.line,column:t.column}}if(this.match("IDENTIFIER"))return{kind:"IdentifierExpr",name:this.previous().value,line:e.line,column:e.column};if(this.match("LPAREN")){let t=this.previous(),n=[],s=!1;if(!this.check("RPAREN"))do if(n.push(this.parseExpression()),this.match("COMMA"))s=!0;else break;while(!this.check("RPAREN")&&!this.isAtEnd());return this.consume("RPAREN","Expected ')' after expression"),n.length===1&&!s?{kind:"GroupingExpr",expression:n[0],line:t.line,column:t.column}:{kind:"TupleExpr",elements:n,line:t.line,column:t.column}}if(this.match("LBRACKET")){let t=[];if(!this.check("RBRACKET"))do t.push(this.parseExpression());while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' after array elements"),{kind:"ArrayExpr",elements:t,line:e.line,column:e.column}}if(this.match("LBRACE")){let t=this.previous(),n=[];if(!this.check("RBRACE"))do{let s="";if(this.match("IDENTIFIER","STRING"))s=this.previous().value;else throw new L("Expected object key (identifier or string)",this.peek().line,this.peek().column,"PARSER",this.file);this.consume("COLON","Expected ':' after object key");let i=this.parseExpression();n.push({key:s,value:i})}while(this.match("COMMA"));return this.consume("RBRACE","Expected '}' after object literal"),{kind:"ObjectExpr",properties:n,line:t.line,column:t.column}}throw new L(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let t of e)if(this.check(t))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,t){if(this.check(e))return this.advance();let n=this.peek();throw new L(t,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},lu=`# LMScript Standard Library (std.lms)
|
|
62
62
|
|
|
63
63
|
# String Utilities
|
|
64
64
|
fn is_blank(s) {
|
|
@@ -153,21 +153,21 @@ fn clamp(val, low, high) {
|
|
|
153
153
|
}
|
|
154
154
|
return val;
|
|
155
155
|
}
|
|
156
|
-
`,zn=null;function cu(){if(!zn){let e=new Bt(lu,"<std>").tokenize(),n=new Wt(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);zn=n}return{kind:"Program",statements:[...zn.statements],line:1,column:1,file:"<std>"}}function du(r,e={}){let t=e.file||"<main>",n=e.baseDir||(e.file?se.dirname(se.resolve(e.file)):process.cwd()),s=new Map,i=new Set;function o(T,f){if(e.moduleResolver)return e.moduleResolver(T,f).path;let E=n;f&&f!=="<main>"&&f!=="<std>"&&(E=se.dirname(f));let y=se.resolve(E,T);try{return O.realpathSync(y)}catch{return y}}function a(T,f){let E,y;if(e.moduleResolver){let S=e.moduleResolver(T,f);E=S.path,y=S.source}else{if(E=o(T,f),s.has(E))return s.get(E);if(i.has(E))return{kind:"Program",statements:[],line:1,column:1,file:E};try{y=O.readFileSync(E,"utf-8")}catch(S){throw new k(`Cannot resolve import '${T}': ${S?.message||String(S)}`,1,1,"PARSER",f)}}if(s.has(E))return s.get(E);if(i.has(E))return{kind:"Program",statements:[],line:1,column:1,file:E};i.add(E);let w=new Bt(y,E).tokenize(),v=new Wt(w,E).parse();for(let S of v.statements)if(S.kind!=="FunctionDeclStmt"&&S.kind!=="ImportStmt")throw new k(`Library '${E}' cannot contain top-level executable statements; libraries must only declare functions. Found '${S.kind}'.`,S.line,S.column,"CHECKER",E);for(let S of v.statements)S.kind==="ImportStmt"&&a(S.path,E);return i.delete(E),s.set(E,v),v}let c=new Bt(r,t).tokenize(),d=new Wt(c,t).parse(),p=t!=="<main>"?o(t):"<main>";s.set(p,d);for(let T of d.statements)T.kind==="ImportStmt"&&a(T.path,t);let m=[];if(!e.noStdlib){let T=cu();for(let f of T.statements)f.kind==="FunctionDeclStmt"&&m.push(f)}for(let[T,f]of s.entries())if(T!==p)for(let E of f.statements)E.kind==="FunctionDeclStmt"&&m.push(E);for(let T of d.statements)T.kind!=="ImportStmt"&&m.push(T);let h={kind:"Program",statements:m,line:d.line,column:d.column,file:t},g=Array.from(s.keys());return{program:h,loadedFiles:g}}var rt=class{variables=new Set;parent;constructor(e){this.parent=e}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}},ts=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new rt;loopDepth=0;inFunction=!1;hasConcurrency=!1;constructor(e,t={}){this.options=t;for(let[n,s]of e.entries())this.hostFunctions.set(n,s),this.functions.set(n,{name:n,paramCount:typeof s.arity=="number"?s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.loopDepth=0,this.inFunction=!1,this.currentScope=new rt,this.options.globals)for(let t of this.options.globals)this.currentScope.define(t);this.functions.clear();for(let[t,n]of this.hostFunctions.entries())this.functions.set(t,{name:t,paramCount:typeof n.arity=="number"?n.arity:-1,params:[],isHost:!0,line:0,column:0});for(let t of e.statements)t.kind==="FunctionDeclStmt"&&this.collectFunction(t);for(let t of e.statements)this.checkStmt(t);return this.diagnostics}addError(e,t,n,s){this.diagnostics.push({message:e,line:t,column:n,severity:"error",file:s})}collectFunction(e){if(this.functions.has(e.name)){let n=this.functions.get(e.name);if(n.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(n.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=n.file?`${n.file}:${n.line}`:`line ${n.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let t=new Set;for(let n of e.params)t.has(n)&&this.addError(`Duplicate parameter name '${n}' in function '${e.name}'`,e.line,e.column,e.file),t.add(n);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"ImportStmt":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 t=this.currentScope,n=this.inFunction;this.inFunction=!0,this.currentScope=new rt(t);for(let s of e.params)this.currentScope.define(s);for(let s of e.body.statements)this.checkStmt(s);this.inFunction=n,this.currentScope=t;break}case"VarDeclStmt":{this.currentScope.hasInCurrent(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),this.currentScope.define(e.name);break}case"TupleVarDeclStmt":{this.checkExpr(e.initializer);for(let t of e.names)this.currentScope.hasInCurrent(t)&&this.addError(`Variable '${t}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(t);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"ForStmt":{let t=this.currentScope;this.currentScope=new rt(t),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),e.update&&this.checkExpr(e.update),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,this.currentScope=t;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);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 t=this.currentScope;this.currentScope=new rt(t);for(let n of e.statements)this.checkStmt(n);this.currentScope=t;break}case"SyncAssignStmt":{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);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 t=e.call;t.args.length===0&&this.addError(`Synchronized call '${t.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let n=this.hostFunctions.get(t.callee);(!n||!n.isContainerMutation)&&this.addError(`Synchronized call '${t.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);break}}}checkReadPath(e){let t=e.args[0];for(;t.kind==="GroupingExpr";)t=t.expression;if(t.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 t.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!O.statSync(t.value).isFile())throw new Error("path is not a regular file");O.accessSync(t.value,O.constants.R_OK)}catch(n){this.addError(`Cannot read file ${JSON.stringify(t.value)}: ${n instanceof Error?n.message:String(n)}`,e.line,e.column,e.file)}}checkExpr(e){switch(e.kind){case"LiteralExpr":break;case"IdentifierExpr":{!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.checkExpr(e.value),this.currentScope.resolve(e.target)||this.currentScope.define(e.target);break}case"TupleAssignExpr":{this.checkExpr(e.value);for(let t of e.targets)this.currentScope.resolve(t)||this.currentScope.define(t);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let t of e.elements)this.checkExpr(t);break}case"ArrayExpr":{for(let t of e.elements)this.checkExpr(t);break}case"ObjectExpr":{for(let t of e.properties)this.checkExpr(t.value);break}case"IndexExpr":{this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let t of e.tasks)this.checkExpr(t);break}case"CallExpr":{let t=this.functions.get(e.callee);t?t.paramCount>=0&&e.args.length!==t.paramCount&&this.addError(`Function '${e.callee}' expects ${t.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(`Call to undefined function '${e.callee}'`,e.line,e.column,e.file);let n=this.hostFunctions.get(e.callee),s=n?.arity;typeof s=="object"&&(e.args.length<s.min||e.args.length>(s.max??1/0))&&this.addError(`Function '${e.callee}' expects ${s.min}..${s.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),this.options.checkFiles&&n?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let i of e.args)this.checkExpr(i);break}}}},yt=class{value;constructor(e){this.value=e}},Ue=class{},$e=class{},Tt=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Ie=class r{static nextId=1;id=r.nextId++;values=new Map;parent;isFunctionBoundary;constructor(e,t=!1){this.parent=e,this.isFunctionBoundary=t}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,t){this.values.set(e,t)}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)}set(e,t){if(this.values.has(e)){this.values.set(e,t);return}if(!this.isFunctionBoundary&&this.parent?.has(e)){this.parent.set(e,t);return}this.values.set(e,t)}},kr=class{holderTaskId;depth=0;waiters=[];acquire(e=0,t=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((n,s)=>{let i;t>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 ${t}ms (possible deadlock)`)))},t));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,n()};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,t=0,n=1e4){await this.acquire(t,n);try{return await e()}finally{this.release()}}},rs=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let t=this.bindingLocks.get(e);return t||(t=new kr,this.bindingLocks.set(e,t)),t}getObjectLock(e){let t=this.objectLocks.get(e);return t||(t=new kr,this.objectLocks.set(e,t)),t}},Lr=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new rs;isAsync;nextTaskId=1;initialGlobals;callDepth=0;asyncCallDepth=new Map;recordedErrors=[];constructor(e,t=o=>console.log(o),n=!1,s,i){this.stdout=t,this.stderr=i,this.isAsync=n,this.initialGlobals=s,this.globalEnv=new Ie,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(...T)=>{let f=T.map(E=>typeof E=="object"?JSON.stringify(E):String(E)).join(" ");return this.stdout(f),f},description:"Prints formatted values to output log",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(...T)=>{let f=T.map(E=>typeof E=="object"?JSON.stringify(E):String(E)).join(" ");return this.stdout(f),f},description:"Prints line to output log",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(T,...f)=>{let E=Ht(T,f);return this.stdout(E),E},description:"Formats a template using %s/%d/%f/%% substitution and prints it",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(...T)=>{let f=T.map(E=>typeof E=="object"?JSON.stringify(E):String(E)).join(" ");return this.stderr?this.stderr(`error: ${f}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${f}
|
|
157
|
-
`):console.error(`error: ${
|
|
158
|
-
`)+(
|
|
159
|
-
`:""),S=
|
|
160
|
-
`)+(
|
|
161
|
-
`:""),S=_.exitCode!==void 0?_.exitCode:_.success?0:1,x={success:_.success&&S===0,stdout:v,output:[..._.output],value:_.value,exit_code:S,code:S,errors:_.errors??[]};return x.toString=()=>v,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let h=e.get("urlget");(!h||h.isDefault)&&this.hostFunctions.set("urlget",{fn:T=>this.isAsync?ou(T):ho(T),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let g=e.get("sleep");(!g||g.isDefault)&&this.hostFunctions.set("sleep",{fn:T=>{if(typeof T!="number"||!Number.isFinite(T)||T<0)throw new Error("sleep() duration must be a non-negative finite number");if(T>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,T));let f=Date.now()+T;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Ie,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let t;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(t=this.execStmt(n,this.globalEnv));return t}execStmt(e,t){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new Ie(t);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,t)),t.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,t);if(!Array.isArray(n))throw new k(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;t.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,t);return this.isTruthy(n)?this.execStmt(e.thenBranch,t):e.elseBranch?this.execStmt(e.elseBranch,t):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,t));){if(++n>1e6)throw new k("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,t)}catch(s){if(s instanceof Ue)break;if(s instanceof $e)continue;throw s}}return}case"ForStmt":{let n=new Ie(t);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new k("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof Ue)break;if(!(i instanceof $e))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,t):null;throw new yt(n)}case"BreakStmt":throw new Ue;case"ContinueStmt":throw new $e;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new k("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,t);default:return}}evalExpr(e,t){switch(e.kind){case"ParallelExpr":throw new k("'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,t);case"AssignExpr":{let n=this.evalExpr(e.value,t);return t.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,t);if(!Array.isArray(n))throw new k(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;t.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,t),s=this.evalExpr(e.index,t),i=this.evalExpr(e.value,t);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),je(n,s,i),i;throw new k("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,t);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,t));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,t));case"ObjectExpr":{let n={};for(let s of e.properties)je(n,s.key,this.evalExpr(s.value,t));return n}case"IndexExpr":{let n=this.evalExpr(e.target,t),s=this.evalExpr(e.index,t);if(n==null)throw new k("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:be(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,t),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new k(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,t);return this.isTruthy(o)?this.evalExpr(e.right,t):o}if(e.operator==="||"){let o=this.evalExpr(e.left,t);return this.isTruthy(o)?o:this.evalExpr(e.right,t)}let n=this.evalExpr(e.left,t),s=this.evalExpr(e.right,t),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new k("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new k(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,t)),s=this.resolveCallTarget(e.callee,t);return this.invokeNamed(s,n,t,e.line,e.column,e.file)}}}resolveCallTarget(e,t){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(t.has(e)){let n=t.get(e);if(n instanceof Tt)return n.name}return e}invokeNamed(e,t,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Ar)throw this.callDepth--,new k(`Execution fuel exhausted: maximum function call depth exceeded (${Ar})`,s,i,"RUNTIME",o);let l=new Ie(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],t[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof yt)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...t)}catch(l){throw l instanceof pe||l?.name==="LMScriptExit"||l?.isControlFlow?l:new k(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new k(`'${e}' is not a function`,s,i,"RUNTIME",o):new k(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,t){return t.has(e)?t.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new Tt(e):t.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Ie,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 t=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,t));return n}async execStmtAsync(e,t,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new Ie(t);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,t,n)),t.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,t,n);if(!Array.isArray(s))throw new k(`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;t.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,t,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,t,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,t,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,t,n));){if(++s>1e6)throw new k("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,t,n)}catch(i){if(i instanceof Ue)break;if(i instanceof $e)continue;throw i}}return}case"ForStmt":{let s=new Ie(t);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new k("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof Ue)break;if(!(o instanceof $e))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,t,n):null;throw new yt(s)}case"BreakStmt":throw new Ue;case"ContinueStmt":throw new $e;case"SyncAssignStmt":{let s=t.resolveBinding(e.target);if(!s)throw new k(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let i=`bind:${s.env.id}:${s.name}`;await this.lockManager.getBindingLock(i).withLock(async()=>{let a=await this.evalExprAsync(e.value,t,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,t,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new k("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,t,n),a=await this.evalExprAsync(e.value,t,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),je(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new k("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 k(`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],t,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new k("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],t,n));await this.invokeCallAsync(s.callee,[o,...l],t,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,t,n);default:return}}async evalExprAsync(e,t,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,t);case"AssignExpr":{let s=await this.evalExprAsync(e.value,t,n);return t.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,t,n);if(!Array.isArray(s))throw new k(`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;t.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,t,n),i=await this.evalExprAsync(e.index,t,n),o=await this.evalExprAsync(e.value,t,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),je(s,i,o),o;throw new k("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,t,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,t,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,t,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)je(s,i.key,await this.evalExprAsync(i.value,t,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let u=this.nextTaskId++;return this.asyncCallDepth.set(u,s),await this.evalExprAsync(c,t,u)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,t,n),i=await this.evalExprAsync(e.index,t,n);if(s==null)throw new k("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]:be(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,t,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new k(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,t,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,t,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,t,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,t,n)}let s=await this.evalExprAsync(e.left,t,n),i=await this.evalExprAsync(e.right,t,n),o=e.operator;switch(o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new k("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 k(`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,t,n));return await this.invokeCallAsync(e.callee,s,t,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,t,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>Ar)throw this.asyncCallDepth.set(o,u-1),new k(`Execution fuel exhausted: maximum function call depth exceeded (${Ar})`,s,i,"RUNTIME",a);let d=new Ie(this.globalEnv,!0);for(let p=0;p<c.params.length;p++)d.define(c.params[p],t[p]);try{for(let p of c.body.statements)await this.execStmtAsync(p,d,o)}catch(p){if(p instanceof yt)return p.value;throw p}finally{this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let u=c.fn(...t);return u instanceof Promise?await u:u}catch(u){throw u instanceof pe||u?.name==="LMScriptExit"||u?.isControlFlow?u:new k(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new k(`'${l}' is not a function`,s,i,"RUNTIME",a):new k(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},uu=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],mu=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],fu=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];function pu(r,e){if(e===void 0)return`${r}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${r}(${i.join(", ")}): any`}let t=Array.from({length:e.min},(i,o)=>`arg${o+1}: any`),n=e.max===void 0?[]:Array.from({length:e.max-e.min},(i,o)=>`[arg${e.min+o+1}: any]`),s=e.max===void 0?["...args: any"]:[];return`${r}(${[...t,...n,...s].join(", ")}): any`}function lo(r,e){let t=new Date(r),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(t.getFullYear());case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%S":return n(t.getSeconds());case"%%":return"%";default:return s}})}function Ht(r,e){let t=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(r).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[t++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}var Me=class r{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of uu)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of mu)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of fu)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){return this.functionDocs.set(e.name,{...e,module:e.module??this.currentRegisteringModule}),this}registerModule(e,t){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,t)}finally{this.currentRegisteringModule=n}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return Array.from(this.functionDocs.values()).filter(t=>(t.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return Array.from(this.functionDocs.values())}getFunctionDoc(e){return this.functionDocs.get(e)}getFunctionCategories(){let e=new Set;for(let t of this.functionDocs.values())e.add(t.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(t=>t.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>O.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>O.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let t=O.readFileSync(e,"utf-8"),n=t.length>0;return t.endsWith(`\r
|
|
156
|
+
`,zn=null;function cu(){if(!zn){let e=new Bt(lu,"<std>").tokenize(),n=new Wt(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);zn=n}return{kind:"Program",statements:[...zn.statements],line:1,column:1,file:"<std>"}}function du(r,e={}){let t=e.file||"<main>",n=e.baseDir||(e.file?se.dirname(se.resolve(e.file)):process.cwd()),s=new Map,i=new Set;function o(_,p){if(e.moduleResolver)return e.moduleResolver(_,p).path;let g=n;p&&p!=="<main>"&&p!=="<std>"&&(g=se.dirname(p));let E=se.resolve(g,_);try{return O.realpathSync(E)}catch{return E}}function a(_,p){let g,E;if(e.moduleResolver){let S=e.moduleResolver(_,p);g=S.path,E=S.source}else{if(g=o(_,p),s.has(g))return s.get(g);if(i.has(g))return{kind:"Program",statements:[],line:1,column:1,file:g};try{E=O.readFileSync(g,"utf-8")}catch(S){throw new L(`Cannot resolve import '${_}': ${S?.message||String(S)}`,1,1,"PARSER",p)}}if(s.has(g))return s.get(g);if(i.has(g))return{kind:"Program",statements:[],line:1,column:1,file:g};i.add(g);let I=new Bt(E,g).tokenize(),v=new Wt(I,g).parse();for(let S of v.statements)if(S.kind!=="FunctionDeclStmt"&&S.kind!=="ImportStmt")throw new L(`Library '${g}' cannot contain top-level executable statements; libraries must only declare functions. Found '${S.kind}'.`,S.line,S.column,"CHECKER",g);for(let S of v.statements)S.kind==="ImportStmt"&&a(S.path,g);return i.delete(g),s.set(g,v),v}let c=new Bt(r,t).tokenize(),d=new Wt(c,t).parse(),m=t!=="<main>"?o(t):"<main>";s.set(m,d);for(let _ of d.statements)_.kind==="ImportStmt"&&a(_.path,t);let h=[];if(!e.noStdlib){let _=cu();for(let p of _.statements)p.kind==="FunctionDeclStmt"&&h.push(p)}for(let[_,p]of s.entries())if(_!==m)for(let g of p.statements)g.kind==="FunctionDeclStmt"&&h.push(g);for(let _ of d.statements)_.kind!=="ImportStmt"&&h.push(_);let f={kind:"Program",statements:h,line:d.line,column:d.column,file:t},T=Array.from(s.keys());return{program:f,loadedFiles:T}}var nt=class{variables=new Set;parent;constructor(e){this.parent=e}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}},ts=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new nt;loopDepth=0;inFunction=!1;hasConcurrency=!1;constructor(e,t={}){this.options=t;for(let[n,s]of e.entries())this.hostFunctions.set(n,s),this.functions.set(n,{name:n,paramCount:typeof s.arity=="number"?s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.loopDepth=0,this.inFunction=!1,this.currentScope=new nt,this.options.globals)for(let t of this.options.globals)this.currentScope.define(t);this.functions.clear();for(let[t,n]of this.hostFunctions.entries())this.functions.set(t,{name:t,paramCount:typeof n.arity=="number"?n.arity:-1,params:[],isHost:!0,line:0,column:0});for(let t of e.statements)t.kind==="FunctionDeclStmt"&&this.collectFunction(t);for(let t of e.statements)this.checkStmt(t);return this.diagnostics}addError(e,t,n,s){this.diagnostics.push({message:e,line:t,column:n,severity:"error",file:s})}collectFunction(e){if(this.functions.has(e.name)){let n=this.functions.get(e.name);if(n.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(n.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=n.file?`${n.file}:${n.line}`:`line ${n.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let t=new Set;for(let n of e.params)t.has(n)&&this.addError(`Duplicate parameter name '${n}' in function '${e.name}'`,e.line,e.column,e.file),t.add(n);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"ImportStmt":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 t=this.currentScope,n=this.inFunction;this.inFunction=!0,this.currentScope=new nt(t);for(let s of e.params)this.currentScope.define(s);for(let s of e.body.statements)this.checkStmt(s);this.inFunction=n,this.currentScope=t;break}case"VarDeclStmt":{this.currentScope.hasInCurrent(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),this.currentScope.define(e.name);break}case"TupleVarDeclStmt":{this.checkExpr(e.initializer);for(let t of e.names)this.currentScope.hasInCurrent(t)&&this.addError(`Variable '${t}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(t);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"ForStmt":{let t=this.currentScope;this.currentScope=new nt(t),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),e.update&&this.checkExpr(e.update),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,this.currentScope=t;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);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 t=this.currentScope;this.currentScope=new nt(t);for(let n of e.statements)this.checkStmt(n);this.currentScope=t;break}case"SyncAssignStmt":{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);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 t=e.call;t.args.length===0&&this.addError(`Synchronized call '${t.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let n=this.hostFunctions.get(t.callee);(!n||!n.isContainerMutation)&&this.addError(`Synchronized call '${t.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);break}}}checkReadPath(e){let t=e.args[0];for(;t.kind==="GroupingExpr";)t=t.expression;if(t.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 t.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!O.statSync(t.value).isFile())throw new Error("path is not a regular file");O.accessSync(t.value,O.constants.R_OK)}catch(n){this.addError(`Cannot read file ${JSON.stringify(t.value)}: ${n instanceof Error?n.message:String(n)}`,e.line,e.column,e.file)}}checkExpr(e){switch(e.kind){case"LiteralExpr":break;case"IdentifierExpr":{!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.checkExpr(e.value),this.currentScope.resolve(e.target)||this.currentScope.define(e.target);break}case"TupleAssignExpr":{this.checkExpr(e.value);for(let t of e.targets)this.currentScope.resolve(t)||this.currentScope.define(t);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let t of e.elements)this.checkExpr(t);break}case"ArrayExpr":{for(let t of e.elements)this.checkExpr(t);break}case"ObjectExpr":{for(let t of e.properties)this.checkExpr(t.value);break}case"IndexExpr":{this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let t of e.tasks)this.checkExpr(t);break}case"CallExpr":{let t=this.functions.get(e.callee);t?t.paramCount>=0&&e.args.length!==t.paramCount&&this.addError(`Function '${e.callee}' expects ${t.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(`Call to undefined function '${e.callee}'`,e.line,e.column,e.file);let n=this.hostFunctions.get(e.callee),s=n?.arity;typeof s=="object"&&(e.args.length<s.min||e.args.length>(s.max??1/0))&&this.addError(`Function '${e.callee}' expects ${s.min}..${s.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),this.options.checkFiles&&n?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let i of e.args)this.checkExpr(i);break}}}},yt=class{value;constructor(e){this.value=e}},$e=class{},je=class{},Tt=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},xe=class r{static nextId=1;id=r.nextId++;values=new Map;parent;isFunctionBoundary;constructor(e,t=!1){this.parent=e,this.isFunctionBoundary=t}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,t){this.values.set(e,t)}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)}set(e,t){if(this.values.has(e)){this.values.set(e,t);return}if(!this.isFunctionBoundary&&this.parent?.has(e)){this.parent.set(e,t);return}this.values.set(e,t)}},kr=class{holderTaskId;depth=0;waiters=[];acquire(e=0,t=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((n,s)=>{let i;t>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 ${t}ms (possible deadlock)`)))},t));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,n()};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,t=0,n=1e4){await this.acquire(t,n);try{return await e()}finally{this.release()}}},rs=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let t=this.bindingLocks.get(e);return t||(t=new kr,this.bindingLocks.set(e,t)),t}getObjectLock(e){let t=this.objectLocks.get(e);return t||(t=new kr,this.objectLocks.set(e,t)),t}},Lr=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new rs;isAsync;nextTaskId=1;initialGlobals;callDepth=0;asyncCallDepth=new Map;recordedErrors=[];constructor(e,t=o=>console.log(o),n=!1,s,i){this.stdout=t,this.stderr=i,this.isAsync=n,this.initialGlobals=s,this.globalEnv=new xe,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(..._)=>{let p=_.map(g=>typeof g=="object"?JSON.stringify(g):String(g)).join(" ");return this.stdout(p),p},description:"Prints formatted values to output log",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(..._)=>{let p=_.map(g=>typeof g=="object"?JSON.stringify(g):String(g)).join(" ");return this.stdout(p),p},description:"Prints line to output log",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(_,...p)=>{let g=Ht(_,p);return this.stdout(g),g},description:"Formats a template using %s/%d/%f/%% substitution and prints it",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(..._)=>{let p=_.map(g=>typeof g=="object"?JSON.stringify(g):String(g)).join(" ");return this.stderr?this.stderr(`error: ${p}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${p}
|
|
157
|
+
`):console.error(`error: ${p}`),this.recordedErrors.push(p),p},description:"Prints error message to stderr and records it for execution error summary",isDefault:!0});let u=e.get("system");(!u||u.isDefault)&&this.hostFunctions.set("system",{fn:(_,p=6e4)=>{if(!Number.isSafeInteger(p)||p<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsync?Eo(_,p):_o(_,p)},arity:{min:1,max:2},description:"Executes shell command or argv array directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",isDefault:!0});let d=e.get("prompt_human");(!d||d.isDefault)&&this.hostFunctions.set("prompt_human",{fn:_=>this.isAsync?qt(_):Xt(_),arity:{min:0,max:1},description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",isDefault:!0});let m=e.get("shell_quote");(!m||m.isDefault)&&this.hostFunctions.set("shell_quote",{fn:_=>go(_),arity:1,description:"Quotes string safely for POSIX shell command execution",isDefault:!0});let h=e.get("run_script");(!h||h.isDefault)&&this.hostFunctions.set("run_script",{fn:(_,p=[])=>{let g=se.resolve(String(_));if(!O.existsSync(g))throw new Error(`run_script: file not found: '${g}'`);let E=O.readFileSync(g,"utf-8"),w=Array.isArray(p)?p.map(String):[],I=new Me;for(let[y,v]of this.hostFunctions)I.hasFunction(y)?v.isDefault||I.registerFunction(y,v.fn,v.arity,{description:v.description,allowOverwrite:!0},!1,v.isContainerMutation):I.registerFunction(y,v.fn,v.arity,v.description,v.isDefault,v.isContainerMutation);if(I.setGlobal("args",[...w]),I.setGlobal("ARGV",[g,...w]),this.isAsync)return(async()=>{let y=await I.runAsync(E,{file:g}),v=y.output.join(`
|
|
158
|
+
`)+(y.output.length>0?`
|
|
159
|
+
`:""),S=y.exitCode!==void 0?y.exitCode:y.success?0:1,x={success:y.success&&S===0,stdout:v,output:[...y.output],value:y.value,exit_code:S,code:S,errors:y.errors??[]};return x.toString=()=>v,x})();{let y=I.run(E,{file:g}),v=y.output.join(`
|
|
160
|
+
`)+(y.output.length>0?`
|
|
161
|
+
`:""),S=y.exitCode!==void 0?y.exitCode:y.success?0:1,x={success:y.success&&S===0,stdout:v,output:[...y.output],value:y.value,exit_code:S,code:S,errors:y.errors??[]};return x.toString=()=>v,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let f=e.get("urlget");(!f||f.isDefault)&&this.hostFunctions.set("urlget",{fn:_=>this.isAsync?ou(_):ho(_),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let T=e.get("sleep");(!T||T.isDefault)&&this.hostFunctions.set("sleep",{fn:_=>{if(typeof _!="number"||!Number.isFinite(_)||_<0)throw new Error("sleep() duration must be a non-negative finite number");if(_>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(g=>setTimeout(g,_));let p=Date.now()+_;for(;Date.now()<p;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new xe,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let t;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(t=this.execStmt(n,this.globalEnv));return t}execStmt(e,t){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new xe(t);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,t)),t.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,t);if(!Array.isArray(n))throw new L(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;t.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,t);return this.isTruthy(n)?this.execStmt(e.thenBranch,t):e.elseBranch?this.execStmt(e.elseBranch,t):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,t));){if(++n>1e6)throw new L("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,t)}catch(s){if(s instanceof $e)break;if(s instanceof je)continue;throw s}}return}case"ForStmt":{let n=new xe(t);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new L("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof $e)break;if(!(i instanceof je))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,t):null;throw new yt(n)}case"BreakStmt":throw new $e;case"ContinueStmt":throw new je;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new L("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,t);default:return}}evalExpr(e,t){switch(e.kind){case"ParallelExpr":throw new L("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,t);case"AssignExpr":{let n=this.evalExpr(e.value,t);return t.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,t);if(!Array.isArray(n))throw new L(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;t.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,t),s=this.evalExpr(e.index,t),i=this.evalExpr(e.value,t);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),Be(n,s,i),i;throw new L("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,t);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,t));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,t));case"ObjectExpr":{let n={};for(let s of e.properties)Be(n,s.key,this.evalExpr(s.value,t));return n}case"IndexExpr":{let n=this.evalExpr(e.target,t),s=this.evalExpr(e.index,t);if(n==null)throw new L("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:Re(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,t),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new L(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,t);return this.isTruthy(o)?this.evalExpr(e.right,t):o}if(e.operator==="||"){let o=this.evalExpr(e.left,t);return this.isTruthy(o)?o:this.evalExpr(e.right,t)}let n=this.evalExpr(e.left,t),s=this.evalExpr(e.right,t),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new L("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new L(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,t)),s=this.resolveCallTarget(e.callee,t);return this.invokeNamed(s,n,t,e.line,e.column,e.file)}}}resolveCallTarget(e,t){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(t.has(e)){let n=t.get(e);if(n instanceof Tt)return n.name}return e}invokeNamed(e,t,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Ar)throw this.callDepth--,new L(`Execution fuel exhausted: maximum function call depth exceeded (${Ar})`,s,i,"RUNTIME",o);let l=new xe(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],t[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof yt)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...t)}catch(l){throw l instanceof he||l?.name==="LMScriptExit"||l?.isControlFlow?l:new L(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new L(`'${e}' is not a function`,s,i,"RUNTIME",o):new L(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,t){return t.has(e)?t.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new Tt(e):t.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new xe,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 t=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,t));return n}async execStmtAsync(e,t,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new xe(t);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,t,n)),t.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,t,n);if(!Array.isArray(s))throw new L(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;t.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,t,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,t,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,t,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,t,n));){if(++s>1e6)throw new L("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,t,n)}catch(i){if(i instanceof $e)break;if(i instanceof je)continue;throw i}}return}case"ForStmt":{let s=new xe(t);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new L("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof $e)break;if(!(o instanceof je))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,t,n):null;throw new yt(s)}case"BreakStmt":throw new $e;case"ContinueStmt":throw new je;case"SyncAssignStmt":{let s=t.resolveBinding(e.target);if(!s)throw new L(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let i=`bind:${s.env.id}:${s.name}`;await this.lockManager.getBindingLock(i).withLock(async()=>{let a=await this.evalExprAsync(e.value,t,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,t,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new L("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,t,n),a=await this.evalExprAsync(e.value,t,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Be(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new L("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new L(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],t,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new L("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],t,n));await this.invokeCallAsync(s.callee,[o,...l],t,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,t,n);default:return}}async evalExprAsync(e,t,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,t);case"AssignExpr":{let s=await this.evalExprAsync(e.value,t,n);return t.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,t,n);if(!Array.isArray(s))throw new L(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;t.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,t,n),i=await this.evalExprAsync(e.index,t,n),o=await this.evalExprAsync(e.value,t,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Be(s,i,o),o;throw new L("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,t,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,t,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,t,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Be(s,i.key,await this.evalExprAsync(i.value,t,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let u=this.nextTaskId++;return this.asyncCallDepth.set(u,s),await this.evalExprAsync(c,t,u)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,t,n),i=await this.evalExprAsync(e.index,t,n);if(s==null)throw new L("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:Re(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,t,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new L(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,t,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,t,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,t,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,t,n)}let s=await this.evalExprAsync(e.left,t,n),i=await this.evalExprAsync(e.right,t,n),o=e.operator;switch(o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new L("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new L(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,t,n));return await this.invokeCallAsync(e.callee,s,t,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,t,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>Ar)throw this.asyncCallDepth.set(o,u-1),new L(`Execution fuel exhausted: maximum function call depth exceeded (${Ar})`,s,i,"RUNTIME",a);let d=new xe(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)d.define(c.params[m],t[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,d,o)}catch(m){if(m instanceof yt)return m.value;throw m}finally{this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let u=c.fn(...t);return u instanceof Promise?await u:u}catch(u){throw u instanceof he||u?.name==="LMScriptExit"||u?.isControlFlow?u:new L(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new L(`'${l}' is not a function`,s,i,"RUNTIME",a):new L(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},uu=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],mu=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],fu=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];function pu(r,e){if(e===void 0)return`${r}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${r}(${i.join(", ")}): any`}let t=Array.from({length:e.min},(i,o)=>`arg${o+1}: any`),n=e.max===void 0?[]:Array.from({length:e.max-e.min},(i,o)=>`[arg${e.min+o+1}: any]`),s=e.max===void 0?["...args: any"]:[];return`${r}(${[...t,...n,...s].join(", ")}): any`}function lo(r,e){let t=new Date(r),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(t.getFullYear());case"%m":return n(t.getMonth()+1);case"%d":return n(t.getDate());case"%H":return n(t.getHours());case"%M":return n(t.getMinutes());case"%S":return n(t.getSeconds());case"%%":return"%";default:return s}})}function Ht(r,e){let t=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(r).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[t++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}var Me=class r{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of uu)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of mu)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of fu)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){return this.functionDocs.set(e.name,{...e,module:e.module??this.currentRegisteringModule}),this}registerModule(e,t){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,t)}finally{this.currentRegisteringModule=n}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return Array.from(this.functionDocs.values()).filter(t=>(t.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return Array.from(this.functionDocs.values())}getFunctionDoc(e){return this.functionDocs.get(e)}getFunctionCategories(){let e=new Set;for(let t of this.functionDocs.values())e.add(t.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(t=>t.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>O.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>O.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let t=O.readFileSync(e,"utf-8"),n=t.length>0;return t.endsWith(`\r
|
|
162
162
|
`)?t=t.slice(0,-2):t.endsWith(`
|
|
163
163
|
`)&&(t=t.slice(0,-1)),n?t.length===0?[""]:t.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,t)=>{if(!Array.isArray(t))throw new Error("write_lines: second argument must be an array of lines");let n=t.length===0?"":t.map(String).join(`
|
|
164
164
|
`)+`
|
|
165
|
-
`;return O.writeFileSync(e,n,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from(O.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return O.readdirSync(se.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,t)=>(O.writeFileSync(e,String(t),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,t)=>(O.writeFileSync(e,String(t),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,t)=>(O.appendFileSync(e,String(t),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let t=O.readFileSync(e,"utf-8");return JSON.parse(t)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,t,n=2)=>(O.writeFileSync(e,JSON.stringify(t,null,n),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,t=!0,n=",")=>{let s=O.readFileSync(e,"utf-8");return so(s,t,n)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,t,n=",")=>(O.writeFileSync(e,oo(t,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",so,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",oo,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=se.resolve(iu(),`lmscript-${su()}`),t=O.openSync(e,"wx",384);return O.closeSync(t),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>O.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new
|
|
165
|
+
`;return O.writeFileSync(e,n,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from(O.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return O.readdirSync(se.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,t)=>(O.writeFileSync(e,String(t),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,t)=>(O.writeFileSync(e,String(t),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,t)=>(O.appendFileSync(e,String(t),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let t=O.readFileSync(e,"utf-8");return JSON.parse(t)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,t,n=2)=>(O.writeFileSync(e,JSON.stringify(t,null,n),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,t=!0,n=",")=>{let s=O.readFileSync(e,"utf-8");return so(s,t,n)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,t,n=",")=>(O.writeFileSync(e,oo(t,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",so,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",oo,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=se.resolve(iu(),`lmscript-${su()}`),t=O.openSync(e,"wx",384);return O.closeSync(t),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>O.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new he(Number(e))},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>O.existsSync(e)?(O.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>O.existsSync(e)?(O.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,t=!0)=>(O.mkdirSync(e,{recursive:!!t}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,t=!1)=>O.existsSync(e)?(t?O.rmSync(e,{recursive:!0,force:!0}):O.rmdirSync(e),!0):!1,{min:1,max:2},"Removes a directory; pass true for recursive removal of a non-empty directory"),this.registerFunction("copy_file",(e,t)=>(O.copyFileSync(e,t),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,t)=>(O.renameSync(e,t),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,t)=>se.basename(e,t),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>se.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>se.join(...e),void 0,"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>se.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,t=null)=>process.env[e]!==void 0?process.env[e]:t,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,t=null)=>process.env[e]!==void 0?process.env[e]:t,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,t)=>(process.env[e]=String(t),!0),2,"Sets an environment variable for this process and its children"),this.registerFunction("list",(...e)=>e,void 0,"Creates a new list/array"),this.registerFunction("array",(...e)=>e,void 0,"Creates a new list/array"),this.registerFunction("push",(e,...t)=>(e.push(...t),e),void 0,"Pushes item(s) to end of array and returns the array",!0,!0),this.registerFunction("pop",e=>e.pop(),1,"Pops item from end of array",!0,!0),this.registerFunction("shift",e=>e.shift(),1,"Removes and returns first element",!0,!0),this.registerFunction("unshift",(e,...t)=>(e.unshift(...t),e),void 0,"Adds item(s) to front of array and returns the array",!0,!0),this.registerFunction("insert",(e,t,n)=>{let s=t<0?e.length+t:t;return e.splice(s,0,n),e},3,"Inserts item at index and returns the array",!0,!0),this.registerFunction("remove_at",(e,t)=>{let n=t<0?e.length+t:t,s=e.splice(n,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...t)=>e.concat(...t),void 0,"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,t)=>{if(!Array.isArray(e))return e;let n=[...e];return t?n.sort((s,i)=>{let o=s?s[t]:void 0,a=i?i[t]:void 0;return o<a?-1:o>a?1:0}):n.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:String(s).localeCompare(String(i)))},void 0,"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("sorted",(e,t)=>this.hostFunctions.get("sort").fn(e,t),void 0,"Sorts array numerically, alphabetically, or by object key (alias for sort)"),this.registerFunction("unique",e=>Array.isArray(e)?Array.from(new Set(e)):[],1,"Removes duplicate elements"),this.registerFunction("flatten",e=>Array.isArray(e)?e.flat():[],1,"Flattens array one level"),this.registerFunction("first",e=>Array.isArray(e)&&e.length>0?e[0]:null,1,"Returns first element"),this.registerFunction("last",e=>Array.isArray(e)&&e.length>0?e[e.length-1]:null,1,"Returns last element"),this.registerFunction("sum",e=>Array.isArray(e)?e.reduce((t,n)=>t+(typeof n=="number"?n:Number(n)||0),0):0,1,"Calculates sum of array"),this.registerFunction("avg",e=>!Array.isArray(e)||e.length===0?0:e.reduce((n,s)=>n+(typeof s=="number"?s:Number(s)||0),0)/e.length,1,"Calculates average of array"),this.registerFunction("hash",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("from_entries",e=>Array.isArray(e)?Object.fromEntries(e):{},1,"Creates map from [key, value] pairs"),this.registerFunction("clear",e=>{if(Array.isArray(e))return e.length=0,e;if(e&&typeof e=="object"){for(let t of Object.keys(e))delete e[t];return e}return e},1,"Clears array or map",!0,!0),this.registerFunction("size",e=>Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns number of elements in array, string, or map"),this.registerFunction("system",(e,t=6e4)=>{if(!Number.isSafeInteger(t)||t<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsyncMode?Eo(e,t):_o(e,t)},{min:1,max:2},"Executes shell command or argv array directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",!0),this.registerFunction("run_script",(e,t=[])=>{let n=se.resolve(String(e));if(!O.existsSync(n))throw new Error(`run_script: file not found: '${n}'`);let s=O.readFileSync(n,"utf-8"),i=Array.isArray(t)?t.map(String):[],o=new r;for(let[a,l]of this.hostFunctions)o.hasFunction(a)?l.isDefault||o.registerFunction(a,l.fn,l.arity,{description:l.description,allowOverwrite:!0},!1,l.isContainerMutation):o.registerFunction(a,l.fn,l.arity,l.description,l.isDefault,l.isContainerMutation);if(o.setGlobal("args",[...i]),o.setGlobal("ARGV",[n,...i]),this.isAsyncMode)return(async()=>{let a=await o.runAsync(s,{file:n}),l=a.output.join(`
|
|
166
166
|
`)+(a.output.length>0?`
|
|
167
167
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,u={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return u.toString=()=>l,u})();{let a=o.run(s,{file:n}),l=a.output.join(`
|
|
168
168
|
`)+(a.output.length>0?`
|
|
169
169
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,u={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return u.toString=()=>l,u}},{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 t=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${t}
|
|
170
|
-
`):console.error(`error: ${t}`),t},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>ho(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let t=Date.now()+e;for(;Date.now()<t;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?qt(e):Xt(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,t)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,t)},{min:1,max:2},"Parses JSON string into object/array, or stringifies data to JSON string"),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(t){throw new Error(`JSON parse error: ${t.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,t=null)=>au(e,t),{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,t)=>JSON.stringify(e,null,t),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,t)=>e&&typeof e=="object"?Object.hasOwn(e,t):!1,2,"Checks if object has key"),this.registerFunction("has",(e,t)=>e&&typeof e=="object"?Object.hasOwn(e,t):!1,2,"Checks if object has key"),this.registerFunction("get",(e,t,n=null)=>{if(e==null)return n;let s=Array.isArray(t)?t:String(t).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o of s){if(i==null||typeof i!="object")return n;i=be(i,o)}return i!==void 0?i:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("set",(e,t,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(t)?t:String(t).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(be(i,a)==null||typeof be(i,a)!="object")&&je(i,a,{}),i=be(i,a)}return s.length>0&&je(i,s[s.length-1],n),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,t)=>Array.isArray(e)?e.map(n=>be(n,t)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,t,n)=>Array.isArray(e)?e.filter(s=>s!=null&&be(s,t)===n):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,t,n)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&be(i,t)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,t)=>({...e,...t}),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,t)=>(e&&typeof e=="object"&&delete e[t],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let t=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(t),t},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let t=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(t),t},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...t)=>{let n=Ht(e,t);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,t="")=>String(e).split(t),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let t=e.split(/\r?\n/);for(let n=t.length-1;n>=0;n--){let s=t[n].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,t=", ")=>Array.isArray(e)?e.join(t):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let t=String(e);return t.length===0?"":t.charAt(0).toUpperCase()+t.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,t=>t.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,t)=>Array.isArray(e)?e.includes(t):String(e).includes(String(t)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,t)=>Array.isArray(e)?e.includes(t):String(e).includes(String(t)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,t)=>String(e).startsWith(t),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,t)=>String(e).startsWith(t),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,t)=>String(e).endsWith(t),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,t)=>String(e).endsWith(t),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,t,n)=>String(e).indexOf(t,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,t,n)=>String(e).indexOf(t,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,t)=>String(e).lastIndexOf(t),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,t)=>t?String(e).split(t).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,t,n)=>{let s=String(e);return n===void 0?s.substring(t):s.substring(t,t+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,t,n)=>String(e).substring(t,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,t,n)=>e!=null?e.slice(t,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,t)=>String(e).charAt(t),2,"Returns character at index"),this.registerFunction("char_code",(e,t=0)=>String(e).charCodeAt(t),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,t,n)=>String(e).replace(t,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,t,n)=>String(e).replaceAll(t,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,t)=>String(e).repeat(t),2,"Repeats string count times"),this.registerFunction("pad_start",(e,t,n=" ")=>String(e).padStart(t,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,t,n=" ")=>String(e).padEnd(t,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof Tt,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>go(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...t)=>{let n=String(e),s=t.length===1&&typeof t[0]=="object"&&t[0]!==null&&!Array.isArray(t[0])?t[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=n.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=n.slice(l+1,u);if(d==="")o+=i<t.length?a(t[i++]):"{}";else if(/^\d+$/.test(d)){let p=Number(d);o+=p<t.length?a(t[p]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...t)=>Ht(e,t),void 0,"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax)"),this.registerFunction("regex_test",(e,t,n="")=>new RegExp(t,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,t,n="")=>new RegExp(t,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string (alias for regex_test)"),this.registerFunction("regex_match",(e,t,n="")=>{let s=String(e).match(new RegExp(t,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null"),this.registerFunction("match",(e,t,n="")=>{let s=String(e).match(new RegExp(t,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("search",(e,t,n="")=>{let s=String(e).match(new RegExp(t,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("regex_find_all",(e,t,n="")=>{let s=new RegExp(t,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...]"),this.registerFunction("findall",(e,t,n="")=>{let s=new RegExp(t,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all)"),this.registerFunction("regex_replace",(e,t,n,s="")=>String(e).replace(new RegExp(t,s),n),{min:3,max:4},'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence, not just the first'),this.registerFunction("split_regex",(e,t,n="")=>String(e).split(new RegExp(t,n)),{min:2,max:3},"Splits a string into an array wherever the regex pattern matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("length",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("count",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("range",(e,t,n=1)=>{let s=t===void 0?0:e,i=t===void 0?e:t,o=[];if(n>0)for(let a=s;a<i;a+=n)o.push(a);else if(n<0)for(let a=s;a>i;a+=n)o.push(a);return o},void 0,"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let t=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...t)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let t=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...t)},void 0,"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,t)=>Math.pow(e,t),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("clock",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms (alias for clock)"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,t)=>lo(e,t),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,t)=>lo(e,t),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let t of e)if(t!=null)return t;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,t)=>e??t,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,t)=>e??t,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,t,n)=>e?t:n,3,"Expression-level ternary: returns thenVal if cond is truthy, else elseVal"),this.registerFunction("str",e=>e===null?"null":String(e),1,"Converts value to string"),this.registerFunction("to_string",e=>e===null?"null":String(e),1,"Converts value to string (alias for str)"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof Tt?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,t="Assertion failed")=>{if(!e)throw new Error(t);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,t,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=typeof s=="object"?s.doc:void 0,d=typeof s=="object"?!!s.allowOverwrite:!1,p=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,m=this.functionOriginModule.get(e);if(m&&m!==p&&!d)throw new Error(`Cannot register function '${e}' from module '${p}': already registered by module '${m}'`);return this.functionOriginModule.set(e,p),this.hostFunctions.set(e,{fn:t,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:u}),u?this.functionDocs.set(e,{...u,module:u.module??p}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:p,signature:pu(e,n),description:a}),this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,t){return this.initialGlobals.set(e,t),this}getGlobal(e){return this.initialGlobals.get(e)}scanAndCheck(e,t={}){try{let{program:n}=du(e,t),s=[...this.initialGlobals.keys(),...t.globals||[]],i=new ts(this.hostFunctions,{...t,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof k?{ast:null,diagnostics:[{message:n.message,line:n.line,column:n.column,severity:"error",file:n.file||t.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:n instanceof Error?n.message:String(n),line:1,column:1,severity:"error",file:t.file}],hasConcurrency:!1}}}run(e,t={}){let n=[],{ast:s,diagnostics:i,hasConcurrency:o}=this.scanAndCheck(e,t);if(i.filter(c=>c.severity==="error").length>0||!s)return this.outputLogs=n,{success:!1,diagnostics:i,output:n};if(o)return this.outputLogs=n,{success:!1,diagnostics:[...i,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:t.file}],output:n};let l;try{l=new Lr(this.hostFunctions,d=>n.push(d),!1,this.initialGlobals,t.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let u=l.getRecordedErrors();return this.lastRecordedErrors=u,{success:!0,value:c,diagnostics:i,output:n,errors:u}}catch(c){let u=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=u,c instanceof pe||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let h=typeof c.exitCode=="number"?c.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:i,output:n,errors:u}}let d=c instanceof k?c.line:1,p=c instanceof k?c.column:1,m=c instanceof k&&c.file||t.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:d,column:p,severity:"error",file:m}],output:n,errors:u}}}async runAsync(e,t={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,t);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new Lr(this.hostFunctions,u=>n.push(u),!0,this.initialGlobals,t.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof pe||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let m=typeof l.exitCode=="number"?l.exitCode:0;return{success:m===0,value:m,exitCode:m,diagnostics:i,output:n,errors:c}}let u=l instanceof k?l.line:1,d=l instanceof k?l.column:1,p=l instanceof k&&l.file||t.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:u,column:d,severity:"error",file:p}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function hu(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
170
|
+
`):console.error(`error: ${t}`),t},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>ho(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let t=Date.now()+e;for(;Date.now()<t;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?qt(e):Xt(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,t)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,t)},{min:1,max:2},"Parses JSON string into object/array, or stringifies data to JSON string"),this.registerFunction("json_parse",e=>{try{return JSON.parse(String(e))}catch(t){throw new Error(`JSON parse error: ${t.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,t=null)=>au(e,t),{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,t)=>JSON.stringify(e,null,t),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,t)=>e&&typeof e=="object"?Object.hasOwn(e,t):!1,2,"Checks if object has key"),this.registerFunction("has",(e,t)=>e&&typeof e=="object"?Object.hasOwn(e,t):!1,2,"Checks if object has key"),this.registerFunction("get",(e,t,n=null)=>{if(e==null)return n;let s=Array.isArray(t)?t:String(t).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o of s){if(i==null||typeof i!="object")return n;i=Re(i,o)}return i!==void 0?i:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("set",(e,t,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(t)?t:String(t).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(Re(i,a)==null||typeof Re(i,a)!="object")&&Be(i,a,{}),i=Re(i,a)}return s.length>0&&Be(i,s[s.length-1],n),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,t)=>Array.isArray(e)?e.map(n=>Re(n,t)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,t,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Re(s,t)===n):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,t,n)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&Re(i,t)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,t)=>({...e,...t}),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,t)=>(e&&typeof e=="object"&&delete e[t],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let t=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(t),t},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let t=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(t),t},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...t)=>{let n=Ht(e,t);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,t="")=>String(e).split(t),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let t=e.split(/\r?\n/);for(let n=t.length-1;n>=0;n--){let s=t[n].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,t=", ")=>Array.isArray(e)?e.join(t):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let t=String(e);return t.length===0?"":t.charAt(0).toUpperCase()+t.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,t=>t.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,t)=>Array.isArray(e)?e.includes(t):String(e).includes(String(t)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,t)=>Array.isArray(e)?e.includes(t):String(e).includes(String(t)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,t)=>String(e).startsWith(t),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,t)=>String(e).startsWith(t),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,t)=>String(e).endsWith(t),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,t)=>String(e).endsWith(t),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,t,n)=>String(e).indexOf(t,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,t,n)=>String(e).indexOf(t,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,t)=>String(e).lastIndexOf(t),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,t)=>t?String(e).split(t).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,t,n)=>{let s=String(e);return n===void 0?s.substring(t):s.substring(t,t+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,t,n)=>String(e).substring(t,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,t,n)=>e!=null?e.slice(t,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,t)=>String(e).charAt(t),2,"Returns character at index"),this.registerFunction("char_code",(e,t=0)=>String(e).charCodeAt(t),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,t,n)=>String(e).replace(t,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,t,n)=>String(e).replaceAll(t,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,t)=>String(e).repeat(t),2,"Repeats string count times"),this.registerFunction("pad_start",(e,t,n=" ")=>String(e).padStart(t,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,t,n=" ")=>String(e).padEnd(t,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof Tt,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>go(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...t)=>{let n=String(e),s=t.length===1&&typeof t[0]=="object"&&t[0]!==null&&!Array.isArray(t[0])?t[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=n.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=n.slice(l+1,u);if(d==="")o+=i<t.length?a(t[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<t.length?a(t[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},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...t)=>Ht(e,t),void 0,"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax)"),this.registerFunction("regex_test",(e,t,n="")=>new RegExp(t,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,t,n="")=>new RegExp(t,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string (alias for regex_test)"),this.registerFunction("regex_match",(e,t,n="")=>{let s=String(e).match(new RegExp(t,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null"),this.registerFunction("match",(e,t,n="")=>{let s=String(e).match(new RegExp(t,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("search",(e,t,n="")=>{let s=String(e).match(new RegExp(t,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("regex_find_all",(e,t,n="")=>{let s=new RegExp(t,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...]"),this.registerFunction("findall",(e,t,n="")=>{let s=new RegExp(t,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all)"),this.registerFunction("regex_replace",(e,t,n,s="")=>String(e).replace(new RegExp(t,s),n),{min:3,max:4},'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence, not just the first'),this.registerFunction("split_regex",(e,t,n="")=>String(e).split(new RegExp(t,n)),{min:2,max:3},"Splits a string into an array wherever the regex pattern matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("length",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("count",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("range",(e,t,n=1)=>{let s=t===void 0?0:e,i=t===void 0?e:t,o=[];if(n>0)for(let a=s;a<i;a+=n)o.push(a);else if(n<0)for(let a=s;a>i;a+=n)o.push(a);return o},void 0,"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let t=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...t)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let t=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...t)},void 0,"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,t)=>Math.pow(e,t),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("clock",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms (alias for clock)"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,t)=>lo(e,t),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,t)=>lo(e,t),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let t of e)if(t!=null)return t;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,t)=>e??t,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,t)=>e??t,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,t,n)=>e?t:n,3,"Expression-level ternary: returns thenVal if cond is truthy, else elseVal"),this.registerFunction("str",e=>e===null?"null":String(e),1,"Converts value to string"),this.registerFunction("to_string",e=>e===null?"null":String(e),1,"Converts value to string (alias for str)"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof Tt?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,t="Assertion failed")=>{if(!e)throw new Error(t);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,t,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=typeof s=="object"?s.doc:void 0,d=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,h=this.functionOriginModule.get(e);if(h&&h!==m&&!d)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${h}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:t,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:u}),u?this.functionDocs.set(e,{...u,module:u.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:pu(e,n),description:a}),this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,t){return this.initialGlobals.set(e,t),this}getGlobal(e){return this.initialGlobals.get(e)}scanAndCheck(e,t={}){try{let{program:n}=du(e,t),s=[...this.initialGlobals.keys(),...t.globals||[]],i=new ts(this.hostFunctions,{...t,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof L?{ast:null,diagnostics:[{message:n.message,line:n.line,column:n.column,severity:"error",file:n.file||t.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:n instanceof Error?n.message:String(n),line:1,column:1,severity:"error",file:t.file}],hasConcurrency:!1}}}run(e,t={}){let n=[],{ast:s,diagnostics:i,hasConcurrency:o}=this.scanAndCheck(e,t);if(i.filter(c=>c.severity==="error").length>0||!s)return this.outputLogs=n,{success:!1,diagnostics:i,output:n};if(o)return this.outputLogs=n,{success:!1,diagnostics:[...i,{message:"Concurrency constructs ('parallel', 'sync') require asynchronous execution via engine.runAsync()",line:1,column:1,severity:"error",file:t.file}],output:n};let l;try{l=new Lr(this.hostFunctions,d=>n.push(d),!1,this.initialGlobals,t.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let u=l.getRecordedErrors();return this.lastRecordedErrors=u,{success:!0,value:c,diagnostics:i,output:n,errors:u}}catch(c){let u=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=u,c instanceof he||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let f=typeof c.exitCode=="number"?c.exitCode:0;return{success:f===0,value:f,exitCode:f,diagnostics:i,output:n,errors:u}}let d=c instanceof L?c.line:1,m=c instanceof L?c.column:1,h=c instanceof L&&c.file||t.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:d,column:m,severity:"error",file:h}],output:n,errors:u}}}async runAsync(e,t={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,t);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new Lr(this.hostFunctions,u=>n.push(u),!0,this.initialGlobals,t.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof he||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let h=typeof l.exitCode=="number"?l.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:i,output:n,errors:c}}let u=l instanceof L?l.line:1,d=l instanceof L?l.column:1,m=l instanceof L&&l.file||t.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:u,column:d,severity:"error",file:m}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function hu(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
171
171
|
`);let r=new Me,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=r.run(`
|
|
172
172
|
fn factorial(n) {
|
|
173
173
|
if (n <= 1) {
|
|
@@ -189,9 +189,9 @@ fn clamp(val, low, high) {
|
|
|
189
189
|
}
|
|
190
190
|
print("sum skipping 3 =", sumVal);
|
|
191
191
|
assert(sumVal == 12, "sum must be 12");
|
|
192
|
-
`);n.success?(console.log(n.output.map(
|
|
192
|
+
`);n.success?(console.log(n.output.map(g=>" [out] "+g).join(`
|
|
193
193
|
`)),console.log(` -> Passed!
|
|
194
|
-
`)):(console.error(" -> Failed:",n.diagnostics),e=!1),console.log("Test Suite 2: TS Predefined Builtins & Host Registration"),r.registerFunction("base64Encode",
|
|
194
|
+
`)):(console.error(" -> Failed:",n.diagnostics),e=!1),console.log("Test Suite 2: TS Predefined Builtins & Host Registration"),r.registerFunction("base64Encode",g=>Buffer.from(g).toString("base64"),1,"Base64 encodes a string"),r.registerFunction("addVectors",(g,E)=>g.map((w,I)=>w+(E[I]||0)),2,"Adds two numeric arrays element-wise");let i=r.run(`
|
|
195
195
|
let text = "TypeScript Engine";
|
|
196
196
|
let encoded = base64Encode(text);
|
|
197
197
|
print("Encoded base64:", encoded);
|
|
@@ -206,7 +206,7 @@ fn clamp(val, low, high) {
|
|
|
206
206
|
|
|
207
207
|
print("sqrt(16) =", sqrt(16));
|
|
208
208
|
print("min(5, 2, 9) =", min(5, 2, 9));
|
|
209
|
-
`);i.success?(console.log(i.output.map(
|
|
209
|
+
`);i.success?(console.log(i.output.map(g=>" [out] "+g).join(`
|
|
210
210
|
`)),console.log(` -> Passed!
|
|
211
211
|
`)):(console.error(" -> Failed:",i.diagnostics),e=!1),console.log("Test Suite 3: Static Analysis Validation (Zero Execution on Error)");let o=`
|
|
212
212
|
let x = 10;
|
|
@@ -224,7 +224,7 @@ fn clamp(val, low, high) {
|
|
|
224
224
|
|
|
225
225
|
undefinedFunctionCall(); // ERROR 4: undefined function
|
|
226
226
|
base64Encode("hello", "extra_arg"); // ERROR 5: arity mismatch
|
|
227
|
-
`,a=r.run(o);console.log(" Executed successfully?",a.success),console.log(" Formatted visual diagnostics caught BEFORE execution:");for(let
|
|
227
|
+
`,a=r.run(o);console.log(" Executed successfully?",a.success),console.log(" Formatted visual diagnostics caught BEFORE execution:");for(let g of a.diagnostics)console.log(" "+fo(g,o).split(`
|
|
228
228
|
`).join(`
|
|
229
229
|
`));!a.success&&a.diagnostics.length===5?console.log(` -> Passed! (All 5 static errors caught upfront with visual carets)
|
|
230
230
|
`):(console.error(" -> Failed! Expected 5 diagnostics, got",a.diagnostics.length),e=!1),console.log("Test Suite 4: Forward Function Declarations & Mutual Recursion");let c=r.run(`
|
|
@@ -240,7 +240,7 @@ fn clamp(val, low, high) {
|
|
|
240
240
|
if (n == 0) { return false; }
|
|
241
241
|
return even(n - 1);
|
|
242
242
|
}
|
|
243
|
-
`);c.success?(console.log(c.output.map(
|
|
243
|
+
`);c.success?(console.log(c.output.map(g=>" [out] "+g).join(`
|
|
244
244
|
`)),console.log(` -> Passed!
|
|
245
245
|
`)):(console.error(" -> Failed:",c.diagnostics),e=!1),console.log("Test Suite 5: Perl-style system() & String Operations");let d=r.run(`
|
|
246
246
|
res = system("ls -ltr");
|
|
@@ -262,9 +262,9 @@ fn clamp(val, low, high) {
|
|
|
262
262
|
print("Split fruits array:", fruits);
|
|
263
263
|
print("Joined fruits:", join(fruits, " | "));
|
|
264
264
|
print("Title Case:", title_case("hello world of scripts"));
|
|
265
|
-
`);d.success?(console.log(d.output.map(
|
|
265
|
+
`);d.success?(console.log(d.output.map(g=>" [out] "+g).join(`
|
|
266
266
|
`)),console.log(` -> Passed!
|
|
267
|
-
`)):(console.error(" -> Failed:",d.diagnostics),e=!1),console.log("Test Suite 6: JSON Parsing & Object Primitive Methods");let
|
|
267
|
+
`)):(console.error(" -> Failed:",d.diagnostics),e=!1),console.log("Test Suite 6: JSON Parsing & Object Primitive Methods");let h=r.run(`
|
|
268
268
|
res = system("echo '{\\"status\\": \\"ok\\", \\"code\\": 200, \\"users\\": [{\\"id\\": 1, \\"name\\": \\"Alice\\", \\"active\\": true}, {\\"id\\": 2, \\"name\\": \\"Bob\\", \\"active\\": false}], \\"server\\": {\\"host\\": \\"localhost\\", \\"port\\": 8080}}'");
|
|
269
269
|
|
|
270
270
|
data = json(res.stdout);
|
|
@@ -303,9 +303,9 @@ fn clamp(val, low, high) {
|
|
|
303
303
|
tags: ["json", "compiler"]
|
|
304
304
|
};
|
|
305
305
|
print("Local config dot access:", localConfig.app, "tags:", localConfig.tags[0]);
|
|
306
|
-
`);
|
|
306
|
+
`);h.success?(console.log(h.output.map(g=>" [out] "+g).join(`
|
|
307
307
|
`)),console.log(` -> Passed!
|
|
308
|
-
`)):(console.error(" -> Failed:",
|
|
308
|
+
`)):(console.error(" -> Failed:",h.diagnostics),e=!1),console.log("Test Suite 7: File I/O & Advanced Data Structures");let T=r.run(`
|
|
309
309
|
// 1. Raw file write and read
|
|
310
310
|
let tmpFile = "scratch_test.txt";
|
|
311
311
|
write_file(tmpFile, "line 1\\nline 2\\nline 3");
|
|
@@ -367,9 +367,9 @@ fn clamp(val, low, high) {
|
|
|
367
367
|
print("Has department?", has_key(userMap, "department"));
|
|
368
368
|
delete_key(userMap, "department");
|
|
369
369
|
print("After delete_key has department?", has_key(userMap, "department"));
|
|
370
|
-
`);
|
|
370
|
+
`);T.success?(console.log(T.output.map(g=>" [out] "+g).join(`
|
|
371
371
|
`)),console.log(` -> Passed!
|
|
372
|
-
`)):(console.error(" -> Failed:",
|
|
372
|
+
`)):(console.error(" -> Failed:",T.diagnostics),e=!1),console.log("Test Suite 8: Concurrency & Synchronized State Access");let p=await r.runAsync(`
|
|
373
373
|
let counter = 0;
|
|
374
374
|
let list = [];
|
|
375
375
|
let state = map();
|
|
@@ -392,46 +392,46 @@ fn clamp(val, low, high) {
|
|
|
392
392
|
assert(len(list) == 3, "list length must be 3");
|
|
393
393
|
assert(state.a == 100, "state.a must be 100");
|
|
394
394
|
assert(res1 == "a" && res2 == "b" && res3 == "c", "parallel results must match return values");
|
|
395
|
-
`);return
|
|
395
|
+
`);return p.success?(console.log(p.output.map(g=>" [out] "+g).join(`
|
|
396
396
|
`)),console.log(` -> Passed!
|
|
397
|
-
`)):(console.error(" -> Failed:",
|
|
398
|
-
`);if(e[0]!=="---")throw new
|
|
399
|
-
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=yo(i)}catch(l){if(l instanceof
|
|
400
|
-
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(Iu(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(xu(c)||!wu(c))continue;let d=vu(c);for(let
|
|
401
|
-
allowed keys: ${To.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
|
|
402
|
-
`)}){let n=
|
|
403
|
-
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=os(i,Ao(n));return{teamfile:n,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(i.session===void 0)throw new
|
|
404
|
-
Run: lmctl seed ${r}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Ao(n),isLead:Jt(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}import{existsSync as Ju,mkdirSync as Vu,readFileSync as Ku,renameSync as Yu,unlinkSync as zu,writeFileSync as Qu}from"node:fs";import{homedir as Co}from"node:os";import{dirname as Vt,join as
|
|
405
|
-
`)}catch{}}function Hu(){if(!Mr){let e=Wu().slice(0,13).replace("T","-");Mr=Fr(ds(),`debug-${e}.log`)}Uu($u(Mr),{recursive:!0})}function
|
|
406
|
-
`)){let t=e.trim();if(!t||t.startsWith("#"))continue;if(t.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(t);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function Gu(){try{let r=No(Fr(ds(),"config.json"),"utf-8"),e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Pr="lmctl",Ur="lmctl0",em={existsSync:Ju,mkdirSync:Vu,readFileSync:Ku,writeFileSync:Qu,renameSync:Yu,unlinkSync:zu},
|
|
407
|
-
`,"utf8"),
|
|
408
|
-
`)),b({event:"mcp_cleanup",path:r,removed:[...i]})}catch{}}function Lo(r,e){return r.length<2||r[0]!=="mcp_servers"?!1:e.has(r[1])}function om(r){let e=new Map,t;for(let s of r.split(/\n/)){let i=Fo(s);if(i===null)return null;if(i!==void 0){t=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=am(a,t);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Pr&&c[1]!==Ur)continue;let u=e.get(c[1])??{};if(c[2]==="command"){let d=Po(l);if(d===null)return null;u.command=d}else if(c[2]==="args"){let d=cm(l);if(d===null)return null;u.args=d}e.set(c[1],u)}let n=new Set;for(let[s,i]of e.entries())s===Pr&&$o(i.command,i.args)&&n.add(s),s===Ur&&jo(i.command,i.args)&&n.add(s);return n}function am(r,e){if(r.startsWith("mcp_servers"))return $r(r);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let t=$r(r);return t===null?null:[...e,...t]}function Fo(r){if(!/^\s*\[/.test(r))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(r);return e===null?null:$r(e[1])}function lm(r){let e=r.indexOf("=");if(e<0)return;let t=r.slice(0,e).trim();if(!(t.length===0||!t.startsWith("mcp_servers")))return $r(t)}function $r(r){let e=[],t=0,n=()=>{for(;t<r.length&&/\s/.test(r[t]);)t+=1};for(;t<r.length;){if(n(),t>=r.length)return null;if(r[t]==='"'){t+=1;let s="",i=!1;for(;t<r.length;){let o=r[t];if(o==="\\"){if(t+1>=r.length)return null;s+=r[t+1],t+=2;continue}if(o==='"'){t+=1,i=!0;break}s+=o,t+=1}if(!i)return null;e.push(s)}else{let s=t;for(;t<r.length&&/[A-Za-z0-9_-]/.test(r[t]);)t+=1;if(t===s)return null;e.push(r.slice(s,t))}if(n(),t>=r.length)break;if(r[t]!==".")return null;t+=1}return e.length>0?e:null}function Po(r){let e=Uo(r).trim();if(e.startsWith('"'))try{let t=JSON.parse(e);return typeof t=="string"?t:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function cm(r){let e=Uo(r).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let t=e.slice(1,-1).trim();if(t.length===0)return[];let n=t.split(",").map(s=>Po(s.trim()));return n.some(s=>s===null)?null:n}function Uo(r){let e;for(let t=0;t<r.length;t+=1){let n=r[t];if(e!==void 0){if(e==='"'&&n==="\\"){t+=1;continue}n===e&&(e=void 0);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return r.slice(0,t)}return r}function dm(r){return vt(r)?r.type==="stdio"&&typeof r.command=="string"&&$o(r.command,r.args):!1}function um(r){return!vt(r)||!Array.isArray(r.command)?!1:r.command.length===2&&typeof r.command[0]=="string"&&typeof r.command[1]=="string"&&Wo(r.command[0])&&r.command[1]==="mcp"||r.command.length===3&&typeof r.command[0]=="string"&&typeof r.command[1]=="string"&&typeof r.command[2]=="string"&&Bo(r.command[0],[r.command[1],r.command[2]])}function mm(r){return vt(r)?r.type==="stdio"&&jo(r.command,r.args):!1}function fm(r){return!vt(r)||!Array.isArray(r.command)?!1:r.command.length===2&&typeof r.command[0]=="string"&&typeof r.command[1]=="string"&&Ho(r.command[0])&&r.command[1]==="mcp"}function $o(r,e){return Wo(r)&&Xo(e)||Bo(r,e)}function jo(r,e){return Ho(r)&&Xo(e)}function Bo(r,e){return pm(r)&&Array.isArray(e)&&e.length===2&&hm(e[0])&&e[1]==="mcp"}function Wo(r){return typeof r=="string"&&ms(r)==="lmctl"}function Ho(r){return typeof r=="string"&&ms(r)==="lmctl0"}function pm(r){if(typeof r!="string")return!1;let e=ms(r).toLowerCase();return e==="node"||e==="node.exe"}function hm(r){if(typeof r!="string")return!1;let e=r.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function ms(r){let e=r.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function Xo(r){return Array.isArray(r)&&r.length===1&&r[0]==="mcp"}function vt(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Jo(r){let e=qo(r.registry,r.fromTeamfile);if(e===void 0)return wt(`sender team is not registered in policy graph: ${r.fromTeamfile}`);if(!Go(e,r.fromAlias))return wt(`sender alias "${r.fromAlias}" not found in ${r.fromTeamfile}`);let t=qo(r.registry,r.toTeamfile);return t===void 0?wt(`target team is not registered in policy graph: ${r.toTeamfile}`):Go(t,r.toAlias)?r.toTeamfile===r.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?wt(`sender team has no Lead: ${r.fromTeamfile}`):r.fromAlias!==e.leadAlias?wt(`cross-team sends may only originate from Lead; got "${r.fromAlias}" in ${r.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:wt(`target alias "${r.toAlias}" not found in ${r.toTeamfile}`)}function qo(r,e){return r.teams.find(t=>t.teamfile===e)}function Go(r,e){return r.aliases.some(t=>t===e)}function wt(r){return{allowed:!1,outOfPolicy:!0,reason:r}}import{basename as gm}from"node:path";var _m=6e4,Em=2,Vo=8*60*60*1e3;function Yo(r,e){let t=new Date(e.now.getTime()-It()).toISOString(),n=Zo(r,t).filter(m=>!m.sender.teamfile.startsWith("prompt:")),s=Tm(e.sender,n),i=Sm(e.sender,n);i!==null&&i.teamfile===e.root&&!Ko(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(m=>Ko(m,o)),c=l.map(m=>m.at).filter(m=>m!==null).sort((m,h)=>h-m)[0]??null,u=c!==null&&e.now.getTime()-c<_m,d=fs(e.sender,n).length;return{stop:l.length>=1&&u&&d>=Em,chain:vm(a)}}function zo(r,e){let t=new Date(e.now.getTime()-It()).toISOString(),n=Zo(r,t),s=fs(e.sender,n);if(s.length===0)return null;let i=s[0];return i.sender.teamfile.startsWith("prompt:")?i.receiver.teamfile:i.sender.teamfile}function It(r=process.env){let e=r.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Vo;let t=Number(e);return!Number.isFinite(t)||t<=0?Vo:t}function Qo(r){return`cross-team cycle detected (${r}); stopping to prevent a runaway loop.`}function ym(r){return{sender:{teamfile:r.sender_teamfile,alias:r.sender_alias},receiver:{teamfile:r.receiver_teamfile,alias:r.receiver_alias},at:Date.parse(r.started_at)}}function Zo(r,e){return r.clearAgentInflightOlderThan(e),r.listAgentInflight().map(ym).filter(t=>Number.isFinite(t.at)&&new Date(t.at).toISOString()>=e).sort((t,n)=>t.at-n.at)}function Tm(r,e,t={}){let n=new Map;for(let a of e)n.set(it(a.receiver),a);let s=[{...r,at:null}],i=r,o=new Set([it(r)]);for(let a=0;a<64;a+=1){let l=n.get(it(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:")&&t.includePromptSender!==!0)break;let u=it(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function fs(r,e){let t=it(r),n=new Set([t]),s=[t],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=it(l.sender),u=it(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(u)||(n.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function Sm(r,e){let t=fs(r,e);if(t.length===0)return null;let n=t[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Ko(r,e){return r.teamfile===e.teamfile&&r.alias===e.alias}function it(r){return`${r.teamfile}\0${r.alias}`}function vm(r){return r.map(e=>`${gm(e.teamfile)}:${e.alias}`).join(" \u2192 ")}import{randomUUID as Oa}from"node:crypto";import{existsSync as Ua,mkdirSync as Ef,renameSync as yf,rmdirSync as Tf}from"node:fs";import{hostname as xs}from"node:os";import{existsSync as wm}from"node:fs";import{createRequire as Im}from"node:module";var ps=null;function xm(){return ps===null&&(ps=Im(import.meta.url)("node:sqlite").DatabaseSync),ps}var gs=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,t={}){if(t.fileMustExist===!0&&e!==":memory:"&&!wm(e))throw new Error("unable to open database file");this.name=e,this.handle=new(xm())(e,{readOnly:t.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new _s(this.handle.prepare(e))}exec(e){this.handle.exec(e),this.updateTransactionDepth(e)}pragma(e,t){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}let s=this.prepare(n).get();return t?.simple===!0?s===void 0?void 0:Object.values(s)[0]:s}transaction(e){return(...t)=>{if(this.transactionDepth===0){this.exec("BEGIN");try{let s=e(...t);return this.exec("COMMIT"),s}catch(s){throw this.inTransaction&&this.exec("ROLLBACK"),s}}let n=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${n}`);try{let s=e(...t);return this.exec(`RELEASE ${n}`),s}catch(s){throw this.inTransaction&&(this.exec(`ROLLBACK TO ${n}`),this.exec(`RELEASE ${n}`)),s}}}get inTransaction(){return this.transactionDepth>0}close(){this.handle.close()}updateTransactionDepth(e){let t=e.trim().match(/^([A-Za-z]+)/)?.[1]?.toUpperCase();if(t!==void 0){if(t==="BEGIN"||t==="SAVEPOINT"){this.transactionDepth+=1;return}if(t==="COMMIT"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}if(t==="RELEASE"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}t==="ROLLBACK"&&!/^ROLLBACK\s+TO\b/i.test(e.trim())&&(this.transactionDepth=0)}}},jr=gs,_s=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let t=this.handle.get(...hs(e));return this.normalizeRow(t)}all(...e){return this.handle.all(...hs(e)).map(t=>this.normalizeRow(t))}run(...e){let t=this.handle.run(...hs(e));return{changes:Number(t.changes),lastInsertRowid:Number(t.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Es(e)?Object.values(e):Es(e)?{...e}:e}};function hs(r){return r.length===1&&Am(r[0])?[r[0]]:r}function Am(r){if(!Es(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}function Es(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}import{existsSync as Pm,mkdirSync as Um,readFileSync as na}from"node:fs";import{randomUUID as $m}from"node:crypto";import{homedir as jm}from"node:os";import{dirname as sa,join as Bm,resolve as ia}from"node:path";import{fileURLToPath as Wm,pathToFileURL as Hm}from"node:url";import{createHash as Nm}from"node:crypto";import{createHash as bm}from"node:crypto";function Rm(r,e,t){return bm("sha256").update(`${r}\0${e}\0${t}`).digest("hex")}function ue(r,e,t){let n=Rm(e.stream_id,e.intentKey??e.event_type,e.observedLastSeq),s=r.prepare(`INSERT INTO message_event (event_id, ts, stream_id, event_type, payload)
|
|
397
|
+
`)):(console.error(" -> Failed:",p.diagnostics),e=!1),e}async function gu(){let r=process.argv.slice(2);if(r.length===0||r.length===1&&r[0]==="--test"){await hu()||(process.exitCode=1);return}let e="Usage: lmscript.ts [--check|--dry-run|--lint] [--check-files] <file> | [check options] -e <source> | --test | --help";if(r.length===1&&r[0]==="--help"){console.log(e);return}let t=!1,n=!1;for(;["--check","--dry-run","--lint","--check-files"].includes(r[0]);)t=!0,r.shift()==="--check-files"&&(n=!0);let s=r[0]==="-e";if(s?r.length!==2:r.length!==1||r[0].startsWith("-")){console.error(e),process.exitCode=1;return}try{let i=s?void 0:se.resolve(r[0]),o=s?r[1]:O.readFileSync(i,"utf-8"),a=new Me,l=t?a.scanAndCheck(o,{checkFiles:n,file:i}):await a.runAsync(o,{file:i});if("output"in l)for(let c of l.output)console.log(c);for(let c of l.diagnostics)console.error(fo(c,o));l.diagnostics.some(c=>c.severity==="error")&&(process.exitCode=1)}catch(i){console.error(`Execution failed: ${i instanceof Error?i.message:String(i)}`),process.exitCode=1}}var co=se.basename(mo(import.meta.url));(co==="lmscript.ts"||co==="lmscript.js")&&process.argv[1]&&O.existsSync(process.argv[1])&&O.realpathSync(mo(import.meta.url))===O.realpathSync(se.resolve(process.argv[1]))&&gu();import{readFileSync as QE}from"node:fs";import{createInterface as ZE}from"node:readline";import{existsSync as Mu}from"node:fs";import{dirname as Ao}from"node:path";import{readFileSync as Eu,writeFileSync as gy,renameSync as _y,existsSync as yu}from"node:fs";import{basename as Tu,resolve as Or,dirname as ns}from"node:path";var Cr=["title","description","members"],_u=new Set(Cr),Ne=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}};function yo(r){if(r.length===0||!r.startsWith("---"))throw new Ne("frontmatter must start at line 1 with `---` on its own line");let e=r.split(`
|
|
398
|
+
`);if(e[0]!=="---")throw new Ne("frontmatter must start at line 1 with `---` on its own line");let t={},n=-1;for(let o=1;o<e.length;o++){let a=e[o];if(a==="---"){n=o;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new Ne(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!_u.has(c))throw new Ne(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Cr.join(", ")}`);t[c]=u}if(n===-1)throw new Ne("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Cr)if(t[o]===void 0)throw new Ne(`missing required frontmatter key "${o}" \u2014 required: ${Cr.join(", ")}`);let s=0;for(let o=0;o<=n;o++)s+=e[o].length+1;s>r.length&&(s=r.length);let i=t.members.split(",").map(o=>o.trim()).filter(Boolean);return{title:t.title,description:t.description,members:i,bodyOffset:s}}var Su="Lead";function vu(r){let e={},t=/(\w+)=(?:"([^"]*)"|([\S]*))/g,n;for(;(n=t.exec(r))!==null;){let s=n[1],i=n[2]!==void 0?n[2]:n[3];e[s]=i}return e}function wu(r){return/^\s*_MEMBER_\s+\S/.test(r)}function Iu(r){return/^\s*_SESSION_\s+\S/.test(r)}function xu(r){return/^\s*_SKILL_(?:\s|$)/.test(r)}function ss(r){let e=Tu(r);return e.endsWith(".lmctl")?e.slice(0,-6):e}function Gt(r){let e=Eu(r,"utf-8"),t=ns(Or(r)),n=is(e,ss(r),{baseDir:t,sourcePath:Or(r)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Or(t,s.sessiondir));return n}var To=["alias","provider","sessionid","sessiondir","teamfile","model","effort"];function is(r,e,t={}){let n=[],s=[];t.sourcePath,t.baseDir;let i=r;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
399
|
+
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=yo(i)}catch(l){if(l instanceof Ne)s.push(`frontmatter: ${l.message}`);else throw l}let a=r.split(`
|
|
400
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(Iu(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(xu(c)||!wu(c))continue;let d=vu(c);for(let h of Object.keys(d))if(!To.includes(h))throw new Error(`line ${u}: unknown key "${h}" on _MEMBER_ line: ${c.trim()}
|
|
401
|
+
allowed keys: ${To.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),n.push(m)}return{name:e,members:n,rawText:r,parseErrors:s,frontmatter:o}}function Jt(r){return r.members.find(e=>e.alias.toLowerCase()===Su.toLowerCase())}function os(r,e,t,n={}){let s=n.requireSession??!0;if(!r.teamfile)throw new Error(`Member "${r.alias}" is not a team reference`);let i=Or(e,r.teamfile),o=t??new Set;if(o.has(i))throw new Error(`Circular team reference: ${r.alias} \u2192 ${i} (already visited: ${[...o].join(" \u2192 ")})`);if(o.add(i),!yu(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${r.alias}")`);let a=Gt(i),l=Jt(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return os(l,ns(i),o,n);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||ns(i),alias:r.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function So(r,e){return r.members.find(t=>t.alias===e)??r.members.find(t=>t.alias.toLowerCase()===e.toLowerCase())}import{createHash as Au}from"node:crypto";import{existsSync as vo,readFileSync as wo,realpathSync as bu}from"node:fs";import{dirname as Ru,resolve as Io}from"node:path";var as=5,Dr=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}};function st(r,e){let t=Io(r);if(vo(t))return bu(t);if(e!==void 0){let n=ku(r,t,e);if(n!==null)return n}return t}function xo(r,e){let t=Ru(e),n=is(r,ss(e),{baseDir:t});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Io(t,s.sessiondir));return n}function St(r,e,t=n=>{process.stderr.write(`warning: ${n}
|
|
402
|
+
`)}){let n=st(r,Nu(e)?e:void 0);if(vo(n)){let i=wo(n,"utf8"),o=xo(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&&Lu(o)&&Du(e,n,o,i,t),o}let s=e?.getRootTeam(n)??null;throw s!==null?new Error(`teamfile missing on disk: ${n} (registered ${s.registered_at}; the file was renamed or deleted \u2014 seed the team at its new path)`):new Error(`teamfile not found: ${r}`)}function Nu(r){return typeof r=="object"&&r!==null&&"getRootTeam"in r&&"listRootTeams"in r}function ku(r,e,t){let n=t.getRootTeam(r)??t.getRootTeam(e);return n===null?null:n.teamfile_path}function Lu(r){return r.parseErrors.length>0?!1:r.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=as)}function Cu(r,e,t){let n=st(e),s=t.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=as);if(s.length!==0)for(let i of r.listRootTeams()){let o,a;try{if(o=st(i.teamfile_path),o===n)continue;a=wo(o,"utf8")}catch(c){if(Ou(c))continue;throw c}let l=xo(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)>=as);if(u!==void 0)throw new Dr(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${u.alias} both use sessionid "${c.session}"`)}}}function Ou(r){let e=r?.code;return e==="ENOENT"||e==="ENOTDIR"}function Du(r,e,t,n,s){try{Cu(r,e,t)}catch(o){if(!(o instanceof Dr))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:t.name,raw_text:n,raw_sha256:Au("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};r.upsertRootTeam(i)}var Se=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}};var ls=/^[A-Za-z][A-Za-z0-9_-]*$/;function Fu(r){return ls.test(r)}function cs(r){if(!r.includes(":"))return null;let e=r.lastIndexOf(":"),t=r.slice(0,e),n=r.slice(e+1);return!t.endsWith(".lmctl")||!ls.test(n)?null:{teamfile:t,alias:n}}function it(r,e,t){if(!r.endsWith(".lmctl"))throw new Se(`lmctl: "${r}" doesn't look like a teamfile (expected .lmctl extension).`);if(!Fu(e))throw new Se(`lmctl: "${e}" is not a valid alias (must match ${ls.source}).`);let n=st(r,t);if(t===void 0&&!Mu(n))throw new Se(`lmctl: teamfile not found: ${r}`);let s;try{s=St(n,t)}catch(o){throw new Se(`lmctl: ${r}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new Se(`lmctl: ${r}: ${s.parseErrors.join("; ")}`);let i=So(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new Se(`lmctl: alias "${e}" not found in ${r}.
|
|
403
|
+
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=os(i,Ao(n));return{teamfile:n,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(i.session===void 0)throw new Se(`lmctl: alias "${i.alias}" in ${r} has no session ID yet.
|
|
404
|
+
Run: lmctl seed ${r}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Ao(n),isLead:Jt(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}import{existsSync as Ju,mkdirSync as Vu,readFileSync as Ku,renameSync as Yu,unlinkSync as zu,writeFileSync as Qu}from"node:fs";import{homedir as Co}from"node:os";import{dirname as Vt,join as de,resolve as Zu}from"node:path";import{readFileSync as No,appendFileSync as Pu,mkdirSync as Uu,existsSync as Cy,readdirSync as Oy,unlinkSync as Dy}from"node:fs";import{join as Fr,dirname as $u}from"node:path";import{homedir as ju}from"node:os";var ko=!1,bo=!1,Ro=0,Bu=5e3;function ds(){return Fr(ju(),".lmctl")}function z(){if(ko||process.env.LMCTL_DEBUG==="1")return!0;let r=Date.now();return r-Ro>=Bu&&(bo=Xu(),Ro=r),bo}function Wu(){let r=new Date,e=r.getTimezoneOffset(),t=e<=0?"+":"-",n=String(Math.floor(Math.abs(e)/60)).padStart(2,"0"),s=String(Math.abs(e)%60).padStart(2,"0");return new Date(r.getTime()-e*6e4).toISOString().replace("Z",`${t}${n}:${s}`)}var Mr=null;function ge(r,e){if(e?.verbose){if(!ko)return}else if(!e?.always&&!z())return;try{Hu();let t={ts:new Date().toISOString(),pid:process.pid,vti:process.env.LMCTL_VTI??null,autocode_run_id:process.env.LMCTL_AUTOCODE_RUN_ID??void 0,...r};Pu(Mr,JSON.stringify(t)+`
|
|
405
|
+
`)}catch{}}function Hu(){if(!Mr){let e=Wu().slice(0,13).replace("T","-");Mr=Fr(ds(),`debug-${e}.log`)}Uu($u(Mr),{recursive:!0})}function _e(...r){ge({event:"legacy",msg:r.join(" ")})}function ie(...r){ge({event:"legacy",msg:r.join(" ")},{verbose:!0})}function b(r){ge(r,{always:!0})}function Xu(){return qu()||Gu()}function qu(){try{let r=No(Fr(ds(),"config.toml"),"utf-8");for(let e of r.split(`
|
|
406
|
+
`)){let t=e.trim();if(!t||t.startsWith("#"))continue;if(t.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(t);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function Gu(){try{let r=No(Fr(ds(),"config.json"),"utf-8"),e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Pr="lmctl",Ur="lmctl0",em={existsSync:Ju,mkdirSync:Vu,readFileSync:Ku,writeFileSync:Qu,renameSync:Yu,unlinkSync:zu},ve=em,us;function Oo(r,e,t){let n=Vt(Zu(t)),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??n,l=i.get(a)??new Set;l.add(o.provider),i.set(a,l)}for(let[o,a]of i.entries())ke(de(o,".mcp.json"),"mcpServers",[We(),He()]),a.has("opencode")&&ke(de(o,".opencode","opencode.json"),"mcp",[Do(),Mo()]),a.has("kimi")&&ke(de(o,".kimi-code","mcp.json"),"mcpServers",[We(),He()]);for(let o of s)sm(o)}function tm(r=us??Co()){return de(r,".copilot","mcp-config.json")}function rm(r,e){ve.mkdirSync(Vt(r),{recursive:!0});let t=de(Vt(r),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{ve.writeFileSync(t,`${JSON.stringify(e,null,2)}
|
|
407
|
+
`,"utf8"),ve.renameSync(t,r)}catch(n){try{ve.unlinkSync(t)}catch{}throw n}}function nm(r,e){ve.mkdirSync(Vt(r),{recursive:!0});let t=de(Vt(r),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{ve.writeFileSync(t,e,"utf8"),ve.renameSync(t,r)}catch(n){try{ve.unlinkSync(t)}catch{}throw n}}function ke(r,e,t){try{if(!ve.existsSync(r))return;let n=JSON.parse(ve.readFileSync(r,"utf8"));if(!vt(n)||!vt(n[e]))return;let s={...n[e]},i=[];for(let{name:o,shouldRemove:a}of t)Object.prototype.hasOwnProperty.call(s,o)&&a(s[o])&&(delete s[o],i.push(o));if(i.length===0)return;n[e]=s,rm(r,n),b({event:"mcp_cleanup",path:r,removed:i})}catch{}}function We(){return{name:Ur,shouldRemove:mm}}function Do(){return{name:Ur,shouldRemove:fm}}function He(){return{name:Pr,shouldRemove:dm}}function Mo(){return{name:Pr,shouldRemove:um}}function sm(r){let e=us??Co();switch(r){case"copilot":ke(tm(e),"mcpServers",[We(),He()]);return;case"claude":ke(de(e,".claude.json"),"mcpServers",[We(),He()]);return;case"gemini":ke(de(e,".gemini","settings.json"),"mcpServers",[We(),He()]);return;case"qwen":ke(de(e,".qwen","settings.json"),"mcpServers",[We(),He()]);return;case"agy":ke(de(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[We(),He()]);return;case"opencode":ke(de(e,".config","opencode","opencode.json"),"mcp",[Do(),Mo()]);return;case"kimi":ke(de(us===void 0?process.env.KIMI_CODE_HOME??de(e,".kimi-code"):de(e,".kimi-code"),"mcp.json"),"mcpServers",[We(),He()]);return;case"codex":im(de(e,".codex","config.toml"));return;default:return}}function im(r){try{if(!ve.existsSync(r))return;let e=ve.readFileSync(r,"utf8"),t=om(e);if(t===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=Fo(l);if(c===null)return;if(c!==void 0){if(Lo(c,t)){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=lm(l);if(u===null)return;if(u!==void 0&&Lo(u,t)){i.add(u[1]);continue}s.push(l)}if(i.size===0)return;nm(r,s.join(`
|
|
408
|
+
`)),b({event:"mcp_cleanup",path:r,removed:[...i]})}catch{}}function Lo(r,e){return r.length<2||r[0]!=="mcp_servers"?!1:e.has(r[1])}function om(r){let e=new Map,t;for(let s of r.split(/\n/)){let i=Fo(s);if(i===null)return null;if(i!==void 0){t=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=am(a,t);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Pr&&c[1]!==Ur)continue;let u=e.get(c[1])??{};if(c[2]==="command"){let d=Po(l);if(d===null)return null;u.command=d}else if(c[2]==="args"){let d=cm(l);if(d===null)return null;u.args=d}e.set(c[1],u)}let n=new Set;for(let[s,i]of e.entries())s===Pr&&$o(i.command,i.args)&&n.add(s),s===Ur&&jo(i.command,i.args)&&n.add(s);return n}function am(r,e){if(r.startsWith("mcp_servers"))return $r(r);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let t=$r(r);return t===null?null:[...e,...t]}function Fo(r){if(!/^\s*\[/.test(r))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(r);return e===null?null:$r(e[1])}function lm(r){let e=r.indexOf("=");if(e<0)return;let t=r.slice(0,e).trim();if(!(t.length===0||!t.startsWith("mcp_servers")))return $r(t)}function $r(r){let e=[],t=0,n=()=>{for(;t<r.length&&/\s/.test(r[t]);)t+=1};for(;t<r.length;){if(n(),t>=r.length)return null;if(r[t]==='"'){t+=1;let s="",i=!1;for(;t<r.length;){let o=r[t];if(o==="\\"){if(t+1>=r.length)return null;s+=r[t+1],t+=2;continue}if(o==='"'){t+=1,i=!0;break}s+=o,t+=1}if(!i)return null;e.push(s)}else{let s=t;for(;t<r.length&&/[A-Za-z0-9_-]/.test(r[t]);)t+=1;if(t===s)return null;e.push(r.slice(s,t))}if(n(),t>=r.length)break;if(r[t]!==".")return null;t+=1}return e.length>0?e:null}function Po(r){let e=Uo(r).trim();if(e.startsWith('"'))try{let t=JSON.parse(e);return typeof t=="string"?t:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function cm(r){let e=Uo(r).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let t=e.slice(1,-1).trim();if(t.length===0)return[];let n=t.split(",").map(s=>Po(s.trim()));return n.some(s=>s===null)?null:n}function Uo(r){let e;for(let t=0;t<r.length;t+=1){let n=r[t];if(e!==void 0){if(e==='"'&&n==="\\"){t+=1;continue}n===e&&(e=void 0);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return r.slice(0,t)}return r}function dm(r){return vt(r)?r.type==="stdio"&&typeof r.command=="string"&&$o(r.command,r.args):!1}function um(r){return!vt(r)||!Array.isArray(r.command)?!1:r.command.length===2&&typeof r.command[0]=="string"&&typeof r.command[1]=="string"&&Wo(r.command[0])&&r.command[1]==="mcp"||r.command.length===3&&typeof r.command[0]=="string"&&typeof r.command[1]=="string"&&typeof r.command[2]=="string"&&Bo(r.command[0],[r.command[1],r.command[2]])}function mm(r){return vt(r)?r.type==="stdio"&&jo(r.command,r.args):!1}function fm(r){return!vt(r)||!Array.isArray(r.command)?!1:r.command.length===2&&typeof r.command[0]=="string"&&typeof r.command[1]=="string"&&Ho(r.command[0])&&r.command[1]==="mcp"}function $o(r,e){return Wo(r)&&Xo(e)||Bo(r,e)}function jo(r,e){return Ho(r)&&Xo(e)}function Bo(r,e){return pm(r)&&Array.isArray(e)&&e.length===2&&hm(e[0])&&e[1]==="mcp"}function Wo(r){return typeof r=="string"&&ms(r)==="lmctl"}function Ho(r){return typeof r=="string"&&ms(r)==="lmctl0"}function pm(r){if(typeof r!="string")return!1;let e=ms(r).toLowerCase();return e==="node"||e==="node.exe"}function hm(r){if(typeof r!="string")return!1;let e=r.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function ms(r){let e=r.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function Xo(r){return Array.isArray(r)&&r.length===1&&r[0]==="mcp"}function vt(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Jo(r){let e=qo(r.registry,r.fromTeamfile);if(e===void 0)return wt(`sender team is not registered in policy graph: ${r.fromTeamfile}`);if(!Go(e,r.fromAlias))return wt(`sender alias "${r.fromAlias}" not found in ${r.fromTeamfile}`);let t=qo(r.registry,r.toTeamfile);return t===void 0?wt(`target team is not registered in policy graph: ${r.toTeamfile}`):Go(t,r.toAlias)?r.toTeamfile===r.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?wt(`sender team has no Lead: ${r.fromTeamfile}`):r.fromAlias!==e.leadAlias?wt(`cross-team sends may only originate from Lead; got "${r.fromAlias}" in ${r.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:wt(`target alias "${r.toAlias}" not found in ${r.toTeamfile}`)}function qo(r,e){return r.teams.find(t=>t.teamfile===e)}function Go(r,e){return r.aliases.some(t=>t===e)}function wt(r){return{allowed:!1,outOfPolicy:!0,reason:r}}import{basename as gm}from"node:path";var _m=6e4,Em=2,Vo=8*60*60*1e3;function Yo(r,e){let t=new Date(e.now.getTime()-It()).toISOString(),n=Zo(r,t).filter(h=>!h.sender.teamfile.startsWith("prompt:")),s=Tm(e.sender,n),i=Sm(e.sender,n);i!==null&&i.teamfile===e.root&&!Ko(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(h=>Ko(h,o)),c=l.map(h=>h.at).filter(h=>h!==null).sort((h,f)=>f-h)[0]??null,u=c!==null&&e.now.getTime()-c<_m,d=fs(e.sender,n).length;return{stop:l.length>=1&&u&&d>=Em,chain:vm(a)}}function zo(r,e){let t=new Date(e.now.getTime()-It()).toISOString(),n=Zo(r,t),s=fs(e.sender,n);if(s.length===0)return null;let i=s[0];return i.sender.teamfile.startsWith("prompt:")?i.receiver.teamfile:i.sender.teamfile}function It(r=process.env){let e=r.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Vo;let t=Number(e);return!Number.isFinite(t)||t<=0?Vo:t}function Qo(r){return`cross-team cycle detected (${r}); stopping to prevent a runaway loop.`}function ym(r){return{sender:{teamfile:r.sender_teamfile,alias:r.sender_alias},receiver:{teamfile:r.receiver_teamfile,alias:r.receiver_alias},at:Date.parse(r.started_at)}}function Zo(r,e){return r.clearAgentInflightOlderThan(e),r.listAgentInflight().map(ym).filter(t=>Number.isFinite(t.at)&&new Date(t.at).toISOString()>=e).sort((t,n)=>t.at-n.at)}function Tm(r,e,t={}){let n=new Map;for(let a of e)n.set(ot(a.receiver),a);let s=[{...r,at:null}],i=r,o=new Set([ot(r)]);for(let a=0;a<64;a+=1){let l=n.get(ot(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:")&&t.includePromptSender!==!0)break;let u=ot(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function fs(r,e){let t=ot(r),n=new Set([t]),s=[t],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=ot(l.sender),u=ot(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(u)||(n.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function Sm(r,e){let t=fs(r,e);if(t.length===0)return null;let n=t[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Ko(r,e){return r.teamfile===e.teamfile&&r.alias===e.alias}function ot(r){return`${r.teamfile}\0${r.alias}`}function vm(r){return r.map(e=>`${gm(e.teamfile)}:${e.alias}`).join(" \u2192 ")}import{randomUUID as Oa}from"node:crypto";import{existsSync as Ua,mkdirSync as Ef,renameSync as yf,rmdirSync as Tf}from"node:fs";import{hostname as xs}from"node:os";import{existsSync as wm}from"node:fs";import{createRequire as Im}from"node:module";var ps=null;function xm(){return ps===null&&(ps=Im(import.meta.url)("node:sqlite").DatabaseSync),ps}var gs=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,t={}){if(t.fileMustExist===!0&&e!==":memory:"&&!wm(e))throw new Error("unable to open database file");this.name=e,this.handle=new(xm())(e,{readOnly:t.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new _s(this.handle.prepare(e))}exec(e){this.handle.exec(e),this.updateTransactionDepth(e)}pragma(e,t){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}let s=this.prepare(n).get();return t?.simple===!0?s===void 0?void 0:Object.values(s)[0]:s}transaction(e){return(...t)=>{if(this.transactionDepth===0){this.exec("BEGIN");try{let s=e(...t);return this.exec("COMMIT"),s}catch(s){throw this.inTransaction&&this.exec("ROLLBACK"),s}}let n=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${n}`);try{let s=e(...t);return this.exec(`RELEASE ${n}`),s}catch(s){throw this.inTransaction&&(this.exec(`ROLLBACK TO ${n}`),this.exec(`RELEASE ${n}`)),s}}}get inTransaction(){return this.transactionDepth>0}close(){this.handle.close()}updateTransactionDepth(e){let t=e.trim().match(/^([A-Za-z]+)/)?.[1]?.toUpperCase();if(t!==void 0){if(t==="BEGIN"||t==="SAVEPOINT"){this.transactionDepth+=1;return}if(t==="COMMIT"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}if(t==="RELEASE"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}t==="ROLLBACK"&&!/^ROLLBACK\s+TO\b/i.test(e.trim())&&(this.transactionDepth=0)}}},jr=gs,_s=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let t=this.handle.get(...hs(e));return this.normalizeRow(t)}all(...e){return this.handle.all(...hs(e)).map(t=>this.normalizeRow(t))}run(...e){let t=this.handle.run(...hs(e));return{changes:Number(t.changes),lastInsertRowid:Number(t.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Es(e)?Object.values(e):Es(e)?{...e}:e}};function hs(r){return r.length===1&&Am(r[0])?[r[0]]:r}function Am(r){if(!Es(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}function Es(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}import{existsSync as Pm,mkdirSync as Um,readFileSync as na}from"node:fs";import{randomUUID as $m}from"node:crypto";import{homedir as jm}from"node:os";import{dirname as sa,join as Bm,resolve as ia}from"node:path";import{fileURLToPath as Wm,pathToFileURL as Hm}from"node:url";import{createHash as Nm}from"node:crypto";import{createHash as bm}from"node:crypto";function Rm(r,e,t){return bm("sha256").update(`${r}\0${e}\0${t}`).digest("hex")}function ue(r,e,t){let n=Rm(e.stream_id,e.intentKey??e.event_type,e.observedLastSeq),s=r.prepare(`INSERT INTO message_event (event_id, ts, stream_id, event_type, payload)
|
|
409
409
|
VALUES (?, ?, ?, ?, ?)
|
|
410
|
-
ON CONFLICT(event_id) DO NOTHING`),i=r.prepare("SELECT seq FROM message_event WHERE event_id = ?");return r.transaction(()=>{let a=s.run(n,e.ts??new Date().toISOString(),e.stream_id,e.event_type,JSON.stringify(e.payload));if(a.changes===0)return{appended:!1,seq:i.get(n).seq,event_id:n};let l=Number(a.lastInsertRowid);return t(l),{appended:!0,seq:l,event_id:n}})()}var
|
|
410
|
+
ON CONFLICT(event_id) DO NOTHING`),i=r.prepare("SELECT seq FROM message_event WHERE event_id = ?");return r.transaction(()=>{let a=s.run(n,e.ts??new Date().toISOString(),e.stream_id,e.event_type,JSON.stringify(e.payload));if(a.changes===0)return{appended:!1,seq:i.get(n).seq,event_id:n};let l=Number(a.lastInsertRowid);return t(l),{appended:!0,seq:l,event_id:n}})()}var H={CREATE:"CREATE",ENQUEUE:"ENQUEUE",DELIVER_CLAIM:"DELIVER_CLAIM",DELIVER_CLAIM_RELEASE:"DELIVER_CLAIM_RELEASE",DELIVERED:"DELIVERED",HANDLED:"HANDLED",WAIT_REGISTER:"WAIT_REGISTER",RESPONSE_CREATE:"RESPONSE_CREATE",RESPONSE_ENQUEUE:"RESPONSE_ENQUEUE",RESPONSE_DELIVERED:"RESPONSE_DELIVERED",INFLIGHT_TAKE:"INFLIGHT_TAKE",INFLIGHT_RELEASE:"INFLIGHT_RELEASE",INFLIGHT_RECLAIM:"INFLIGHT_RECLAIM",TERMINAL_LOCK_TAKE:"TERMINAL_LOCK_TAKE",TERMINAL_LOCK_RELEASE:"TERMINAL_LOCK_RELEASE",TERMINAL_LOCK_EXPIRE:"TERMINAL_LOCK_EXPIRE",INVOCATION_START:"INVOCATION_START",INVOCATION_FINISH:"INVOCATION_FINISH",INVOCATION_NOTIFY_CLAIM:"INVOCATION_NOTIFY_CLAIM"};function at(r,e){return r==null?null:{teamfile:r,alias:e??""}}function km(r,e,t){return`lease_${Nm("sha256").update(`${r}\0${e}\0${t}`).digest("hex").slice(0,16)}`}function Br(r,e,t,n){t.forEach((s,i)=>{ue(r,{stream_id:e,event_type:s.event_type,payload:s.payload,observedLastSeq:i,ts:s.ts},()=>{}).appended?n.appended+=1:n.skipped+=1})}function Lm(r){let e=`msg_tcl_${r.id}`,t=at(r.sender_teamfile,r.sender_alias),n=at(r.receiver_teamfile,r.receiver_alias),s={table:"team_chat_log",id:r.id},i={message_id:e,sender:t,receiver:n,root_teamfile:r.root_teamfile,legacy:s},o=[{event_type:H.CREATE,ts:r.created_at,payload:{...i,message_type:"request",content:r.message,origin:r.origin,correlation_status:"legacy-unavailable"}}];return r.status!=="running"&&o.push({event_type:H.HANDLED,ts:r.created_at,payload:{...i,outcome:r.status,receipt:r.response,error:r.error_detail,truncated:r.truncated===1}}),{streamId:e,events:o}}function Cm(r){let e=`msg_mbx_${r.id}`,t=at(r.sender_teamfile,r.sender_alias),n=at(r.receiver_teamfile,r.receiver_alias),s={table:"agent_mailbox",id:r.id},i={message_id:e,sender:t,receiver:n,root_teamfile:r.root_teamfile,legacy:s},o=[];if(r.message_type==="response"){let a=r.request_mailbox_id!==null?`msg_mbx_${r.request_mailbox_id}`:null;return o.push({event_type:H.RESPONSE_CREATE,ts:r.created_at,payload:{...i,message_type:"response",content:r.payload,in_reply_to_message_id:a,correlation_status:"legacy-unavailable"}}),o.push({event_type:H.RESPONSE_ENQUEUE,ts:r.created_at,payload:{...i,message_type:"response",in_reply_to_message_id:a}}),r.delivered_at!==null&&o.push({event_type:H.RESPONSE_DELIVERED,ts:r.delivered_at,payload:{...i,message_type:"response",receipt:r.receipt}}),{streamId:e,events:o}}return o.push({event_type:H.CREATE,ts:r.created_at,payload:{...i,message_type:"request",content:r.payload,correlation_status:"legacy-unavailable"}}),o.push({event_type:H.ENQUEUE,ts:r.created_at,payload:{...i,message_type:"request"}}),r.waited_at!==null&&o.push({event_type:H.WAIT_REGISTER,ts:r.waited_at,payload:{...i,waited_by:r.waited_by}}),(r.delivering_at!==null||r.delivery_holder_pid!==null)&&o.push({event_type:H.DELIVER_CLAIM,ts:r.delivering_at??r.created_at,payload:{...i,pid:r.delivery_holder_pid,host:r.delivery_holder_host}}),r.delivered_at!==null&&o.push({event_type:H.DELIVERED,ts:r.delivered_at,payload:{...i,receipt:r.receipt}}),{streamId:e,events:o}}function Om(r){let e=`inv_${r.id}`,t=at(r.target_teamfile,r.target_alias),n={table:"tracked_invocation",id:r.id},s=[{event_type:H.INVOCATION_START,ts:r.started_at,payload:{invocation_id:e,kind:r.kind,origin:r.origin,launch_source:r.launch_source,from_identity:r.from_identity,target:t,root_teamfile:r.root_teamfile,scope_teamfile:r.scope_teamfile,cwd:r.cwd,command:r.command,request_payload:r.request_payload,started_at:r.started_at,request_message_id:r.team_chat_log_id!==null?`msg_tcl_${r.team_chat_log_id}`:null,holder_pid:r.holder_pid,holder_host:r.holder_host,legacy:n}}];return r.notified_by!==null&&s.push({event_type:H.INVOCATION_NOTIFY_CLAIM,ts:r.notified_at??r.started_at,payload:{invocation_id:e,notified_by:r.notified_by,notified_at:r.notified_at,legacy:n}}),r.status!=="running"&&s.push({event_type:H.INVOCATION_FINISH,ts:r.ended_at??r.started_at,payload:{invocation_id:e,status:r.status,ended_at:r.ended_at,exit_code:r.exit_code,signal:r.signal,result_summary:r.result_summary,error:r.error,legacy:n}}),{streamId:e,events:s}}function Dm(r){let e=km(r.receiver_teamfile,r.receiver_alias,r.started_at),t=at(r.receiver_teamfile,r.receiver_alias),n=at(r.sender_teamfile,r.sender_alias);return{streamId:e,events:[{event_type:H.INFLIGHT_TAKE,ts:r.started_at,payload:{lease_id:e,receiver:t,sender:n,holder_pid:r.holder_pid,holder_host:null,started_at:r.started_at,legacy:{table:"agent_inflight",receiver_teamfile:r.receiver_teamfile,receiver_alias:r.receiver_alias}}}]}}function Wr(r,e){return r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ea(r){let e={appended:0,skipped:0},t={team_chat_log:0,agent_mailbox:0,tracked_invocation:0,agent_inflight:0};r.transaction(()=>{if(Wr(r,"team_chat_log"))for(let i of r.prepare("SELECT * FROM team_chat_log ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=Lm(i);Br(r,a,l,e),t.team_chat_log+=e.appended+e.skipped-o}if(Wr(r,"agent_mailbox"))for(let i of r.prepare("SELECT * FROM agent_mailbox ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=Cm(i);Br(r,a,l,e),t.agent_mailbox+=e.appended+e.skipped-o}if(Wr(r,"tracked_invocation"))for(let i of r.prepare("SELECT * FROM tracked_invocation ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=Om(i);Br(r,a,l,e),t.tracked_invocation+=e.appended+e.skipped-o}if(Wr(r,"agent_inflight"))for(let i of r.prepare("SELECT * FROM agent_inflight ORDER BY receiver_teamfile, receiver_alias").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=Dm(i);Br(r,a,l,e),t.agent_inflight+=e.appended+e.skipped-o}Mm(r)})();let s=i=>r.prepare(`SELECT count(*) AS n FROM ${i}`).get().n;return{appended:e.appended,skipped:e.skipped,bySource:t,projections:{agent_state:s("agent_state"),message_pending:s("message_pending"),invocation_state:s("invocation_state")}}}function Mm(r){r.exec("DELETE FROM agent_state"),r.exec("DELETE FROM message_pending"),r.exec("DELETE FROM invocation_state");let e=r.prepare("SELECT seq, stream_id, event_type, payload FROM message_event ORDER BY seq").all();for(let t of e){let n=JSON.parse(t.payload);Fm(r,t.seq,t.stream_id,t.event_type,n)}}function re(r,e,t){let n=r[e];return n!=null?n[t]??null:null}function Fm(r,e,t,n,s){switch(n){case H.ENQUEUE:case H.RESPONSE_ENQUEUE:{let i=n===H.RESPONSE_ENQUEUE;r.prepare(`INSERT INTO message_pending
|
|
411
411
|
(message_id, message_type, in_reply_to, sender_teamfile, sender_alias,
|
|
412
412
|
receiver_teamfile, receiver_alias, lifecycle_state, created_seq, last_seq)
|
|
413
413
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)
|
|
414
|
-
ON CONFLICT(message_id) DO UPDATE SET lifecycle_state='queued', last_seq=excluded.last_seq`).run(t,i?"response":"request",i?s.in_reply_to_message_id??null:null,re(s,"sender","teamfile"),re(s,"sender","alias"),re(s,"receiver","teamfile"),re(s,"receiver","alias"),e,e);break}case
|
|
415
|
-
WHERE message_id=?`).run(s.lease_id??null,s.pid??null,e,t);break;case
|
|
414
|
+
ON CONFLICT(message_id) DO UPDATE SET lifecycle_state='queued', last_seq=excluded.last_seq`).run(t,i?"response":"request",i?s.in_reply_to_message_id??null:null,re(s,"sender","teamfile"),re(s,"sender","alias"),re(s,"receiver","teamfile"),re(s,"receiver","alias"),e,e);break}case H.DELIVER_CLAIM:r.prepare(`UPDATE message_pending SET lifecycle_state='claimed', delivery_lease_id=?, delivery_holder_pid=?, last_seq=?
|
|
415
|
+
WHERE message_id=?`).run(s.lease_id??null,s.pid??null,e,t);break;case H.DELIVER_CLAIM_RELEASE:r.prepare(`UPDATE message_pending
|
|
416
416
|
SET lifecycle_state='queued', delivery_lease_id=NULL,
|
|
417
417
|
delivery_holder_pid=NULL, last_seq=?
|
|
418
|
-
WHERE message_id=?`).run(e,t);break;case
|
|
418
|
+
WHERE message_id=?`).run(e,t);break;case H.DELIVERED:case H.RESPONSE_DELIVERED:r.prepare("DELETE FROM message_pending WHERE message_id=?").run(t);break;case H.INFLIGHT_TAKE:r.prepare(`INSERT INTO agent_state
|
|
419
419
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias, holder_pid, holder_host, started_at, last_seq)
|
|
420
420
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
421
421
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
422
422
|
lease_id=excluded.lease_id, sender_teamfile=excluded.sender_teamfile, sender_alias=excluded.sender_alias,
|
|
423
|
-
holder_pid=excluded.holder_pid, holder_host=excluded.holder_host, started_at=excluded.started_at, last_seq=excluded.last_seq`).run(re(s,"receiver","teamfile"),re(s,"receiver","alias"),s.lease_id??null,re(s,"sender","teamfile"),re(s,"sender","alias"),s.holder_pid??null,s.holder_host??null,s.started_at??null,e);break;case
|
|
424
|
-
WHERE receiver_teamfile=? AND receiver_alias=?`).run(s.lease_id??null,re(s,"sender","teamfile"),re(s,"sender","alias"),s.holder_pid??null,s.holder_host??null,e,re(s,"receiver","teamfile"),re(s,"receiver","alias"));break;case
|
|
423
|
+
holder_pid=excluded.holder_pid, holder_host=excluded.holder_host, started_at=excluded.started_at, last_seq=excluded.last_seq`).run(re(s,"receiver","teamfile"),re(s,"receiver","alias"),s.lease_id??null,re(s,"sender","teamfile"),re(s,"sender","alias"),s.holder_pid??null,s.holder_host??null,s.started_at??null,e);break;case H.INFLIGHT_RELEASE:r.prepare("DELETE FROM agent_state WHERE receiver_teamfile=? AND receiver_alias=? AND terminal_lock_id IS NULL AND terminal_invocation_id IS NULL").run(re(s,"receiver","teamfile"),re(s,"receiver","alias"));break;case H.INFLIGHT_RECLAIM:r.prepare(`UPDATE agent_state SET lease_id=?, sender_teamfile=?, sender_alias=?, holder_pid=?, holder_host=?, last_seq=?
|
|
424
|
+
WHERE receiver_teamfile=? AND receiver_alias=?`).run(s.lease_id??null,re(s,"sender","teamfile"),re(s,"sender","alias"),s.holder_pid??null,s.holder_host??null,e,re(s,"receiver","teamfile"),re(s,"receiver","alias"));break;case H.TERMINAL_LOCK_TAKE:r.prepare(`INSERT INTO agent_state
|
|
425
425
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
426
426
|
VALUES (?, ?, ?, ?)
|
|
427
427
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
428
|
-
terminal_lock_id=excluded.terminal_lock_id, last_seq=excluded.last_seq`).run(re(s,"receiver","teamfile"),re(s,"receiver","alias"),s.lock_id??t,e);break;case
|
|
429
|
-
WHERE receiver_teamfile=? AND receiver_alias=?`).run(e,re(s,"receiver","teamfile"),re(s,"receiver","alias"));break;case
|
|
428
|
+
terminal_lock_id=excluded.terminal_lock_id, last_seq=excluded.last_seq`).run(re(s,"receiver","teamfile"),re(s,"receiver","alias"),s.lock_id??t,e);break;case H.TERMINAL_LOCK_RELEASE:case H.TERMINAL_LOCK_EXPIRE:r.prepare(`UPDATE agent_state SET terminal_lock_id=NULL, last_seq=?
|
|
429
|
+
WHERE receiver_teamfile=? AND receiver_alias=?`).run(e,re(s,"receiver","teamfile"),re(s,"receiver","alias"));break;case H.INVOCATION_START:r.prepare(`INSERT INTO invocation_state
|
|
430
430
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias, root_teamfile,
|
|
431
431
|
cwd, command, request_message_id, request_payload, holder_pid, holder_host, status, started_at, last_seq)
|
|
432
432
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)
|
|
433
|
-
ON CONFLICT(invocation_id) DO NOTHING`).run(t,s.kind??"chat",s.origin??"unknown",s.launch_source??"",s.from_identity??"",re(s,"target","teamfile"),re(s,"target","alias"),s.root_teamfile??null,s.cwd??null,s.command??null,s.request_message_id??null,s.request_payload??null,s.holder_pid??null,s.holder_host??null,s.started_at??"",e);break;case
|
|
434
|
-
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,t);break;case
|
|
433
|
+
ON CONFLICT(invocation_id) DO NOTHING`).run(t,s.kind??"chat",s.origin??"unknown",s.launch_source??"",s.from_identity??"",re(s,"target","teamfile"),re(s,"target","alias"),s.root_teamfile??null,s.cwd??null,s.command??null,s.request_message_id??null,s.request_payload??null,s.holder_pid??null,s.holder_host??null,s.started_at??"",e);break;case H.INVOCATION_FINISH:r.prepare(`UPDATE invocation_state SET status=?, ended_at=?, result_summary=?, error=?, last_seq=?
|
|
434
|
+
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,t);break;case H.INVOCATION_NOTIFY_CLAIM:r.prepare("UPDATE invocation_state SET notified_by=?, notified_at=?, last_seq=? WHERE invocation_id=?").run(s.notified_by??null,s.notified_at??null,e,t);break;default:break}}var oa=sa(Wm(import.meta.url)),aa=ia(oa,"schema.sql"),Xm=ia(oa,"migrations"),qe=61,Kt=class extends Error{dbPath;dbVersion;buildVersion;constructor(e,t,n=qe){super(`${e}: state.db is v${t}; this build understands v${n} -- refusing to proceed rather than risk misreading newer data or corrupting it. Update: npm install -g @lmctl-ai/lmctl@latest -- or, only if you must run THIS exact build against this db right now, re-run with --allow-schema-skew (best-effort; newer data/features may be invisible).`),this.name="SchemaSkewError",this.dbPath=e,this.dbVersion=t,this.buildVersion=n}};function Hr(r){r.dbPath!==":memory:"&&Um(sa(r.dbPath),{recursive:!0});let e=new jr(r.dbPath);try{e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let t=la(e),n=r.buildVersionForTests??qe;if(t===0)e.exec(na(aa,"utf8")),e.pragma(`user_version = ${qe}`);else if(t>n){let s=Jm(e,t);if(Km={dbVersion:t,buildVersion:n},s>n&&!r.allowSchemaSkew)throw e.close(),new Kt(r.dbPath,t,n);return Vm(r.dbPath,t,n),e}return qm(e,t),Gm(e),e}catch(t){try{e.close()}catch{}throw t}}function qm(r,e){let t=e;if(t<2&&t!==0&&(r.exec(`
|
|
435
435
|
CREATE TABLE IF NOT EXISTS session_size (
|
|
436
436
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
437
437
|
team_name TEXT NOT NULL,
|
|
@@ -508,7 +508,7 @@ fn clamp(val, low, high) {
|
|
|
508
508
|
);
|
|
509
509
|
CREATE INDEX IF NOT EXISTS idx_pr_followup_event_pr ON pr_followup_event(submitted_pr_id);
|
|
510
510
|
CREATE INDEX IF NOT EXISTS idx_pr_followup_event_kind ON pr_followup_event(event_kind);
|
|
511
|
-
`),r.pragma("user_version = 7"),t=7),t<8&&t!==0&&(r.prepare("PRAGMA table_info(step_artifact)").all().some(s=>s.name==="provider_call_mode")||r.exec("ALTER TABLE step_artifact ADD COLUMN provider_call_mode TEXT"),r.pragma("user_version = 8"),t=8),t<9&&t!==0){let n=
|
|
511
|
+
`),r.pragma("user_version = 7"),t=7),t<8&&t!==0&&(r.prepare("PRAGMA table_info(step_artifact)").all().some(s=>s.name==="provider_call_mode")||r.exec("ALTER TABLE step_artifact ADD COLUMN provider_call_mode TEXT"),r.pragma("user_version = 8"),t=8),t<9&&t!==0){let n=B(r,"team_member");n.has("state")||r.exec("ALTER TABLE team_member ADD COLUMN state TEXT NOT NULL DEFAULT 'idle' CHECK(state IN ('idle','in_chat','attention_needed','retired'))"),n.has("state_reason")||r.exec("ALTER TABLE team_member ADD COLUMN state_reason TEXT"),n.has("state_updated_at")||r.exec("ALTER TABLE team_member ADD COLUMN state_updated_at TEXT"),n.has("role_prompt")||r.exec("ALTER TABLE team_member ADD COLUMN role_prompt TEXT"),n.has("prompt_snapshot")||r.exec("ALTER TABLE team_member ADD COLUMN prompt_snapshot TEXT"),B(r,"team").has("lead_seed_prompt")||r.exec("ALTER TABLE team ADD COLUMN lead_seed_prompt TEXT"),B(r,"run").has("parent_run_id")||r.exec("ALTER TABLE run ADD COLUMN parent_run_id INTEGER REFERENCES run(id)"),B(r,"project").has("memory_mode")||r.exec("ALTER TABLE project ADD COLUMN memory_mode TEXT NOT NULL DEFAULT 'folder' CHECK(memory_mode IN ('folder','db'))"),r.pragma("user_version = 9"),t=9}if(t<10&&t!==0&&(r.exec(`
|
|
512
512
|
CREATE TABLE IF NOT EXISTS memory (
|
|
513
513
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
514
514
|
project_id INTEGER NOT NULL REFERENCES project(id),
|
|
@@ -597,7 +597,7 @@ fn clamp(val, low, high) {
|
|
|
597
597
|
UNIQUE(workflow_id, version)
|
|
598
598
|
);
|
|
599
599
|
CREATE INDEX IF NOT EXISTS idx_workflow_version_wf ON workflow_version(workflow_id, version DESC);
|
|
600
|
-
`),
|
|
600
|
+
`),B(r,"workflow").has("active_version_id")||r.exec("ALTER TABLE workflow ADD COLUMN active_version_id INTEGER REFERENCES workflow_version(id)"),B(r,"run").has("workflow_version_id")||r.exec("ALTER TABLE run ADD COLUMN workflow_version_id INTEGER REFERENCES workflow_version(id)"),r.pragma("user_version = 15"),t=15),t<16&&t!==0&&(r.exec(`
|
|
601
601
|
CREATE TABLE IF NOT EXISTS trigger_instance (
|
|
602
602
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
603
603
|
workflow_id INTEGER NOT NULL REFERENCES workflow(id),
|
|
@@ -614,7 +614,7 @@ fn clamp(val, low, high) {
|
|
|
614
614
|
);
|
|
615
615
|
CREATE INDEX IF NOT EXISTS idx_trigger_instance_wf ON trigger_instance(workflow_id);
|
|
616
616
|
CREATE INDEX IF NOT EXISTS idx_trigger_instance_enabled ON trigger_instance(enabled) WHERE enabled = 1;
|
|
617
|
-
`),
|
|
617
|
+
`),B(r,"step").has("parent_step_id")||r.exec("ALTER TABLE step ADD COLUMN parent_step_id INTEGER REFERENCES step(id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_step_parent ON step(parent_step_id)"),r.pragma("user_version = 16"),t=16),t<17&&t!==0&&(r.exec(`
|
|
618
618
|
CREATE TABLE IF NOT EXISTS project_workflow (
|
|
619
619
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
620
620
|
project_id INTEGER NOT NULL REFERENCES project(id),
|
|
@@ -627,7 +627,7 @@ fn clamp(val, low, high) {
|
|
|
627
627
|
UNIQUE(project_id, workflow_id, condition)
|
|
628
628
|
);
|
|
629
629
|
CREATE INDEX IF NOT EXISTS idx_project_workflow_project ON project_workflow(project_id, enabled);
|
|
630
|
-
`),
|
|
630
|
+
`),B(r,"job").has("workflow_id_override")||r.exec("ALTER TABLE job ADD COLUMN workflow_id_override INTEGER REFERENCES workflow(id)"),r.pragma("user_version = 17"),t=17),t<18&&t!==0&&(r.exec(`
|
|
631
631
|
CREATE TABLE IF NOT EXISTS project_issue (
|
|
632
632
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
633
633
|
project_id INTEGER NOT NULL REFERENCES project(id),
|
|
@@ -689,7 +689,7 @@ fn clamp(val, low, high) {
|
|
|
689
689
|
value TEXT NOT NULL,
|
|
690
690
|
updated_at TEXT NOT NULL
|
|
691
691
|
);
|
|
692
|
-
`),r.pragma("user_version = 20"),t=20),t<21&&t!==0){let n=
|
|
692
|
+
`),r.pragma("user_version = 20"),t=20),t<21&&t!==0){let n=B(r,"project");n.has("active_run_id")||r.exec("ALTER TABLE project ADD COLUMN active_run_id INTEGER REFERENCES run(id)"),n.has("active_locked_at")||r.exec("ALTER TABLE project ADD COLUMN active_locked_at TEXT"),n.has("active_locked_by")||r.exec("ALTER TABLE project ADD COLUMN active_locked_by TEXT"),r.pragma("user_version = 21"),t=21}if(t<22&&t!==0&&(B(r,"project").has("active_locked_expires_at")||r.exec("ALTER TABLE project ADD COLUMN active_locked_expires_at TEXT"),r.exec("CREATE INDEX IF NOT EXISTS idx_project_active_lock_expires ON project(active_locked_expires_at) WHERE active_locked_expires_at IS NOT NULL"),r.pragma("user_version = 22"),t=22),t<23&&t!==0){r.exec("DROP INDEX IF EXISTS idx_project_active_lock_expires");let n=B(r,"project");n.has("active_locked_expires_at")&&r.exec("ALTER TABLE project DROP COLUMN active_locked_expires_at"),n.has("active_locked_by")&&r.exec("ALTER TABLE project DROP COLUMN active_locked_by"),n.has("active_locked_at")&&r.exec("ALTER TABLE project DROP COLUMN active_locked_at"),n.has("active_run_id")&&r.exec("ALTER TABLE project DROP COLUMN active_run_id"),r.pragma("user_version = 23"),t=23}if(t<24&&t!==0){let n=B(r,"team_member");n.size>0&&!n.has("provider_resolved")&&r.exec("ALTER TABLE team_member ADD COLUMN provider_resolved TEXT"),r.pragma("user_version = 24"),t=24}if(t<25&&t!==0&&(r.exec(`
|
|
693
693
|
CREATE TABLE IF NOT EXISTS composition_unit (
|
|
694
694
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
695
695
|
name TEXT NOT NULL,
|
|
@@ -702,7 +702,7 @@ fn clamp(val, low, high) {
|
|
|
702
702
|
UNIQUE(name, version)
|
|
703
703
|
);
|
|
704
704
|
CREATE INDEX IF NOT EXISTS idx_composition_unit_name ON composition_unit(name, version DESC);
|
|
705
|
-
`),r.pragma("user_version = 25"),t=25),t<26&&t!==0){let n=
|
|
705
|
+
`),r.pragma("user_version = 25"),t=25),t<26&&t!==0){let n=B(r,"workflow");n.size>0&&!n.has("source_uri")&&r.exec("ALTER TABLE workflow ADD COLUMN source_uri TEXT"),n.size>0&&!n.has("source_sha256")&&r.exec("ALTER TABLE workflow ADD COLUMN source_sha256 TEXT"),r.pragma("user_version = 26"),t=26}if(t<27&&t!==0){let n=B(r,"run");n.size>0&&!n.has("pending_escalation_decision")&&r.exec("ALTER TABLE run ADD COLUMN pending_escalation_decision TEXT"),r.pragma("user_version = 27"),t=27}if(t<28&&t!==0&&(r.exec(`
|
|
706
706
|
CREATE TABLE IF NOT EXISTS prompt_dispatch (
|
|
707
707
|
prompt_id TEXT PRIMARY KEY,
|
|
708
708
|
project_id INTEGER NOT NULL REFERENCES project(id),
|
|
@@ -781,7 +781,7 @@ fn clamp(val, low, high) {
|
|
|
781
781
|
started_at TEXT NOT NULL,
|
|
782
782
|
PRIMARY KEY(receiver_teamfile, receiver_alias)
|
|
783
783
|
);
|
|
784
|
-
`),r.pragma("user_version = 32"),t=32),t<33&&t!==0&&(
|
|
784
|
+
`),r.pragma("user_version = 32"),t=32),t<33&&t!==0&&(B(r,"mailbox_cursor").has("mailbox_key")?r.exec(`
|
|
785
785
|
CREATE TABLE IF NOT EXISTS mailbox_cursor_v33 (
|
|
786
786
|
user_id TEXT NOT NULL,
|
|
787
787
|
mailbox_key TEXT NOT NULL,
|
|
@@ -834,7 +834,7 @@ fn clamp(val, low, high) {
|
|
|
834
834
|
last_pushed_id INTEGER NOT NULL,
|
|
835
835
|
updated_at TEXT NOT NULL
|
|
836
836
|
);
|
|
837
|
-
`),r.pragma("user_version = 34"),t=34),t<35&&t!==0&&(
|
|
837
|
+
`),r.pragma("user_version = 34"),t=34),t<35&&t!==0&&(B(r,"mailbox_cursor").has("last_processed_seq")||r.exec("ALTER TABLE mailbox_cursor ADD COLUMN last_processed_seq INTEGER;"),r.pragma("user_version = 35"),t=35),t<36&&t!==0&&(r.exec(`
|
|
838
838
|
CREATE TABLE IF NOT EXISTS usage_meter (
|
|
839
839
|
user_id TEXT NOT NULL,
|
|
840
840
|
device_id TEXT NOT NULL,
|
|
@@ -845,7 +845,7 @@ fn clamp(val, low, high) {
|
|
|
845
845
|
updated_at TEXT NOT NULL,
|
|
846
846
|
PRIMARY KEY(user_id, device_id, period)
|
|
847
847
|
);
|
|
848
|
-
`),r.pragma("user_version = 36"),t=36),t<37&&t!==0&&(
|
|
848
|
+
`),r.pragma("user_version = 36"),t=36),t<37&&t!==0&&(Ae(r,"team_connection")&&r.exec(`
|
|
849
849
|
CREATE TABLE IF NOT EXISTS team_connection_v37 (
|
|
850
850
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
851
851
|
source_teamfile TEXT NOT NULL,
|
|
@@ -871,7 +871,7 @@ fn clamp(val, low, high) {
|
|
|
871
871
|
ORDER BY id ASC;
|
|
872
872
|
DROP TABLE team_connection;
|
|
873
873
|
ALTER TABLE team_connection_v37 RENAME TO team_connection;
|
|
874
|
-
`),r.pragma("user_version = 37"),t=37),t<38&&t!==0&&(
|
|
874
|
+
`),r.pragma("user_version = 37"),t=37),t<38&&t!==0&&(B(r,"agent_inflight").has("active_count")||r.exec("ALTER TABLE agent_inflight ADD COLUMN active_count INTEGER NOT NULL DEFAULT 1;"),r.exec("DROP TABLE IF EXISTS team_connection;"),r.pragma("user_version = 38"),t=38),t<39&&t!==0&&(B(r,"agent_inflight").has("holder_pid")||r.exec("ALTER TABLE agent_inflight ADD COLUMN holder_pid INTEGER;"),r.pragma("user_version = 39"),t=39),t<40&&t!==0&&(r.exec(`
|
|
875
875
|
CREATE TABLE IF NOT EXISTS delegation_job (
|
|
876
876
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
877
877
|
teamfile TEXT NOT NULL,
|
|
@@ -907,7 +907,7 @@ fn clamp(val, low, high) {
|
|
|
907
907
|
);
|
|
908
908
|
CREATE INDEX IF NOT EXISTS idx_delegation_event_job_id
|
|
909
909
|
ON delegation_event(delegation_job_id, id);
|
|
910
|
-
`),r.pragma("user_version = 40"),t=40),t<41&&t!==0){let n=
|
|
910
|
+
`),r.pragma("user_version = 40"),t=40),t<41&&t!==0){let n=B(r,"delegation_job");n.has("permission_mode")||r.exec("ALTER TABLE delegation_job ADD COLUMN permission_mode TEXT;"),n.has("idle_timeout_ms")||r.exec("ALTER TABLE delegation_job ADD COLUMN idle_timeout_ms INTEGER;"),r.pragma("user_version = 41"),t=41}if(t<42&&t!==0&&(B(r,"delegation_job").has("delivered_at")||r.exec("ALTER TABLE delegation_job ADD COLUMN delivered_at TEXT;"),r.pragma("user_version = 42"),t=42),t<43&&t!==0&&(B(r,"delegation_job").has("meta")||r.exec("ALTER TABLE delegation_job ADD COLUMN meta TEXT;"),r.exec(`
|
|
911
911
|
CREATE TABLE IF NOT EXISTS runtime_state (
|
|
912
912
|
scope TEXT NOT NULL,
|
|
913
913
|
key TEXT NOT NULL,
|
|
@@ -970,7 +970,7 @@ fn clamp(val, low, high) {
|
|
|
970
970
|
ON agent_mailbox(sender_teamfile, sender_alias, created_at);
|
|
971
971
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_created
|
|
972
972
|
ON agent_mailbox(created_at);
|
|
973
|
-
`),r.pragma("user_version = 45"),t=45),t<46&&t!==0&&(
|
|
973
|
+
`),r.pragma("user_version = 45"),t=45),t<46&&t!==0&&(Ae(r,"team_chat_log")?ta(r):r.exec(`
|
|
974
974
|
CREATE TABLE IF NOT EXISTS team_chat_log (
|
|
975
975
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
976
976
|
root_teamfile TEXT NOT NULL,
|
|
@@ -989,18 +989,18 @@ fn clamp(val, low, high) {
|
|
|
989
989
|
`),r.exec(`
|
|
990
990
|
CREATE INDEX IF NOT EXISTS idx_team_chat_log_root_time
|
|
991
991
|
ON team_chat_log(root_teamfile, created_at);
|
|
992
|
-
`),r.pragma("user_version = 46"),t=46),t>=46&&
|
|
992
|
+
`),r.pragma("user_version = 46"),t=46),t>=46&&Ae(r,"team_chat_log")&&!B(r,"team_chat_log").has("origin")&&ta(r),t<47&&t!==0){if(Xe(r,"tracked_invocation"),Ae(r,"agent_mailbox")){let s=B(r,"agent_mailbox");s.has("delivered_at")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN delivered_at TEXT;"),s.has("receipt")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN receipt TEXT;")}let n=B(r,"tracked_invocation");n.has("notified_by")||r.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_by TEXT;"),n.has("notified_at")||r.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_at TEXT;"),r.pragma("user_version = 47"),t=47}if(t<48&&t!==0){if(Ae(r,"agent_mailbox")){let n=B(r,"agent_mailbox");n.has("delivering_at")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN delivering_at TEXT;"),n.has("delivery_holder_pid")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_pid INTEGER;"),n.has("delivery_holder_host")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_host TEXT;"),n.has("waited_at")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_at TEXT;"),n.has("waited_by")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_by TEXT;"),r.exec(`
|
|
993
993
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_sender_delivery_wait
|
|
994
994
|
ON agent_mailbox(sender_teamfile, sender_alias, delivered_at, waited_at, id);
|
|
995
995
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_lane_delivery
|
|
996
996
|
ON agent_mailbox(sender_teamfile, sender_alias, receiver_teamfile, receiver_alias, delivered_at, delivering_at, id);
|
|
997
|
-
`)}r.pragma("user_version = 48"),t=48}if(t<49&&t!==0&&(
|
|
997
|
+
`)}r.pragma("user_version = 48"),t=48}if(t<49&&t!==0&&(Xe(r,"tracked_invocation"),r.exec(`
|
|
998
998
|
UPDATE tracked_invocation
|
|
999
999
|
SET notified_by = 'migration-baseline',
|
|
1000
1000
|
notified_at = COALESCE(ended_at, started_at)
|
|
1001
1001
|
WHERE status IN ('done', 'error', 'busy', 'cancelled')
|
|
1002
1002
|
AND notified_by IS NULL;
|
|
1003
|
-
`),r.pragma("user_version = 49"),t=49),t<50&&t!==0&&(
|
|
1003
|
+
`),r.pragma("user_version = 49"),t=49),t<50&&t!==0&&(Xe(r,"tracked_invocation"),B(r,"tracked_invocation").has("launch_source")||r.exec("ALTER TABLE tracked_invocation ADD COLUMN launch_source TEXT;"),r.pragma("user_version = 50"),t=50),t<51&&t!==0){if(Ae(r,"agent_mailbox")){let n=B(r,"agent_mailbox");n.has("message_type")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN message_type TEXT NOT NULL DEFAULT 'request' CHECK(message_type IN ('request','response'));"),n.has("reply_mode")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN reply_mode TEXT NOT NULL DEFAULT 'pull' CHECK(reply_mode IN ('push','pull'));"),n.has("request_mailbox_id")||r.exec("ALTER TABLE agent_mailbox ADD COLUMN request_mailbox_id INTEGER;"),r.exec(`
|
|
1004
1004
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_agent_mailbox_response_request_unique
|
|
1005
1005
|
ON agent_mailbox(request_mailbox_id)
|
|
1006
1006
|
WHERE message_type = 'response' AND request_mailbox_id IS NOT NULL;
|
|
@@ -1016,7 +1016,7 @@ fn clamp(val, low, high) {
|
|
|
1016
1016
|
BEGIN
|
|
1017
1017
|
SELECT RAISE(ABORT, 'agent_mailbox response requires request_mailbox_id');
|
|
1018
1018
|
END;
|
|
1019
|
-
`)}r.pragma("user_version = 51"),t=51}if(t<52&&t!==0&&(
|
|
1019
|
+
`)}r.pragma("user_version = 51"),t=51}if(t<52&&t!==0&&(Xe(r,"tracked_invocation"),B(r,"tracked_invocation").has("request_payload")||r.exec("ALTER TABLE tracked_invocation ADD COLUMN request_payload TEXT;"),r.pragma("user_version = 52"),t=52),t<53&&t!==0&&(r.exec(`
|
|
1020
1020
|
CREATE TABLE IF NOT EXISTS message_event (
|
|
1021
1021
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1022
1022
|
event_id TEXT NOT NULL UNIQUE,
|
|
@@ -1098,7 +1098,7 @@ fn clamp(val, low, high) {
|
|
|
1098
1098
|
ON invocation_state(target_teamfile, target_alias, status, launch_source);
|
|
1099
1099
|
CREATE INDEX IF NOT EXISTS idx_invocation_state_from_time
|
|
1100
1100
|
ON invocation_state(from_identity, started_at DESC);
|
|
1101
|
-
`),r.pragma("user_version = 53"),t=53),t<54&&t!==0&&(
|
|
1101
|
+
`),r.pragma("user_version = 53"),t=53),t<54&&t!==0&&(Xe(r,"agent_state"),B(r,"agent_state").has("currently_handling_message_id")||r.exec("ALTER TABLE agent_state ADD COLUMN currently_handling_message_id TEXT;"),r.pragma("user_version = 54"),t=54),t<55&&t!==0&&(Xe(r,"agent_state"),B(r,"agent_state").has("currently_handling_since")||r.exec("ALTER TABLE agent_state ADD COLUMN currently_handling_since TEXT;"),r.pragma("user_version = 55"),t=55),t<56&&t!==0&&(Ae(r,"tracked_invocation")&&r.exec(`
|
|
1102
1102
|
CREATE TABLE tracked_invocation_v56 (
|
|
1103
1103
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1104
1104
|
kind TEXT NOT NULL CHECK(kind IN ('chat', 'exec')),
|
|
@@ -1152,19 +1152,19 @@ fn clamp(val, low, high) {
|
|
|
1152
1152
|
ON tracked_invocation(scope_teamfile, status, started_at);
|
|
1153
1153
|
CREATE INDEX IF NOT EXISTS idx_tracked_invocation_status_ended
|
|
1154
1154
|
ON tracked_invocation(status, ended_at);
|
|
1155
|
-
`),r.pragma("user_version = 56"),t=56),t<57&&t!==0&&(
|
|
1155
|
+
`),r.pragma("user_version = 56"),t=56),t<57&&t!==0&&(Ae(r,"agent_mailbox")&&ea(r),r.exec("DROP TABLE IF EXISTS agent_mailbox;"),r.pragma("user_version = 57"),t=57),t<58&&t!==0&&(Xe(r,"tracked_invocation"),B(r,"tracked_invocation").has("parent_invocation_id")||r.exec("ALTER TABLE tracked_invocation ADD COLUMN parent_invocation_id INTEGER;"),r.pragma("user_version = 58"),t=58),t<59&&t!==0&&(r.exec(`
|
|
1156
1156
|
CREATE TABLE IF NOT EXISTS state_ledger_identity (
|
|
1157
1157
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
1158
1158
|
instance_id TEXT NOT NULL,
|
|
1159
1159
|
created_at TEXT NOT NULL
|
|
1160
1160
|
);
|
|
1161
|
-
`),r.pragma("user_version = 59"),t=59),t<60&&t!==0&&(
|
|
1161
|
+
`),r.pragma("user_version = 59"),t=59),t<60&&t!==0&&(Xe(r,"tracked_invocation"),B(r,"tracked_invocation").has("config_warnings")||r.exec("ALTER TABLE tracked_invocation ADD COLUMN config_warnings TEXT;"),r.pragma("user_version = 60"),t=60),t<61&&t!==0){let n=B(r,"team_chat_log");n.size>0&&!n.has("message_type")&&r.exec("ALTER TABLE team_chat_log ADD COLUMN message_type TEXT CHECK(message_type IN ('batch'));"),r.exec(`
|
|
1162
1162
|
CREATE TABLE IF NOT EXISTS schema_meta (
|
|
1163
1163
|
key TEXT PRIMARY KEY,
|
|
1164
1164
|
value TEXT NOT NULL
|
|
1165
1165
|
);
|
|
1166
1166
|
INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '60');
|
|
1167
|
-
`),r.pragma("user_version = 61"),t=61}Pm(Xm)}function Gm(r){r.prepare("SELECT instance_id FROM state_ledger_identity WHERE singleton = 1").get()===void 0&&r.prepare("INSERT OR IGNORE INTO state_ledger_identity (singleton, instance_id, created_at) VALUES (1, ?, ?)").run($m(),new Date().toISOString())}function
|
|
1167
|
+
`),r.pragma("user_version = 61"),t=61}Pm(Xm)}function Gm(r){r.prepare("SELECT instance_id FROM state_ledger_identity WHERE singleton = 1").get()===void 0&&r.prepare("INSERT OR IGNORE INTO state_ledger_identity (singleton, instance_id, created_at) VALUES (1, ?, ?)").run($m(),new Date().toISOString())}function B(r,e){let t=r.prepare(`PRAGMA table_info(${e})`).all();return new Set(t.map(n=>n.name))}function Ae(r,e){return r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Xe(r,e){if(!Ae(r,e)&&(r.exec(na(aa,"utf8")),!Ae(r,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function ta(r){let e=B(r,"team_chat_log");r.pragma("foreign_keys = OFF");try{r.exec(`
|
|
1168
1168
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
1169
1169
|
CREATE TABLE team_chat_log_v46 (
|
|
1170
1170
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -1193,7 +1193,7 @@ fn clamp(val, low, high) {
|
|
|
1193
1193
|
FROM team_chat_log;
|
|
1194
1194
|
DROP TABLE team_chat_log;
|
|
1195
1195
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
1196
|
-
`)}finally{r.pragma("foreign_keys = ON")}}function la(r){let e=r.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function Jm(r,e){try{if(!
|
|
1196
|
+
`)}finally{r.pragma("foreign_keys = ON")}}function la(r){let e=r.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function Jm(r,e){try{if(!Ae(r,"schema_meta"))return e;let t=r.prepare("SELECT value FROM schema_meta WHERE key = 'min_reader_version'").get();if(t===void 0)return e;let n=Number.parseInt(t.value,10);return Number.isInteger(n)&&n>0?n:e}catch{return e}}var ra=!1;function Vm(r,e,t=qe){ra||(ra=!0,process.stderr.write(`warning: ${r}: state.db is v${e}; this build understands v${t} -- some newer data or features may not be visible, proceeding best-effort. Update: npm install -g @lmctl-ai/lmctl@latest
|
|
1197
1197
|
`),process.argv.includes("--json")&&process.stderr.write(`${JSON.stringify({schema_skew:{db_version:e,build_version:t,mode:"best_effort"}})}
|
|
1198
1198
|
`))}var Km=null;function Ym(){return process.env.LMCTL_DB??Bm(jm(),".lmctl","state.db")}if(process.argv[1]&&(process.argv[1].endsWith("migrate.ts")||process.argv[1].endsWith("migrate.js"))&&import.meta.url===Hm(process.argv[1]).href){let r=Hr({dbPath:process.argv[2]??Ym()});try{process.stdout.write(`migrated user_version=${la(r)}
|
|
1199
1199
|
`)}finally{r.close()}}function ca(r){return{getAgentInflight:r.prepare("SELECT * FROM agent_inflight WHERE receiver_teamfile = ? AND receiver_alias = ?"),listAgentInflight:r.prepare("SELECT * FROM agent_inflight ORDER BY started_at ASC, receiver_teamfile ASC, receiver_alias ASC"),acquireAgentInflight:r.prepare(`
|
|
@@ -1413,14 +1413,14 @@ fn clamp(val, low, high) {
|
|
|
1413
1413
|
AND holder_host IS ?
|
|
1414
1414
|
AND started_at = ?
|
|
1415
1415
|
AND last_heartbeat_at IS ?
|
|
1416
|
-
`)}}function
|
|
1416
|
+
`)}}function we(r){if(r==null)return null;if(Buffer.byteLength(r,"utf8")<=65536)return r;let t=Buffer.byteLength(da,"utf8"),n=Math.max(0,65536-t),s=Buffer.from(r,"utf8"),i=n;for(;i>0&&(s[i]&192)===128;)i-=1;return`${s.subarray(0,i).toString("utf8")}${da}`}var Yt="terminal_lock",zt="member";function Qt(r,e){return JSON.stringify([r,e])}function ma(r){try{let e=JSON.parse(r);return typeof e.lock_id!="string"||typeof e.teamfile!="string"||typeof e.alias!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||!Array.isArray(e.holder_ips)||!e.holder_ips.every(t=>typeof t=="string")||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,teamfile:e.teamfile,alias:e.alias,holder_pid:e.holder_pid,holder_host:e.holder_host,holder_ips:e.holder_ips,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}function Ee(r){if(!Number.isInteger(r)||(r??0)<=0)return!1;try{return process.kill(r,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}import{randomUUID as nf}from"node:crypto";import{hostname as sf}from"node:os";import{hostname as xt}from"node:os";var fa=8*60*60*1e3,pa=12e4,zm=3e4;function Xr(r,e={}){let t=setInterval(()=>{Promise.resolve().then(()=>r(new Date().toISOString())).then(n=>{n||clearInterval(t)}).catch(n=>e.onError?.(n))},e.intervalMs??zm);return t.unref?.(),t}function qr(r,e){let t=new Date().toISOString(),n=new Date(Date.now()-e.ttlMs).toISOString(),s={receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,started_at:t},i=r.getAgentInflight(e.receiver_teamfile,e.receiver_alias),o=i===null||i.holder_pid===null,a=r.tryAcquireAgentInflight(s,{...o?{stale_before:n}:{},force:e.force,reclaim_reason:e.reclaimReason});if(a.acquired){let c=i===null?null:e.force===!0?e.reclaimReason??"force":i.holder_pid===null&&i.started_at<n?"stale":null;return{acquired:!0,lease:a.current??s,leaseId:a.lease_id,previous:i,reclaimReason:c}}if(!Jr(a.current,n))return{acquired:!1,current:a.current};let l=r.tryAcquireAgentInflight(s,a.current.holder_pid===null?{stale_before:n}:{reclaim_observed:{sender_teamfile:a.current.sender_teamfile,sender_alias:a.current.sender_alias,started_at:a.current.started_at,holder_pid:a.current.holder_pid},reclaim_reason:"dead-pid"});return l.acquired?{acquired:!0,lease:l.current??s,leaseId:l.lease_id,previous:a.current,reclaimReason:a.current.holder_pid===null?"stale":"dead-pid"}:{acquired:!1,current:l.current}}function ha(r){return r.status!=="running"?null:r.holder_host===xt()&&r.holder_pid!==null&&r.holder_pid>0?Ee(r.holder_pid)?"live":"dead":"unknown"}function Gr(r,e,t){let n,s=r.getTerminalLock(e,t);if(s!==null){if(Qm(s))return{busy:!0,reason:"terminal-held",source:"terminal-lock",terminalLock:s};n??={source:"terminal-lock",holder_pid:s.holder_pid,holder_host:s.holder_host,reason:s.holder_host===xt()?"dead-pid":"stale"}}let i=Zm(r,e,t);if(i!==null){if(ef(i))return{busy:!0,reason:"terminal-held",source:"terminal-invocation",terminalInvocation:i};n??={source:"terminal-invocation",holder_pid:i.holder_pid,holder_host:i.holder_host,reason:i.holder_pid!==null&&(i.holder_host===null||i.holder_host===xt())?"dead-pid":"stale"}}let o=r.getAgentInflight(e,t);if(o!==null){let a=new Date(Date.now()-At()).toISOString();if(!Jr(o,a))return{busy:!0,reason:"in-flight",inFlight:o};n??={source:"in-flight",holder_pid:o.holder_pid,holder_host:o.holder_pid===null?null:xt(),reason:o.holder_pid===null?"stale":"dead-pid"}}return n===void 0?{busy:!1}:{busy:!1,reclaimable:n}}function Qm(r){if(r.holder_host===xt())return Ee(r.holder_pid);let e=Date.parse(r.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=rf():!1}function Zm(r,e,t){return r.query(`SELECT id, started_at, last_heartbeat_at, holder_pid, holder_host
|
|
1417
1417
|
FROM tracked_invocation
|
|
1418
1418
|
WHERE target_teamfile = ?
|
|
1419
1419
|
AND target_alias = ?
|
|
1420
1420
|
AND status = 'running'
|
|
1421
1421
|
AND launch_source = 'terminal'
|
|
1422
1422
|
ORDER BY started_at DESC, id DESC
|
|
1423
|
-
LIMIT 1`,e,t)[0]??null}function ef(r){return r.holder_pid!==null&&(r.holder_host===null||r.holder_host===xt())?
|
|
1423
|
+
LIMIT 1`,e,t)[0]??null}function ef(r){return r.holder_pid!==null&&(r.holder_host===null||r.holder_host===xt())?Ee(r.holder_pid):tf(r)}function tf(r){let e=Date.parse(r.last_heartbeat_at??r.started_at);return Number.isFinite(e)?Date.now()-e<=At():!1}function Jr(r,e){return r.holder_pid===null?r.started_at<e:!Ee(r.holder_pid)}function At(r=process.env){let e=r.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return fa;let t=Number(e);return!Number.isFinite(t)||t<=0?fa:t}function rf(r=process.env){let e=r.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return pa;let t=Number(e);return!Number.isFinite(t)||t<=0?pa:t}var of=60*60*1e3;function Ge(r,e){return{teamfile:r,alias:e}}function ga(r,e,t={}){return{teamfile:r,alias:e,...t.provider===void 0||t.provider===null?{}:{provider:t.provider},...t.sessionId===void 0||t.sessionId===null?{}:{session_id:t.sessionId}}}function ys(r,e){return r===null?null:Ge(r,e??"")}function Fe(r){return`msg_tcl_${r}`}function lt(r){return`inv_${r}`}function bt(r,e,t){return r.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias,
|
|
1424
1424
|
holder_pid, holder_host, started_at, terminal_lock_id,
|
|
1425
1425
|
terminal_invocation_id, currently_handling_message_id,
|
|
1426
1426
|
currently_handling_since, last_seq
|
|
@@ -1437,12 +1437,12 @@ fn clamp(val, low, high) {
|
|
|
1437
1437
|
SET currently_handling_message_id = NULL,
|
|
1438
1438
|
currently_handling_since = NULL
|
|
1439
1439
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1440
|
-
AND currently_handling_message_id = ?`).run(e,t,n).changes===1}function cf(r,e){let t=e??new Date(Date.now()-At()).toISOString();return Jr({holder_pid:r.holder_pid,started_at:r.started_at??""},t)}function df(r,e,t){return e==="force"||e==="session-idle"?e:t?"force":r.holder_pid!==null&&!
|
|
1440
|
+
AND currently_handling_message_id = ?`).run(e,t,n).changes===1}function cf(r,e){let t=e??new Date(Date.now()-At()).toISOString();return Jr({holder_pid:r.holder_pid,started_at:r.started_at??""},t)}function df(r,e,t){return e==="force"||e==="session-idle"?e:t?"force":r.holder_pid!==null&&!Ee(r.holder_pid)?"dead-pid":"stale"}function uf(r){return{sender:ys(r.sender_teamfile,r.sender_alias),holder_pid:r.holder_pid,holder_host:r.holder_host,started_at:r.started_at}}function Rt(r,e){if(r!==1)throw new Error(`event projection CAS failed during ${e}`)}function vs(r,e,t){let n=Fe(e),s=ys(t.sender_teamfile,t.sender_alias),i=ga(t.receiver_teamfile,t.receiver_alias,{provider:t.receiver_provider,sessionId:t.receiver_session_id}),o={message_id:n,message_type:"request",sender:s,receiver:i,root_teamfile:t.root_teamfile,legacy:{table:"team_chat_log",id:e}};return ue(r,{stream_id:n,event_type:"CREATE",observedLastSeq:0,ts:t.created_at,payload:{...o,content:t.message,provider_prompt:t.provider_prompt??t.message,origin:t.origin,...lf(r,t.sender_teamfile,t.sender_alias)}},()=>{Ts(r,t.receiver_teamfile,t.receiver_alias,n,t.created_at)}),n}function Vr(r,e,t){let n=Fe(e),s={message_id:n,message_type:"request",sender:ys(t.sender_teamfile,t.sender_alias),receiver:ga(t.receiver_teamfile,t.receiver_alias,{provider:t.receiver_provider,sessionId:t.receiver_session_id}),root_teamfile:t.root_teamfile,legacy:{table:"team_chat_log",id:e}};return ue(r,{stream_id:n,event_type:"HANDLED",observedLastSeq:1,ts:t.created_at,payload:{...s,outcome:t.status,receipt:t.response,error:t.error_detail,truncated:t.truncated===1}},()=>{Ss(r,t.receiver_teamfile,t.receiver_alias,n)}),n}function mf(r){return{sender:Ge(r.sender_teamfile,r.sender_alias),holder_pid:r.holder_pid,holder_host:null,started_at:r.started_at}}function _a(r,e,t,n){let s=r.prepare(`UPDATE agent_state
|
|
1441
1441
|
SET lease_id = NULL, sender_teamfile = NULL, sender_alias = NULL,
|
|
1442
1442
|
holder_pid = NULL, holder_host = NULL, started_at = NULL,
|
|
1443
1443
|
last_heartbeat_at = NULL, last_seq = ?
|
|
1444
1444
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1445
|
-
AND lease_id IS ? AND last_seq = ?`).run(t,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Rt(s.changes,n)}function Ea(r,e,t,n,s=null,i=!1){let o=sf();if(t!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=bt(r,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||cf(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let d=df(a,n,i),
|
|
1445
|
+
AND lease_id IS ? AND last_seq = ?`).run(t,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Rt(s.changes,n)}function Ea(r,e,t,n,s=null,i=!1){let o=sf();if(t!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=bt(r,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||cf(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let d=df(a,n,i),m=uf(a),h=a.lease_id;ue(r,{stream_id:h,event_type:"INFLIGHT_RECLAIM",observedLastSeq:a.last_seq,ts:e.started_at,payload:{receiver:Ge(e.receiver_teamfile,e.receiver_alias),reason:d,previous_holder:m}},f=>_a(r,a,f,"INFLIGHT_RECLAIM")),a=bt(r,e.receiver_teamfile,e.receiver_alias)}let l=a?.last_seq??0,c=`lease_${nf()}`;return ue(r,{stream_id:c,event_type:"INFLIGHT_TAKE",observedLastSeq:l,ts:e.started_at,payload:{lease_id:c,receiver:Ge(e.receiver_teamfile,e.receiver_alias),sender:Ge(e.sender_teamfile,e.sender_alias),holder_pid:e.holder_pid,holder_host:o,started_at:e.started_at}},u=>{if(a===null){r.prepare(`INSERT INTO agent_state
|
|
1446
1446
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile,
|
|
1447
1447
|
sender_alias, holder_pid, holder_host, started_at,
|
|
1448
1448
|
last_heartbeat_at, last_seq)
|
|
@@ -1456,11 +1456,11 @@ fn clamp(val, low, high) {
|
|
|
1456
1456
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1457
1457
|
AND lease_id = ?
|
|
1458
1458
|
AND sender_teamfile = ? AND sender_alias = ?
|
|
1459
|
-
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,t,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function Zt(r,e,t,n){let s=bt(r,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||ue(r,{stream_id:s.lease_id,event_type:t,observedLastSeq:s.last_seq,payload:{receiver:
|
|
1459
|
+
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,t,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function Zt(r,e,t,n){let s=bt(r,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||ue(r,{stream_id:s.lease_id,event_type:t,observedLastSeq:s.last_seq,payload:{receiver:Ge(e.receiver_teamfile,e.receiver_alias),...t==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:mf(e)}:{lease_id:s.lease_id}}},i=>_a(r,s,i,t))}function Ta(r,e){let t=bt(r,e.teamfile,e.alias),n=t?.last_seq??0;ue(r,{stream_id:e.lock_id,event_type:"TERMINAL_LOCK_TAKE",observedLastSeq:n,ts:e.started_at,payload:{receiver:Ge(e.teamfile,e.alias),lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at}},s=>{if(t===null){r.prepare(`INSERT INTO agent_state
|
|
1460
1460
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
1461
1461
|
VALUES (?, ?, ?, ?)`).run(e.teamfile,e.alias,e.lock_id,s);return}let i=r.prepare(`UPDATE agent_state SET terminal_lock_id = ?, last_seq = ?
|
|
1462
1462
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1463
|
-
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,t.last_seq);Rt(i.changes,"TERMINAL_LOCK_TAKE")})}function ws(r,e,t=!1){let n=bt(r,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||ue(r,{stream_id:e.lock_id,event_type:t?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE",observedLastSeq:n.last_seq,payload:{receiver:
|
|
1463
|
+
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,t.last_seq);Rt(i.changes,"TERMINAL_LOCK_TAKE")})}function ws(r,e,t=!1){let n=bt(r,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||ue(r,{stream_id:e.lock_id,event_type:t?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE",observedLastSeq:n.last_seq,payload:{receiver:Ge(e.teamfile,e.alias),lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host}},s=>{let i=r.prepare(`UPDATE agent_state SET terminal_lock_id = NULL, last_seq = ?
|
|
1464
1464
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1465
1465
|
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);Rt(i.changes,t?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE")})}function Sa(r,e,t){let n=bt(r,t.targetTeamfile,t.targetAlias);if(n===null){r.prepare(`INSERT INTO agent_state
|
|
1466
1466
|
(receiver_teamfile, receiver_alias, terminal_invocation_id,
|
|
@@ -1480,22 +1480,22 @@ fn clamp(val, low, high) {
|
|
|
1480
1480
|
terminal_invocation_host = NULL,
|
|
1481
1481
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1482
1482
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1483
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,t,n.last_seq);Rt(s.changes,"terminal INVOCATION_FINISH")}var ff="INVOCATION_START",pf="INVOCATION_FINISH",hf="INVOCATION_NOTIFY_CLAIM";function Ia(r,e){return r.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function Is(r){return r.launch_source==="terminal"&&r.target_teamfile!==null}function xa(r,e){let t=
|
|
1483
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,t,n.last_seq);Rt(s.changes,"terminal INVOCATION_FINISH")}var ff="INVOCATION_START",pf="INVOCATION_FINISH",hf="INVOCATION_NOTIFY_CLAIM";function Ia(r,e){return r.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function Is(r){return r.launch_source==="terminal"&&r.target_teamfile!==null}function xa(r,e){let t=lt(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;ue(r,{stream_id:t,event_type:ff,observedLastSeq:0,ts:e.started_at,payload:{invocation_id:t,kind:e.kind,origin:e.origin,launch_source:e.launch_source,from_identity:e.from_identity,target:n,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=>{r.prepare(`INSERT INTO invocation_state
|
|
1484
1484
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1485
1485
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1486
1486
|
status, started_at, last_heartbeat_at, last_seq)
|
|
1487
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)`).run(t,e.kind,e.origin,e.launch_source??e.kind,e.from_identity,e.target_teamfile,e.target_alias,e.root_teamfile,e.cwd,e.command,e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,e.request_payload,e.holder_pid,e.holder_host,e.started_at,e.last_heartbeat_at,i),Is(e)&&Sa(r,i,{invocationId:t,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function Kr(r,e){let t=
|
|
1487
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)`).run(t,e.kind,e.origin,e.launch_source??e.kind,e.from_identity,e.target_teamfile,e.target_alias,e.root_teamfile,e.cwd,e.command,e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,e.request_payload,e.holder_pid,e.holder_host,e.started_at,e.last_heartbeat_at,i),Is(e)&&Sa(r,i,{invocationId:t,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function Kr(r,e){let t=lt(e.id),n=Ia(r,t);return n===null?!1:(ue(r,{stream_id:t,event_type:pf,observedLastSeq:n.last_seq,ts:e.ended_at??e.started_at,payload:{invocation_id:t,status:e.status,ended_at:e.ended_at,exit_code:e.exit_code,signal:e.signal,result_summary:e.result_summary,error:e.error,legacy:{table:"tracked_invocation",id:e.id}}},s=>{if(r.prepare(`UPDATE invocation_state
|
|
1488
1488
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1489
|
-
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,t,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${t}`);Is(e)&&wa(r,s,t)}),!0)}function Aa(r,e,t,n){let s=
|
|
1489
|
+
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,t,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${t}`);Is(e)&&wa(r,s,t)}),!0)}function Aa(r,e,t,n){let s=lt(e.id),i=Ia(r,s);return i===null?!1:(ue(r,{stream_id:s,event_type:hf,observedLastSeq:i.last_seq,ts:n,payload:{invocation_id:s,notified_by:t,notified_at:n,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(r.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(t,n,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function ba(r,e,t){let n=lt(e.id);r.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(t,n),Is(e)&&va(r,n,t)}function Ra(r,e,t){r.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(t,lt(e))}function Na(r,e,t){r.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(t,lt(e))}var gf="other",_f=["not_enough_information","dont_know","other_work"],IT=new Set([gf,..._f]),ka="@abort",La="invalid_decision";var Ca="workflow_escalation";function C(){return new Date().toISOString()}function Sf(r){let e={rootTeams:[],config:[]};if(r===":memory:"||!Ua(r))return e;let t;try{t=new jr(r,{readonly:!0})}catch{return e}try{let n=[];try{n=t.prepare("SELECT teamfile_path, name, raw_text, raw_sha256, registered_at, last_seeded_at FROM root_team").all()}catch{}let s=[];try{s=t.prepare("SELECT key, value FROM lmctl_config").all()}catch{}return{rootTeams:n,config:s}}finally{t.close()}}function vf(r){if(r===":memory:"||!Ua(r))return null;let e=`${r}.bak-${Date.now()}-${process.pid}`;for(let t of["","-wal","-shm"]){let n=`${r}${t}`;try{yf(n,`${e}${t}`)}catch{}}return e}function Da(r,e){let t=e instanceof Error?e.message:String(e);try{let n=Sf(r),s=vf(r),i=new Yr(Hr({dbPath:r}));for(let o of n.rootTeams)i.upsertRootTeam(o);for(let{key:o,value:a}of n.config)i.setConfig(o,a);return process.stderr.write(`lmctl: couldn't migrate ${r} to schema v${qe} (${t}); started a fresh database instead. Preserved ${n.rootTeams.length} team registration(s) and ${n.config.length} config value(s).`+(s!==null?` Old database backed up at ${s}.
|
|
1490
1490
|
`:`
|
|
1491
|
-
`)),i}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${r}: unusable (${t}), 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 Ma(r,e){let t;try{return t=Hr({dbPath:r,allowSchemaSkew:e}),{dal:new Yr(t)}}catch(n){if(n instanceof Kt)throw n;let s;if(t!==void 0)try{s=t.pragma("user_version",{simple:!0})}catch{}try{t?.close()}catch{}return{cause:n,dbVersion:s}}}var wf=3,$a=".recovery.lock",If=20,xf=50;function Af(r){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function bf(r){if(r===":memory:")return!0;try{return Ef(`${r}${$a}`),!0}catch{return!1}}function Rf(r){if(r!==":memory:")try{Tf(`${r}${$a}`)}catch{}}function lt(r){let e=r.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",t={};for(let n=0;n<wf;n+=1)if(t=Ma(r.path,e),t.dal!==void 0)return t.dal;if(t.dbVersion!==void 0&&t.dbVersion>Xe){let n=t.cause instanceof Error?t.cause.message:String(t.cause);throw new Error(`${r.path}: state.db schema is v${t.dbVersion}; this build (understands v${Xe}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<If;n+=1){if(bf(r.path))try{return Da(r.path,t.cause)}finally{Rf(r.path)}Af(xf);let s=Ma(r.path,e);if(s.dal!==void 0)return s.dal}return Da(r.path,t.cause)}var Yr=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=Of(e),this.claimTxn=e.transaction((t,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(t,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((t,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(t,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((t,n,s,i,o)=>{let a=this.getJob(t);if(a===null)return{claimed:!1,reason:"not_found",job_id:t};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:t,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:t,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:t,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let h=this.getJob(a.id);return{claimed:!1,reason:h?.locked_until!==null&&h?.locked_until!==void 0&&h.locked_until>=i?"locked":"not_claimable",job_id:t,status:h?.status??a.status,locked_by:h?.locked_by??a.locked_by,locked_until:h?.locked_until??a.locked_until}}let m=this.getJob(a.id);return m===null?{claimed:!1,reason:"not_found",job_id:t}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((t,n,s)=>Df("state_not_found")),this.resumeInteractiveTxn=e.transaction((t,n,s,i)=>{let o=this.getInteractiveSessionByStepId(t);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(t),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((t,n,s)=>{let i=this.stmts.getAttention.get(t);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Ca)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==ka&&!a.includes(n))return{resumed:!1,reason:La};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,t),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(t,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(t.receiver_teamfile,t.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...t,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=Ea(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:c}}else a={acquired:!1,current:this.getAgentInflight(t.receiver_teamfile,t.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...t){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...t)}insertWorkflow(e){Fa(e.name,e.definition,o=>this.getWorkflowByName(o));let t=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,L()),n=this.getWorkflow(Number(t.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,L());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){Fa(e.name,e.definition,o=>this.getWorkflowByName(o));let t=this.getWorkflowByName(e.name);if(t===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(t.id)?.version??t.version)+1,i=this.stmts.insertWorkflowVersion.run(t.id,s,e.definition,e.author??null,L());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??t.definition_schema_version,s,t.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,t.id),this.syncWorkflowTriggers(t.id,e.definition),this.getWorkflow(t.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,L())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,t){return(t===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,t))??null}findWorkflowByName(e,t){return this.getWorkflowByName(e,t)}insertWorkflowVersion(e,t,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,t,n??null,L());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,t){let n=this.getWorkflowVersionById(t);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(t,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,L()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,t){return this.stmts.setTriggerCursor.run(t,L(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,t){return this.stmts.setTriggerFailure.run(L(),t,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,t){let n;try{n=JSON.parse(t)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let t=this.stmts.insertTeam.run(e.name,L());return this.stmts.getTeam.get(t.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let t=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,L());return this.stmts.getTeamMember.get(t.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,t){return this.stmts.findTeamMemberByAlias.get(e,t)??null}updateTeamMemberSession(e,t){return this.stmts.updateTeamMemberSession.run(t,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,t,n){return this.stmts.setMemberState.run(t,n??null,L(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,t){return this.stmts.setMemberPromptSnapshot.run(t,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,t){return this.stmts.setMemberProviderResolved.run(t,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,t){return this.stmts.setMemberRolePrompt.run(t,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,t){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(t,"role_prompt"),i=Object.prototype.hasOwnProperty.call(t,"model"),o=Object.prototype.hasOwnProperty.call(t,"provider");return this.stmts.updateTeamMemberMeta.run(s?t.role_prompt??null:n.role_prompt,i?t.model??null:n.model,o?t.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let t=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,L());return this.stmts.getTeamMemberCompanion.get(t.lastInsertRowid)}insertProject(e){let t=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",L());return this.stmts.getProject.get(t.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,t){return this.stmts.setProjectIntakeConfig.run(t,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,t){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(t,"local_path"),i=Object.prototype.hasOwnProperty.call(t,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(t,"default_branch"),a=Object.prototype.hasOwnProperty.call(t,"intake_config");return this.stmts.updateProjectSettings.run(s?t.local_path:n.local_path,i?t.durable_memory_mode:n.durable_memory_mode,o?t.default_branch??null:n.default_branch,a?t.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let t=JSON.parse(e.intake_config);return typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let t=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,t);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,t,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,L());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,t)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,t={}){return t.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,t){return this.stmts.setProjectWorkflowEnabled.run(t?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let t=L(),n=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,t,t);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,t={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(t.status!==void 0&&!t.status.includes(n.status)||t.severity!==void 0&&!t.severity.includes(n.severity)||t.ai_test_path!==void 0&&n.ai_test_path!==t.ai_test_path))}claimNextIssue(e,t){return this.stmts.claimNextIssue.get(t,L(),e)??null}claimIssue(e,t){return this.stmts.claimIssue.get(t,L(),e)??null}closeIssue(e,t,n){let s=L(),i=this.stmts.closeIssue.get(t,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,t){let n=this.stmts.reopenIssue.get(t,L(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,t){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(t,"labels"),i=Object.prototype.hasOwnProperty.call(t,"ai_test_path"),o=this.stmts.updateIssue.get(t.title??n.title,t.body??n.body,t.severity??n.severity,s?t.labels??null:n.labels,i?t.ai_test_path??null:n.ai_test_path,L(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,t){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=L();return this.stmts.insertWebuiSession.run(e,t,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,t,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(t,n,s,i,L(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,t){if(this.stmts.setWebuiSessionChatbot.run(t,L(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,t){let n=Oa(),s=L();return this.stmts.insertChatbotSession.run(n,e,t??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,t,n,s){let i=L(),o=this.stmts.insertChatbotMessage.run(e,t,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,t){this.stmts.upsertConfig.run(e,t,L())}getConfigAll(){let e=this.stmts.listConfig.all(),t={};for(let n of e)t[n.key]=n.value;return t}enqueueJob(e){let t=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??L(),e.dedupe_key??null,e.concurrency_key??null,L());if(t.changes===1)return this.stmts.getJob.get(t.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let t=L(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,t)}claimNextJobWithConcurrency(e){let t=L(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,t,e.evaluator)}claimJobByIdWithConcurrency(e){let t=L(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,t,e.evaluator)}releaseJob(e,t,n){let s=t==="queued"||t==="running"?null:L();return this.stmts.releaseJob.run(t,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,t){return this.stmts.findJobByDedupe.get(e,t)??null}insertRun(e){let t=this.getWorkflow(e.workflow_id);if(t===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,t.active_version_id,e.parent_run_id??null,L()),s=this.stmts.getRun.get(n.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,t){return this.stmts.setJobRun.run(t,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,L()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,t){return this.stmts.setPromptDispatchCompleted.run(t??L(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let t=e.id??"default";this.stmts.ensureWorkspace.run(t,e.name??"Default workspace",e.idleThresholdMs??6e5,L());let n=this.getWorkspace(t);if(n===null)throw new Error(`workspace ${t} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let t=L(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,t,t),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let t=this.getWebProject(e.id);return t===null||t.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??t.name,e.config_json===void 0?t.config_json:e.config_json,L(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(L(),e).changes===1}loadMailboxCursor(e,t){return this.stmts.loadMailboxCursor.get(e,t)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,t,n){return this.stmts.loadUsage.get(e,t,n)??null}sumUsageForPeriod(e,t){let n=this.stmts.sumUsageForPeriod.get(e,t);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let t=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(t.lastInsertRowid);return vs(this.db,n,e),Vr(this.db,n,e),n})()}beginTeamChatLog(e){return this.db.transaction(()=>{let t=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(t.lastInsertRowid);return vs(this.db,n,e),n})()}finishTeamChatLog(e,t){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(t.response,t.status,t.error_detail,t.truncated,e).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${e}`);Vr(this.db,e,t)})()}setCurrentlyHandlingMessage(e,t,n){this.db.transaction(()=>{Ts(this.db,e,t,n)})()}clearCurrentlyHandlingMessage(e,t,n){return this.db.transaction(()=>Ss(this.db,e,t,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,t=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(t)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let t=e.started_at??L(),n=e.holder_host??xs(),s=e.last_heartbeat_at??t,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,ve(e.command),t,e.holder_pid??null,n,s,ve(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return xa(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,t,n={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,t];n.sinceMs!==void 0&&(s.push("started_at >= ?"),i.push(new Date(n.sinceMs).toISOString())),n.untilMs!==void 0&&(s.push("started_at <= ?"),i.push(new Date(n.untilMs).toISOString()));let o=Math.max(1,Math.trunc(n.limit??200));return this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${s.join(" AND ")} ORDER BY started_at DESC LIMIT ?`).all(...i,o)}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}listRecentlyFinishedTrackedInvocations(e){return this.stmts.listRecentlyFinishedTrackedInvocations.all(e)}listFinishedTrackedInvocationChildren(e,t){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.db.prepare(`
|
|
1491
|
+
`)),i}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${r}: unusable (${t}), 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 Ma(r,e){let t;try{return t=Hr({dbPath:r,allowSchemaSkew:e}),{dal:new Yr(t)}}catch(n){if(n instanceof Kt)throw n;let s;if(t!==void 0)try{s=t.pragma("user_version",{simple:!0})}catch{}try{t?.close()}catch{}return{cause:n,dbVersion:s}}}var wf=3,$a=".recovery.lock",If=20,xf=50;function Af(r){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function bf(r){if(r===":memory:")return!0;try{return Ef(`${r}${$a}`),!0}catch{return!1}}function Rf(r){if(r!==":memory:")try{Tf(`${r}${$a}`)}catch{}}function ct(r){let e=r.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",t={};for(let n=0;n<wf;n+=1)if(t=Ma(r.path,e),t.dal!==void 0)return t.dal;if(t.dbVersion!==void 0&&t.dbVersion>qe){let n=t.cause instanceof Error?t.cause.message:String(t.cause);throw new Error(`${r.path}: state.db schema is v${t.dbVersion}; this build (understands v${qe}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<If;n+=1){if(bf(r.path))try{return Da(r.path,t.cause)}finally{Rf(r.path)}Af(xf);let s=Ma(r.path,e);if(s.dal!==void 0)return s.dal}return Da(r.path,t.cause)}var Yr=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=Of(e),this.claimTxn=e.transaction((t,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(t,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((t,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(t,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((t,n,s,i,o)=>{let a=this.getJob(t);if(a===null)return{claimed:!1,reason:"not_found",job_id:t};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:t,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:t,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:t,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let f=this.getJob(a.id);return{claimed:!1,reason:f?.locked_until!==null&&f?.locked_until!==void 0&&f.locked_until>=i?"locked":"not_claimable",job_id:t,status:f?.status??a.status,locked_by:f?.locked_by??a.locked_by,locked_until:f?.locked_until??a.locked_until}}let h=this.getJob(a.id);return h===null?{claimed:!1,reason:"not_found",job_id:t}:{claimed:!0,job:h}}),this.resumeRunTxn=e.transaction((t,n,s)=>Df("state_not_found")),this.resumeInteractiveTxn=e.transaction((t,n,s,i)=>{let o=this.getInteractiveSessionByStepId(t);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(t),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((t,n,s)=>{let i=this.stmts.getAttention.get(t);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Ca)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==ka&&!a.includes(n))return{resumed:!1,reason:La};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,t),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(t,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(t.receiver_teamfile,t.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...t,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=Ea(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:c}}else a={acquired:!1,current:this.getAgentInflight(t.receiver_teamfile,t.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...t){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...t)}insertWorkflow(e){Fa(e.name,e.definition,o=>this.getWorkflowByName(o));let t=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,C()),n=this.getWorkflow(Number(t.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,C());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){Fa(e.name,e.definition,o=>this.getWorkflowByName(o));let t=this.getWorkflowByName(e.name);if(t===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(t.id)?.version??t.version)+1,i=this.stmts.insertWorkflowVersion.run(t.id,s,e.definition,e.author??null,C());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??t.definition_schema_version,s,t.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,t.id),this.syncWorkflowTriggers(t.id,e.definition),this.getWorkflow(t.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,C())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,t){return(t===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,t))??null}findWorkflowByName(e,t){return this.getWorkflowByName(e,t)}insertWorkflowVersion(e,t,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,t,n??null,C());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,t){let n=this.getWorkflowVersionById(t);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(t,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,C()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,t){return this.stmts.setTriggerCursor.run(t,C(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,t){return this.stmts.setTriggerFailure.run(C(),t,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,t){let n;try{n=JSON.parse(t)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let t=this.stmts.insertTeam.run(e.name,C());return this.stmts.getTeam.get(t.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let t=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,C());return this.stmts.getTeamMember.get(t.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,t){return this.stmts.findTeamMemberByAlias.get(e,t)??null}updateTeamMemberSession(e,t){return this.stmts.updateTeamMemberSession.run(t,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,t,n){return this.stmts.setMemberState.run(t,n??null,C(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,t){return this.stmts.setMemberPromptSnapshot.run(t,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,t){return this.stmts.setMemberProviderResolved.run(t,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,t){return this.stmts.setMemberRolePrompt.run(t,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,t){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(t,"role_prompt"),i=Object.prototype.hasOwnProperty.call(t,"model"),o=Object.prototype.hasOwnProperty.call(t,"provider");return this.stmts.updateTeamMemberMeta.run(s?t.role_prompt??null:n.role_prompt,i?t.model??null:n.model,o?t.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let t=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,C());return this.stmts.getTeamMemberCompanion.get(t.lastInsertRowid)}insertProject(e){let t=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",C());return this.stmts.getProject.get(t.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,t){return this.stmts.setProjectIntakeConfig.run(t,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,t){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(t,"local_path"),i=Object.prototype.hasOwnProperty.call(t,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(t,"default_branch"),a=Object.prototype.hasOwnProperty.call(t,"intake_config");return this.stmts.updateProjectSettings.run(s?t.local_path:n.local_path,i?t.durable_memory_mode:n.durable_memory_mode,o?t.default_branch??null:n.default_branch,a?t.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let t=JSON.parse(e.intake_config);return typeof t=="object"&&t!==null&&!Array.isArray(t)&&t.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let t=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,t);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,t,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,C());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,t)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,t={}){return t.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,t){return this.stmts.setProjectWorkflowEnabled.run(t?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let t=C(),n=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,t,t);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,t={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(t.status!==void 0&&!t.status.includes(n.status)||t.severity!==void 0&&!t.severity.includes(n.severity)||t.ai_test_path!==void 0&&n.ai_test_path!==t.ai_test_path))}claimNextIssue(e,t){return this.stmts.claimNextIssue.get(t,C(),e)??null}claimIssue(e,t){return this.stmts.claimIssue.get(t,C(),e)??null}closeIssue(e,t,n){let s=C(),i=this.stmts.closeIssue.get(t,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,t){let n=this.stmts.reopenIssue.get(t,C(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,t){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(t,"labels"),i=Object.prototype.hasOwnProperty.call(t,"ai_test_path"),o=this.stmts.updateIssue.get(t.title??n.title,t.body??n.body,t.severity??n.severity,s?t.labels??null:n.labels,i?t.ai_test_path??null:n.ai_test_path,C(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,t){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=C();return this.stmts.insertWebuiSession.run(e,t,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,t,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(t,n,s,i,C(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,t){if(this.stmts.setWebuiSessionChatbot.run(t,C(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,t){let n=Oa(),s=C();return this.stmts.insertChatbotSession.run(n,e,t??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,t,n,s){let i=C(),o=this.stmts.insertChatbotMessage.run(e,t,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,t){this.stmts.upsertConfig.run(e,t,C())}getConfigAll(){let e=this.stmts.listConfig.all(),t={};for(let n of e)t[n.key]=n.value;return t}enqueueJob(e){let t=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??C(),e.dedupe_key??null,e.concurrency_key??null,C());if(t.changes===1)return this.stmts.getJob.get(t.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let t=C(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,t)}claimNextJobWithConcurrency(e){let t=C(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,t,e.evaluator)}claimJobByIdWithConcurrency(e){let t=C(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,t,e.evaluator)}releaseJob(e,t,n){let s=t==="queued"||t==="running"?null:C();return this.stmts.releaseJob.run(t,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,t){return this.stmts.findJobByDedupe.get(e,t)??null}insertRun(e){let t=this.getWorkflow(e.workflow_id);if(t===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,t.active_version_id,e.parent_run_id??null,C()),s=this.stmts.getRun.get(n.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,t){return this.stmts.setJobRun.run(t,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,C()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,t){return this.stmts.setPromptDispatchCompleted.run(t??C(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let t=e.id??"default";this.stmts.ensureWorkspace.run(t,e.name??"Default workspace",e.idleThresholdMs??6e5,C());let n=this.getWorkspace(t);if(n===null)throw new Error(`workspace ${t} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let t=C(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,t,t),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let t=this.getWebProject(e.id);return t===null||t.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??t.name,e.config_json===void 0?t.config_json:e.config_json,C(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(C(),e).changes===1}loadMailboxCursor(e,t){return this.stmts.loadMailboxCursor.get(e,t)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,t,n){return this.stmts.loadUsage.get(e,t,n)??null}sumUsageForPeriod(e,t){let n=this.stmts.sumUsageForPeriod.get(e,t);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let t=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(t.lastInsertRowid);return vs(this.db,n,e),Vr(this.db,n,e),n})()}beginTeamChatLog(e){return this.db.transaction(()=>{let t=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(t.lastInsertRowid);return vs(this.db,n,e),n})()}finishTeamChatLog(e,t){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(t.response,t.status,t.error_detail,t.truncated,e).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${e}`);Vr(this.db,e,t)})()}setCurrentlyHandlingMessage(e,t,n){this.db.transaction(()=>{Ts(this.db,e,t,n)})()}clearCurrentlyHandlingMessage(e,t,n){return this.db.transaction(()=>Ss(this.db,e,t,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,t=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(t)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let t=e.started_at??C(),n=e.holder_host??xs(),s=e.last_heartbeat_at??t,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,we(e.command),t,e.holder_pid??null,n,s,we(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return xa(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,t,n={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,t];n.sinceMs!==void 0&&(s.push("started_at >= ?"),i.push(new Date(n.sinceMs).toISOString())),n.untilMs!==void 0&&(s.push("started_at <= ?"),i.push(new Date(n.untilMs).toISOString()));let o=Math.max(1,Math.trunc(n.limit??200));return this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${s.join(" AND ")} ORDER BY started_at DESC LIMIT ?`).all(...i,o)}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}listRecentlyFinishedTrackedInvocations(e){return this.stmts.listRecentlyFinishedTrackedInvocations.all(e)}listFinishedTrackedInvocationChildren(e,t){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.db.prepare(`
|
|
1492
1492
|
SELECT * FROM tracked_invocation
|
|
1493
1493
|
WHERE parent_invocation_id IN (${n})
|
|
1494
1494
|
AND ended_at IS NOT NULL
|
|
1495
1495
|
AND ended_at >= ?
|
|
1496
1496
|
ORDER BY started_at ASC, id ASC
|
|
1497
|
-
`).all(...e,t)}finishTrackedInvocation(e,t){return this.db.transaction(()=>{let n=t.ended_at??
|
|
1498
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==t)return this.db.exec("COMMIT"),!1;if(n.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&&Zt(this.db,n,"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(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(Zt(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,t){let n=this.stmts.getRuntimeState.get(Yt,Qt(e,t),zt);return n===void 0?null:ma(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&ws(this.db,n,!0),this.stmts.upsertRuntimeState.run(Yt,Qt(e.teamfile,e.alias),zt,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&Ta(this.db,e)})()}heartbeatTerminalLock(e,t,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,t);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(Yt,Qt(e,t),zt,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,t,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,t);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Yt,Qt(e,t),zt);return i.changes===1&&ws(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,t,n){let s=this.stmts.getRuntimeState.get(e,t,n);return s===void 0?null:Lf(s.data)}tryAcquireRuntimeProcessLock(e,t,n,s,i=L()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,t,n);if(o!==null&&!Cf(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Oa(),holder_pid:process.pid,holder_host:xs(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,t,n,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,t,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,t,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,t,n);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,t){return this.stmts.setRunCurrentState.run(t,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,t,n){return this.stmts.setRunPausedState.run(t,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,t){return this.stmts.setRunPendingEscalationDecision.run(t,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,t){return this.stmts.setRunTerminalState.run(t,L(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,t){return this.resumeRunTxn(e,t,L())}insertStep(e){let t=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,L());return this.stmts.getStep.get(t.lastInsertRowid)}finishStep(e,t,n){return this.stmts.finishStep.run(t??null,n??null,L(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let t=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of t)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let t=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??L(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(t.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 t=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,L());return this.stmts.getStepArtifact.get(t.lastInsertRowid)}insertExternalObject(e){let n=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,L()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let t=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,L()),n=t.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(t.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let t=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,L());return this.stmts.getAttention.get(t.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(L(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let t=L();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,t,t),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,t){return this.stmts.getDurableMemoryByName.get(e,t)??null}deleteDurableMemory(e,t){return this.stmts.deleteDurableMemory.run(e,t).changes>0}listDurableMemory(e,t){return t!==void 0?this.stmts.listDurableMemoryByType.all(e,t):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,t){return t!==void 0&&t.length>0?this.stmts.listDurableMemory.all(e).filter(s=>t.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:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let t=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??L());return this.stmts.getSessionSize.get(t.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,t,n=20){return this.stmts.sessionSizeHistory.all(e,t,n)}insertSessionEvent(e){let t=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(t.lastInsertRowid)}listSessionEvents(e,t){return t!==void 0?this.stmts.listSessionEventsSince.all(e,t):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,t=1e3){return this.stmts.listAllEventsSince.all(e,t)}latestAgentCall(e){let t=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(t===void 0)return null;try{let n=JSON.parse(t.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let t=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of t)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,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 t=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(t.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,t,n){return this.stmts.findUnackedDrift.get(e,t??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let t=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,t,t),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,t){return this.stmts.getInteractiveSessionByRunAndState.get(e,t)??null}setInteractiveAgentOutput(e,t,n){this.stmts.setInteractiveAgentOutput.run(t,n,Date.now(),e)}resumeInteractive(e,t,n){return this.resumeInteractiveTxn(e,t,n,L())}resumeEscalation(e,t){return this.resumeEscalationTxn(e,t,L())}};function Fa(r,e,t){let n=Pa(e);if(n.length===0)return;let s=new Set,i=[],o=l=>{if(l===r)return n;let c=t(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return Pa(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(r)}function Pa(r){let e=Nf(r),t=e===null?null:kf(e,"states");if(t===null)return[];let n=[];for(let s of Object.values(t))zr(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function Nf(r){try{let e=JSON.parse(r);return zr(e)?e:null}catch{return null}}function kf(r,e){let t=r[e];return zr(t)?t:null}function zr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Lf(r){try{let e=JSON.parse(r);return!zr(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 Cf(r,e){return r===null?!0:r.holder_host===xs()?!_e(r.holder_pid):r.last_heartbeat<e}function Of(r){return{getRuntimeState:r.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:r.prepare(`
|
|
1497
|
+
`).all(...e,t)}finishTrackedInvocation(e,t){return this.db.transaction(()=>{let n=t.ended_at??C();if(this.stmts.finishTrackedInvocation.run(t.status,n,t.exit_code??null,t.signal??null,we(t.result_summary),we(t.error),t.team_chat_log_id??null,we(t.meta),we(t.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Kr(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,t,n){return this.db.transaction(()=>{let s=n.ended_at??C();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,we(n.result_summary),we(n.error),n.team_chat_log_id??null,we(n.meta),we(n.config_warnings),s,e,t.holder_pid,t.holder_host,t.started_at,t.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Kr(this.db,o),o})()}heartbeatTrackedInvocation(e,t=C()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(t,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return ba(this.db,s,t),s})()}updateTrackedInvocationRequestPayload(e,t){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(t,e).changes!==1?null:(Ra(this.db,e,t),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,t){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(t,e).changes!==1?null:(Na(this.db,e,Fe(t)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,t,n){return this.db.transaction(()=>{let s=C();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,we(n),e,t.holder_pid,t.holder_host,t.started_at,t.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Kr(this.db,o),o.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(o.team_chat_log_id,n),o})()}terminalizeLinkedChatMessage(e,t){let n=this.stmts.getTeamChatLogById.get(e);n===void 0||n.status!=="running"||this.stmts.terminalizeTeamChatLogIfRunning.run("error",t,e).changes!==1||Vr(this.db,e,{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,message:n.message,response:null,origin:n.origin,status:"error",error_detail:t,truncated:n.truncated,created_at:C()})}listClaimableTerminalTrackedInvocations(e){let t=["status IN ('done', 'error', 'busy', 'cancelled', 'aborted')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];e.from!==void 0&&(t.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(t.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return n.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${t.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...n)}claimTrackedInvocationNotification(e,t,n=C()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(t,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Aa(this.db,i,t,n),i})()}listTrackedInvocations(e={}){let t=[],n=[];e.from!==void 0&&(t.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(t.push("scope_teamfile = ?"),n.push(e.scope_teamfile)),e.status!==void 0&&(t.push("status = ?"),n.push(e.status)),e.kind!==void 0&&(t.push("kind = ?"),n.push(e.kind)),e.origin!==void 0&&(t.push("origin = ?"),n.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));n.push(s);let i=t.length===0?"":` WHERE ${t.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let t=[],n=[];e.from!==void 0&&(t.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(t.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=t.length===0?"":` WHERE ${t.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}updateTeamChatLogResponse(e,t){this.stmts.updateTeamChatLogResponse.run(t.response,t.status,t.error_detail,t.truncated,e)}getAgentInflight(e,t){return this.stmts.getAgentInflight.get(e,t)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,t){return this.tryAcquireAgentInflightTxn(e,t)}heartbeatAgentInflight(e,t,n=C()){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:ya(this.db,s,t,n)})()}clearAgentInflight(e,t){this.db.transaction(()=>{let s=this.getAgentInflight(e,t);if(s===null)return;this.stmts.clearAgentInflight.run(e,t).changes===1&&Zt(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,t,n){return this.db.transaction(()=>{let i=this.getAgentInflight(e,t),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:t,observed_sender_teamfile:n.sender_teamfile,observed_sender_alias:n.sender_alias,observed_started_at:n.started_at,observed_holder_pid:n.holder_pid});return o.changes===1&&i!==null&&Zt(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,t){this.db.exec("BEGIN IMMEDIATE");try{let n=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(n===null||n.sender_teamfile!==e.sender_teamfile||n.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(t!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
1498
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==t)return this.db.exec("COMMIT"),!1;if(n.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&&Zt(this.db,n,"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(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(Zt(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,t){let n=this.stmts.getRuntimeState.get(Yt,Qt(e,t),zt);return n===void 0?null:ma(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&ws(this.db,n,!0),this.stmts.upsertRuntimeState.run(Yt,Qt(e.teamfile,e.alias),zt,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&Ta(this.db,e)})()}heartbeatTerminalLock(e,t,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,t);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(Yt,Qt(e,t),zt,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,t,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,t);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Yt,Qt(e,t),zt);return i.changes===1&&ws(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,t,n){let s=this.stmts.getRuntimeState.get(e,t,n);return s===void 0?null:Lf(s.data)}tryAcquireRuntimeProcessLock(e,t,n,s,i=C()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,t,n);if(o!==null&&!Cf(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Oa(),holder_pid:process.pid,holder_host:xs(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,t,n,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,t,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,t,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,t,n);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,t){return this.stmts.setRunCurrentState.run(t,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,t,n){return this.stmts.setRunPausedState.run(t,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,t){return this.stmts.setRunPendingEscalationDecision.run(t,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,t){return this.stmts.setRunTerminalState.run(t,C(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,t){return this.resumeRunTxn(e,t,C())}insertStep(e){let t=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,C());return this.stmts.getStep.get(t.lastInsertRowid)}finishStep(e,t,n){return this.stmts.finishStep.run(t??null,n??null,C(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let t=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of t)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let t=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??C(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(t.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 t=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,C());return this.stmts.getStepArtifact.get(t.lastInsertRowid)}insertExternalObject(e){let n=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,C()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let t=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,C()),n=t.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(t.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let t=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,C());return this.stmts.getAttention.get(t.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(C(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let t=C();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,t,t),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,t){return this.stmts.getDurableMemoryByName.get(e,t)??null}deleteDurableMemory(e,t){return this.stmts.deleteDurableMemory.run(e,t).changes>0}listDurableMemory(e,t){return t!==void 0?this.stmts.listDurableMemoryByType.all(e,t):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,t){return t!==void 0&&t.length>0?this.stmts.listDurableMemory.all(e).filter(s=>t.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:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let t=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??C());return this.stmts.getSessionSize.get(t.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,t,n=20){return this.stmts.sessionSizeHistory.all(e,t,n)}insertSessionEvent(e){let t=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(t.lastInsertRowid)}listSessionEvents(e,t){return t!==void 0?this.stmts.listSessionEventsSince.all(e,t):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,t=1e3){return this.stmts.listAllEventsSince.all(e,t)}latestAgentCall(e){let t=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(t===void 0)return null;try{let n=JSON.parse(t.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let t=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of t)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,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 t=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(t.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,t,n){return this.stmts.findUnackedDrift.get(e,t??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let t=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,t,t),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,t){return this.stmts.getInteractiveSessionByRunAndState.get(e,t)??null}setInteractiveAgentOutput(e,t,n){this.stmts.setInteractiveAgentOutput.run(t,n,Date.now(),e)}resumeInteractive(e,t,n){return this.resumeInteractiveTxn(e,t,n,C())}resumeEscalation(e,t){return this.resumeEscalationTxn(e,t,C())}};function Fa(r,e,t){let n=Pa(e);if(n.length===0)return;let s=new Set,i=[],o=l=>{if(l===r)return n;let c=t(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return Pa(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(r)}function Pa(r){let e=Nf(r),t=e===null?null:kf(e,"states");if(t===null)return[];let n=[];for(let s of Object.values(t))zr(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function Nf(r){try{let e=JSON.parse(r);return zr(e)?e:null}catch{return null}}function kf(r,e){let t=r[e];return zr(t)?t:null}function zr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Lf(r){try{let e=JSON.parse(r);return!zr(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 Cf(r,e){return r===null?!0:r.holder_host===xs()?!Ee(r.holder_pid):r.last_heartbeat<e}function Of(r){return{getRuntimeState:r.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:r.prepare(`
|
|
1499
1499
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
1500
1500
|
VALUES (?, ?, ?, ?, ?)
|
|
1501
1501
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1902,49 +1902,49 @@ fn clamp(val, low, high) {
|
|
|
1902
1902
|
response = NULL
|
|
1903
1903
|
WHERE id = ?
|
|
1904
1904
|
AND status = 'running'
|
|
1905
|
-
`),...ua(r),...ca(r)}}function Df(r,e){return e===void 0?{resumed:!1,reason:r}:{resumed:!1,reason:r,valid:e}}var Ka=ro(bs(),1);import{homedir as Yf}from"node:os";import{join as Ja}from"node:path";var zf=".lmctl",Qf="state.db";function Zf(){let r=process.env.LMCTL_HOME;return r!==void 0&&r.length>0?r:Ja(Yf(),zf)}function ep(){return Ja(Zf(),Qf)}function Pe(r){return r!==void 0&&r.length>0?r:process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?process.env.LMCTL_DB:ep()}function Va(r){return process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?`db: ${r} (overridden by --db/LMCTL_DB)`:`db: ${r}`}async function
|
|
1906
|
-
`),1}function
|
|
1905
|
+
`),...ua(r),...ca(r)}}function Df(r,e){return e===void 0?{resumed:!1,reason:r}:{resumed:!1,reason:r,valid:e}}var Ka=ro(bs(),1);import{homedir as Yf}from"node:os";import{join as Ja}from"node:path";var zf=".lmctl",Qf="state.db";function Zf(){let r=process.env.LMCTL_HOME;return r!==void 0&&r.length>0?r:Ja(Yf(),zf)}function ep(){return Ja(Zf(),Qf)}function Pe(r){return r!==void 0&&r.length>0?r:process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?process.env.LMCTL_DB:ep()}function Va(r){return process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?`db: ${r} (overridden by --db/LMCTL_DB)`:`db: ${r}`}async function $(r,e){if(r.dal!==void 0)return e(r.dal);let t=ct({path:Pe()});try{return await e(t)}finally{t.close()}}function dt(r,e){return r.stderr.write(`error: ${e}
|
|
1906
|
+
`),1}function Ve(){return(0,Ka.formatClock)()}function Zr(r,e,t=5e3){let n=Date.now(),s=n,i=setInterval(()=>{let o=Date.now();o-s<t||r.stderr.write(e(Math.round((o-n)/1e3)))},t);return i.unref(),{poke:()=>{s=Date.now()},stop:()=>clearInterval(i)}}function en(r){if(r===void 0)return null;let e=Number.parseInt(r,10);return Number.isInteger(e)&&e>0?e:null}function tp(r,e){if(ha(e)!=="dead")return null;let t=`holder process verified not alive; reconciled to aborted (invocation #${e.id}, holder pid ${e.holder_pid??"unknown"} on ${e.holder_host??"unknown"})`;return r.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},t)}function tn(r,e,t){let n=r.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
1907
1907
|
FROM tracked_invocation
|
|
1908
1908
|
WHERE target_teamfile = ?
|
|
1909
1909
|
AND target_alias = ?
|
|
1910
|
-
AND status = 'running'`,e,t),s=0;for(let i of n)tp(r,i)!==null&&(s+=1);return s}import{platform as Ya}from"node:os";import{realpathSync as rp}from"node:fs";import{resolve as np}from"node:path";function Rs(r){let e=np(r);try{return rp(e)}catch{return e}}var rn=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let t=[],n=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)t.push(...o);let i=t;if(e?.workspace){let o=Rs(e.workspace);i=i.filter(a=>Rs(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,t){let n=t?this.providers.filter(s=>s.name===t):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,t){let n=await this.resolveSessions(e,t);return n.length===1?n[0]:null}async resolveSessions(e,t){let n=t?this.providers.filter(i=>i.name===t):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Ya()==="darwin"||Ya()==="win32",t=[];for(let n of this.providers)if(typeof n.getWatchPaths=="function")for(let s of n.getWatchPaths())t.push({provider:n.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return t}async deleteSession(e,t){let n=await this.resolveSession(e,t);return n?n.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:t=>e.load(t),resolveSessionPath:t=>e.resolvePath(t),deleteSession:t=>e.delete(t),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}};function
|
|
1911
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function M(r,e){return r.length<=e?r:r.slice(0,e-3)+"..."}function
|
|
1912
|
-
`):"";
|
|
1913
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let
|
|
1914
|
-
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",l=>{if(l===0||l===null)n({success:!0});else{let c=er(o).trim(),u=er(i).trim();n({success:!1,error:(c||u).slice(0,500)||`exit code ${l}`})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,t){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:an,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,t){let n=this.turnOptsFor(t);if(n.userConfig&&il(n.userConfig,this.name)){let i=n.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,n,i.agent)}let s=n.timeoutMs??r.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,t,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:
|
|
1910
|
+
AND status = 'running'`,e,t),s=0;for(let i of n)tp(r,i)!==null&&(s+=1);return s}import{platform as Ya}from"node:os";import{realpathSync as rp}from"node:fs";import{resolve as np}from"node:path";function Rs(r){let e=np(r);try{return rp(e)}catch{return e}}var rn=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let t=[],n=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)t.push(...o);let i=t;if(e?.workspace){let o=Rs(e.workspace);i=i.filter(a=>Rs(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,t){let n=t?this.providers.filter(s=>s.name===t):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,t){let n=await this.resolveSessions(e,t);return n.length===1?n[0]:null}async resolveSessions(e,t){let n=t?this.providers.filter(i=>i.name===t):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Ya()==="darwin"||Ya()==="win32",t=[];for(let n of this.providers)if(typeof n.getWatchPaths=="function")for(let s of n.getWatchPaths())t.push({provider:n.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return t}async deleteSession(e,t){let n=await this.resolveSession(e,t);return n?n.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:t=>e.load(t),resolveSessionPath:t=>e.resolvePath(t),deleteSession:t=>e.delete(t),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}};function ut(r){let e=new rn;for(let t of r)e.registerAdapter(t);return e}import{join as cc}from"node:path";import{readdir as nn,stat as el,unlink as op}from"node:fs/promises";import{join as Nt,basename as tl}from"node:path";import{createReadStream as za}from"node:fs";import{createInterface as Qa}from"node:readline";import{stat as sp}from"node:fs/promises";import{homedir as ip}from"node:os";var U=ip();function Za(r){try{let e=JSON.parse(r);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*Z(r){let e=za(r,{encoding:"utf-8"}),t=Qa({input:e,crlfDelay:1/0});try{for await(let n of t){let s=n.trim();if(!s)continue;let i=Za(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function ye(r,e){let t=[],n=za(r,{encoding:"utf-8"}),s=Qa({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=Za(o);if(a!==void 0&&t.push(a),t.length>=e)break}}finally{s.close(),n.destroy()}return t}async function te(r){let e=await sp(r);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function q(r){return r.replace(/\\n/g,`
|
|
1911
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function M(r,e){return r.length<=e?r:r.slice(0,e-3)+"..."}function Ie(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0}function ap(r){return r==="file-history-snapshot"||r==="progress"||r==="system"||r==="queue-operation"}function lp(r){if(r.type==="system"){let e=r.message?.content;if(typeof e=="string"&&e.trim())return q(e.trim());if(e!==void 0)return JSON.stringify(e,null,2)}return r.type==="progress"&&r.data!==void 0?JSON.stringify(r.data,null,2):JSON.stringify(r,null,2)}async function rl(r){let e=0,t=0,n=0,s=0,i=0,o=0,a,l;for await(let c of Z(r))if(!c.isSidechain){if(c.type==="user"&&!c.isMeta&&c.message){let u=c.message.content;if(typeof u=="string"){if(u.includes("<command-name>")||u.includes("<local-command-"))continue;e++,l=M(u.trim(),80)}}else if(c.type==="assistant"&&c.message){let u=c.message.content;if(Array.isArray(u))for(let m of u)m.type==="text"&&e++;let d=c.message.usage;if(d){let m=d.input_tokens||0,h=d.cache_creation_input_tokens||0,f=d.cache_read_input_tokens||0,T=d.output_tokens||0;t+=m+h+f,n+=f,s+=h,i+=T;let _=m+h+f;_&&(o=_),a={inputTokens:m,cacheWriteInputTokens:h,cachedInputTokens:f,outputTokens:T}}}}return{messageCount:e,totalInputTokens:t,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}var sn=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Nt(U,".claude"),this.projectsDir=Nt(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],t;try{t=await nn(this.projectsDir)}catch{return e}for(let n of t){let s=Nt(this.projectsDir,n);if(!(await el(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await nn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=tl(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Nt(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,t){let n=await ye(e,50),s=await te(e),i="",o,a,l,c,u,d;for(let h of n)if(!ap(h.type)&&(!i&&h.cwd&&(i=h.cwd),!o&&h.slug&&(o=h.slug),!a&&h.version&&(a=h.version),!d&&h.timestamp&&(d=new Date(h.timestamp)),h.type==="assistant"&&h.message?.model&&(l=h.message.model),h.type==="user"&&!h.isMeta&&h.message)){let f=h.message.content;if(typeof f=="string"){if(f.includes("<command-name>")||f.includes("<local-command-"))continue;c||(c=M(f.trim(),80)),u=M(f.trim(),80)}}if(!i)return null;let m=await rl(e);return{provider:"claude",sessionId:t,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,totalOutputTokens:m.totalOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async loadSession(e){let t=await this.resolveSessionFile(e);if(!t)return null;let n=await te(t),s=[],i="",o,a,l,c,u,d,m,h=e,f,T=[];for await(let p of Z(t))if(p.type!=="file-history-snapshot"&&!p.isSidechain){if(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!c&&p.gitBranch&&(c=p.gitBranch),!m&&p.timestamp&&(m=new Date(p.timestamp)),p.sessionId&&(h=p.sessionId),p.type==="system"||p.type==="progress"||p.type==="queue-operation"){s.push({role:"system",timestamp:new Date(p.timestamp||0),content:lp(p)});continue}if(p.type==="user"&&p.message){if(p.isMeta)continue;let g=new Date(p.timestamp||0),E=p.message.content;if(p.isCompactSummary!==!0&&p.isVisibleInTranscriptOnly!==!0&&p.promptSource!=="system"&&p.toolUseResult===void 0&&p.origin?.kind!=="task-notification"&&p.interruptedMessageId===void 0&&p.interruptedByShutdown!==!0&&p.scheduledTaskId===void 0&&p.scheduledFireId===void 0&&!(Array.isArray(E)&&E.some(w=>w.type==="tool_result"))){let w=typeof E=="string"?E:Array.isArray(E)?E.filter(I=>I.type==="text"&&typeof I.text=="string").map(I=>I.text).join(`
|
|
1912
|
+
`):"";w&&!/^<(?:command-name>|local-command-)/u.test(w.trimStart())&&T.push(w)}if(typeof E=="string"){if(E.includes("<command-name>")||E.includes("<local-command-"))continue;u||(u=M(E.trim(),80)),d=M(E.trim(),80),f=void 0,s.push({role:"user",timestamp:g,content:q(E.trim())})}else if(Array.isArray(E)){for(let w of E)if(w.type==="tool_result"){let I=typeof w.content=="string"?q(w.content):JSON.stringify(w.content);s.push({role:"tool_result",timestamp:g,content:I,toolCallId:w.tool_use_id})}}}if(p.type==="assistant"&&p.message){p.message.stop_reason===null||p.message.stop_reason==="tool_use"?f="in_progress":typeof p.message.stop_reason=="string"&&(f="complete"),p.message.model&&(l=p.message.model);let g=new Date(p.timestamp||0),E=p.message.content;if(Array.isArray(E))for(let w of E)w.type==="text"&&w.text?s.push({role:"assistant",timestamp:g,content:q(w.text),model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):w.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:w.name||"unknown tool",toolName:w.name,toolInput:JSON.stringify(w.input,null,2),toolInputData:w.input,toolCallId:w.id,model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):w.type==="thinking"&&w.thinking&&s.push({role:"thinking",timestamp:g,content:w.thinking})}}if(!i)return null;cp(s);let _=await rl(t);return{provider:"claude",sessionId:h,slug:o,cwd:i,createdAt:m||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:f,firstUserMessage:u,lastUserMessage:d,messageCount:_.messageCount,filePath:t,totalInputTokens:_.totalInputTokens||void 0,totalCachedInputTokens:_.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:_.totalCacheWriteInputTokens||void 0,totalOutputTokens:_.totalOutputTokens||void 0,lastInputTokens:_.lastInputTokens||void 0,lastTokenUsage:_.lastTokenUsage,messages:s,userPrompts:T}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let t=await this.resolveSessionFile(e);return t?(await op(t),!0):!1}async resolveSessionFile(e){let t;try{t=await nn(this.projectsDir)}catch{return null}let n=[];for(let o of t){let a=Nt(this.projectsDir,o);if(!(await el(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await nn(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=tl(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&n.push({filePath:Nt(a,u),fileSessionId:d})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await ye(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}};function cp(r){let e=dp(r),t=new Set;for(let n of r){if(n.role!=="tool_use"||n.toolName!=="Bash"||n.toolInputData?.run_in_background!==!0||n.toolCallId===void 0)continue;let s=e.get(n.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&&(t.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of r){if(n.role!=="tool_use"||n.toolName!=="TaskOutput"&&n.toolName!=="TaskStop"||n.toolCallId===void 0)continue;let s=n.toolInputData?.task_id;if(typeof s!="string"||!t.has(s))continue;n.backgroundTaskId=s;let i=e.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function dp(r){let e=new Map;for(let t of r)t.role==="tool_result"&&t.toolCallId!==void 0&&e.set(t.toolCallId,t);return e}import{spawn as cl}from"node:child_process";import{mkdirSync as xp}from"node:fs";import{readFileSync as up,writeFileSync as mS,mkdirSync as fS}from"node:fs";import{join as mp,dirname as hS}from"node:path";import{homedir as fp}from"node:os";var Ns={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:""}}}},pp={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 hp(r){return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r}function gp(r){let e=r.indexOf("=");if(e===-1)return null;let t=r.slice(0,e).trim(),n=hp(r.slice(e+1).trim());return t?{key:t,value:n}:null}function _p(r){let e=r.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function on(r){return"'"+r.replace(/'/g,"'\\''")+"'"}function Ep(){return mp(fp(),".lmctl","config.toml")}function sl(r){let e=r??Ep(),t;try{t=up(e,"utf-8")}catch{return{tools:{}}}return yp(t)}function nl(r){if(typeof r=="number")return Number.isFinite(r)?r:null;let e=String(r).trim();if(!e)return null;let t=e.match(/^(\d+(?:\.\d+)?)\s*([KkMm]?)$/);if(!t)return null;let n=parseFloat(t[1]);if(!Number.isFinite(n))return null;switch(t[2]){case"K":case"k":return Math.round(n*1e3);case"M":case"m":return Math.round(n*1e6);default:return Math.round(n)}}function yp(r){let e={},t={},n=r.split(`
|
|
1913
|
+
`),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?t.providers?.[s.provider]??{}:t.global??{};if(i.min!==void 0){let m=nl(i.min);m!==null&&(d.min=m)}if(i.max!==void 0){let m=nl(i.max);m!==null&&(d.max=m)}s.provider?(t.providers||(t.providers={}),t.providers[s.provider]=d):t.global=d}i={}}for(let d of n){let m=d.trim();if(!m||m.startsWith("#"))continue;let h=_p(m);if(h!==null){if(o=!0,l(),h.startsWith("tool.")){let T=".profile.",_=h.indexOf(T);_!==-1?s={kind:"tool",tool:h.slice(5,_),profile:h.slice(_+T.length)}:s={kind:"tool",tool:h.slice(5),profile:null}}else h==="compact"?s={kind:"compact",provider:null}:h.startsWith("compact.")?s={kind:"compact",provider:h.slice(8)}:s={kind:"none"};continue}let f=gp(m);f&&s.kind!=="none"?i[f.key]=f.value:f&&!o&&(a[f.key]=f.value)}l();let c={tools:e};(t.global||t.providers)&&(c.compact=t);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function Tp(r,e,t){if(!t)return"";let n=r.tools[e]??Ns[e],s=n?.profiles?.[t]?.flags??Ns[e]?.profiles?.[t]?.flags;if(s!==void 0)return s.trim();if(n?.profile_flag)return n.profile_flag.replace(/\{\{profile\}\}/g,t).trim();throw new Error(`Profile "${t}" is not configured for tool "${e}"`)}function il(r,e){return!!r.tools[e]}function ol(r,e,t,n,s){let i=r.tools[e]??Ns[e],o;if(i?.agent){let l=on(n);o=i.agent.replace(/\{\{session_id\}\}/g,t).replace(/\{\{prompt\}\}/g,l)}else{let l=pp[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,t).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let u=c.map(on).join(" ");o=`printf '%s\\n' ${on(n)} | ${u}`}else o=c.map(on).join(" ")}let a=Tp(r,e,s);return a&&(o+=" "+a),o}function al(r=process.env){let e=r.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let t=Number(e);return!Number.isFinite(t)||t<=0?6e5:t}var Sp="ACK: waiting for explicit lmctl task.",W=`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: ${Sp}`,an=`send this exact lmctl seed instruction: "${W}"`;import{existsSync as vp}from"node:fs";var ks="LMCTL_SELF_SESSIONID",wp="LMCTL_LAUNCH_SOURCE";function ll(r){let e=r.CLAUDE_CODE_EXECPATH;if(e===void 0||e.length===0)return r;let t=process.platform!=="win32"&&e.toLowerCase().endsWith(".exe"),n=!t&&!vp(e);if(!t&&!n)return r;b({event:"claude_execpath_sanitized",reason:t?"wrong_platform_exe":"missing_file",value:e,platform:process.platform});let s={...r};return delete s.CLAUDE_CODE_EXECPATH,s}function kt(r,e){let t={...r??process.env,PWD:e};return delete t.OLDPWD,t}function Ip(r,e){return e===void 0||e.length===0?r:{...r??process.env,[ks]:e}}function ce(r,e,t,n="chat"){return{...Ip(kt(r,e),t),[wp]:n}}function er(r){return r.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Ls=class r extends Error{cancelReason;constructor(e,t){super(e),this.name="TurnAbortError",this.cancelReason=t,Object.setPrototypeOf(this,r.prototype)}},V=class r{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){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.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 t=e?.prompt;return t===void 0?this.seedArgs:this.seedArgs.map(n=>n===W?t:n)}turnOptsFor(e){return e}seed(e,t){return xp(e,{recursive:!0}),new Promise(n=>{let s;try{s=cl(this.binary,this.seedArgsFor(t),{cwd:e,env:kt(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(l){return n({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=t?.prompt!==void 0&&this.seedStdin!==void 0?`${t.prompt}
|
|
1914
|
+
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",l=>{if(l===0||l===null)n({success:!0});else{let c=er(o).trim(),u=er(i).trim();n({success:!1,error:(c||u).slice(0,500)||`exit code ${l}`})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,t){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:an,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,t){let n=this.turnOptsFor(t);if(n.userConfig&&il(n.userConfig,this.name)){let i=n.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,n,i.agent)}let s=n.timeoutMs??r.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,t,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:f=>{a+=f,c(),n.onDelta?.(f)},onProgress:f=>{f.kind!=="api_retry"&&c(),n.onProgress?.(f)}},m=this.transportFn(t,d).then(f=>(u(),{...f,status:f.status??"ok"})).catch(f=>{throw u(),o==="external"?new Ls("Turn cancelled","external"):f}),h=new Promise(f=>{l=f});return Promise.race([m,h])}runOneShotAgent(e,t,n){let s=ol(t.userConfig,this.name,t.sessionId,e,t.profile),i=Date.now();return new Promise((o,a)=>{let l=al(t.env),c=cl(s,{shell:!0,cwd:t.cwd,env:ce(t.env,t.cwd,t.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m=setTimeout(()=>{d=!0,c.kill()},l),h="",f="";if(c.stdout?.on("data",T=>{let _=T.toString();h+=_,t.onDelta?.(_)}),c.stderr?.on("data",T=>{f+=T.toString()}),t.signal){if(t.signal.aborted)return clearTimeout(m),c.kill(),a(new Error("Aborted"));t.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",T=>{if(u)return;u=!0,clearTimeout(m);let _=Date.now()-i;d?a(new Error(`Agent command timed out after ${l}ms`)):T===0||T===null?o({text:h.trim(),sessionId:t.sessionId,durationMs:_}):a(new Error(f.trim().slice(0,200)||`Agent command exited with code ${T}`))}),c.on("error",T=>{u||(u=!0,clearTimeout(m),a(T))})})}};import{spawn as hl}from"node:child_process";import{existsSync as gl}from"node:fs";var tr=class extends Error{constructor(e,t){super(e,t),this.name=this.constructor.name}},K=class extends tr{};var ln=class extends tr{rpcCode;rpcData;constructor(e,t,n){super(e),t!==void 0&&(this.rpcCode=t),n!==void 0&&(this.rpcData=n)}};function rr(r,e){let t;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(t=n)}return new ln(r,t,e)}import*as Os from"node:child_process";var Ap=1e3;function bp(r){if(typeof Os.spawnSync=="function")try{Os.spawnSync("taskkill",["/T","/F","/PID",String(r)],{windowsHide:!0})}catch{}}function dl(r){return r.exitCode!==null||r.signalCode!==null}function Cs(r,e){return dl(r)?Promise.resolve(!0):new Promise(t=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(i),t(!0))},i=setTimeout(()=>{n||(n=!0,r.removeListener("exit",s),t(!1))},e);r.once("exit",s)})}async function Y(r,e={}){let t=Date.now(),n=e.stdinEnd!==!1,s=e.softDelayMs??5e3,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??bp;if(dl(r))return{signal:"natural",elapsedMs:Date.now()-t};if(n&&r.stdin&&!r.stdin.destroyed)try{r.stdin.end()}catch{}if(await Cs(r,s))return{signal:"stdin",elapsedMs:Date.now()-t};if(o==="win32"&&typeof r.pid=="number")a(r.pid);else try{r.kill("SIGTERM")}catch{}if(await Cs(r,i))return{signal:"SIGTERM",elapsedMs:Date.now()-t};if(o!=="win32")try{r.kill("SIGKILL")}catch{}return await Cs(r,Ap)?{signal:"SIGKILL",elapsedMs:Date.now()-t}:{signal:"abandoned",elapsedMs:Date.now()-t}}function ul(r){z()&&ge({event:"legacy",msg:`[debug] ${r}`},{always:!0})}var Rp={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},Np={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"]}};function Ke(r,e){let t=Np[r];if(t)return t[e]??t.yolo}var kp=new Set(["codex","opencode","kimi","dsh","hermes","pi"]);function Lp(r,e){if(e.length===0)return!0;for(let t=0;t+e.length<=r.length;t++){let n=!0;for(let s=0;s<e.length;s++)if(r[t+s]!==e[s]){n=!1;break}if(n)return!0}return!1}function oe(r,e,t="yolo"){if(kp.has(r)){ul(`YOLO ${r} [mode=${t}]: ${r==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${t==="plan"?"read-only":"danger-full-access"})`:r==="opencode"?".opencode/opencode.json (permission=allow)":r==="kimi"?`ACP session/set_config_option (configId=mode, value=${t==="plan"?"plan":"auto"})`:r==="dsh"?"DSH_PERMISSION_MODE=danger-full-access env var on the sidecar spawn \u2014 no argv flag":r==="hermes"?"HERMES_YOLO_MODE=1 shell gate + ACP session/set_mode (modeId=dont_ask) edit gate":r==="pi"?"no tool-permission prompts exist in pi by design \u2014 nothing to bypass":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=t==="plan"?Ke(r,"plan"):Rp[r];if(!n){let s=`unknown provider "${r}" \u2014 YOLO contract not configured. Add an entry to YOLO_FLAGS in src/providers/yolo-contract.ts before spawning this provider.`;throw b({event:"yolo_assert_failed",provider:r,reason:"unconfigured_provider",args:e.join(" "),message:s}),new K(s)}if(!Lp(e,n)){let s=n.join(" "),i=`${r} 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 b({event:"yolo_assert_failed",provider:r,reason:"flag_missing",required_flag:s,mode:t,args:e.join(" "),message:i}),new K(i)}ul(`YOLO ${r} [mode=${t}]: argv flag '${n.join(" ")}'`)}var Cp=2e3,cn=8*60*60*1e3,Op=5e3,Dp=1e3,Mp=50,Ds=Symbol("check-timed-out");async function dn(r,e,t){if(typeof r=="boolean")return r;let n,s;try{return await Promise.race([r,new Promise(i=>{n=setTimeout(()=>i(Ds),e),n.unref?.(),t!==void 0&&(s=()=>i(Ds),t.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&t?.removeEventListener("abort",s)}}function Ye(r,e){if(r===void 0){e.closeStdin();return}let t=!1,n=i=>{if(!t){t=!0;try{r.onRelease?.({elapsedMs:Date.now()-i.startedMs,held:i.held,reason:i.reason})}catch{}}e.closeStdin()},s=Date.now();Fp(r,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function Fp(r,e,t,n){let s=r.pollMs??Cp,i=r.maxHoldMs??cn,o=r.settleMs??Op,a=r.backgroundGraceMs??Dp,l=!1,c=null,u=d=>n({startedMs:t,held:l,reason:d});for(;;){if(e.isAborted())return u("aborted");if(e.hasChildExited())return u("child-exited");let d=i-(Date.now()-t);if(d<=0)return u("max-hold");let m;try{m=await dn(r.hasOutstandingWork(),d,e.signal)}catch{return u("check-error")}if(m===Ds)return u(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(m)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-t<a){let T=a-(Date.now()-t);await new Promise(_=>setTimeout(_,Math.max(0,Math.min(s,Mp,T))).unref?.());continue}if(!l||o<=0)return u("cleared");c===null&&(c=Date.now(),ie(`${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,r.onHold?.(),ie(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-t>=i)return b({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-t}),u("max-hold");let h=Math.max(0,Math.min(s,i-(Date.now()-t)));await new Promise(f=>setTimeout(f,h).unref?.())}}function ml(r){if(r.length===0)return"";if(r.length===1)return r[0];let e=[];for(let t=0;t<r.length;t++)t===0?e.push(r[t]):e.push(`
|
|
1915
1915
|
|
|
1916
1916
|
--- additional response (turn ${t+1} of ${r.length}; likely an injected mid-call notification) ---
|
|
1917
1917
|
|
|
1918
|
-
`+r[t]);return e.join("")}function un(r={}){let e=[],t="",n=!1;return{processLine(s){if(!s.trim())return;let i;try{i=JSON.parse(s)}catch{return}r.onEvent?.(i);let o=i.type;if(o==="system"&&i.subtype==="init"&&(t=i.session_id||t),o==="assistant"){let l=i.message?.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&r.onText?.(c.text)}o==="result"&&(n=!0,e.push(i))},sawResult(){return n},finalize(){if(!n)return null;let s=fl(e),i=ml(s.resultTexts);return{result:i,sessionId:s.sessionId||t,durationMs:s.durationMs,numTurns:s.numTurns,isError:s.isError&&i.trim().length===0,errorMessage:s.errorMessage}}}}function fl(r){let e=[],t=0,n=0,s="",i=!1,o;for(let a of r){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(t+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(n=c);let u=a.session_id;if(typeof u=="string"&&u&&(s=u),a.is_error===!0){i=!0;let d=a.errors,
|
|
1918
|
+
`+r[t]);return e.join("")}function un(r={}){let e=[],t="",n=!1;return{processLine(s){if(!s.trim())return;let i;try{i=JSON.parse(s)}catch{return}r.onEvent?.(i);let o=i.type;if(o==="system"&&i.subtype==="init"&&(t=i.session_id||t),o==="assistant"){let l=i.message?.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&r.onText?.(c.text)}o==="result"&&(n=!0,e.push(i))},sawResult(){return n},finalize(){if(!n)return null;let s=fl(e),i=ml(s.resultTexts);return{result:i,sessionId:s.sessionId||t,durationMs:s.durationMs,numTurns:s.numTurns,isError:s.isError&&i.trim().length===0,errorMessage:s.errorMessage}}}}function fl(r){let e=[],t=0,n=0,s="",i=!1,o;for(let a of r){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(t+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(n=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,h=typeof a.subtype=="string"?a.subtype:"unknown";o=m&&m.length>0?m:`result subtype=${h} (no error detail provided)`}}return{resultTexts:e,durationMs:t,numTurns:n,sessionId:s,isError:i,errorMessage:o}}import{join as mn}from"node:path";import{readdir as Pp}from"node:fs/promises";var Up={claude:"claude",qwen:"qwen"};function _l(){let r=process.env.LMCTL_RESULT_GRACE_TIMEOUT_MS;if(r===void 0||r.trim().length===0)return 12e4;let e=Number(r);return Number.isFinite(e)&&e>0?e:12e4}function El(){let r=process.env.LMCTL_TOOL_USE_GRACE_TIMEOUT_MS;if(r===void 0||r.trim().length===0)return 27e5;let e=Number(r);return Number.isFinite(e)&&e>0?e:27e5}function yl(r){let t=r.message?.content;return Array.isArray(t)?t.some(n=>n?.type==="tool_use"):!1}function $p(r){let e=r.stderr.trim().slice(0,500),t=`lmctl: ${r.tool} exited with code ${r.exitCode} before returning a final result event.
|
|
1919
1919
|
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:
|
|
1920
1920
|
${e}
|
|
1921
1921
|
|
|
1922
|
-
${t}`:t}var jp={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]};function Tl(r){let e=r.tool||"claude",t=r.binaryPath||Up[e]||"claude",n=["-p","","--output-format","stream-json","--input-format","stream-json"];e==="claude"&&n.push("--verbose"),r.sessionId&&n.push("--resume",r.sessionId),r.model&&n.push("--model",r.model);let s=r.permissionMode??"yolo",i=
|
|
1923
|
-
`);d=
|
|
1924
|
-
`),ie(`stream-json: prompt sent (${r.length} chars)`)})}function Bp(r){return r==="qwen"?[mn(
|
|
1925
|
-
`);D=F.pop()||"";for(let ne of F)jt(ne)}),i.on("error",
|
|
1926
|
-
`),ie(`stream-json bundle: prompt sent (${
|
|
1922
|
+
${t}`:t}var jp={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]};function Tl(r){let e=r.tool||"claude",t=r.binaryPath||Up[e]||"claude",n=["-p","","--output-format","stream-json","--input-format","stream-json"];e==="claude"&&n.push("--verbose"),r.sessionId&&n.push("--resume",r.sessionId),r.model&&n.push("--model",r.model);let s=r.permissionMode??"yolo",i=Ke(e,s)??jp[e]??["--dangerously-skip-permissions"];if(n.push(...i),oe(e,n,s),r.cwd&&!gl(r.cwd))throw b({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${r.cwd}`,elapsed_ms:0}),new K(`sessiondir missing: ${r.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=ce(r.env,r.cwd,r.sessionId);return{tool:e,binary:t,args:n,spawnEnv:e==="claude"?ll(o):o}}function Sl(r,e){return new Promise((t,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=Tl(e))}catch(D){return n(D instanceof Error?D:new Error(String(D)))}let c=hl(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",D=>{ie(`stream-json: stdin pipe error, ignored (exit handler reports): ${D.message}`)});let u=!1;if(e.signal){if(e.signal.aborted)return u=!0,b({event:"transport_abort",provider:i,phase:"pre_spawn"}),Y(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,b({event:"transport_abort",provider:i}),Y(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let d="",m=!1,h=!1,f=0,T=!1,_="",p="",g,E,w=null,I=null,y=!1,v=!1,S=_l(),x=El();function A(){g!==void 0&&(clearTimeout(g),g=void 0)}function N(){E!==void 0&&(clearTimeout(E),E=void 0)}let P=null;function k(){return m||u||ae.sawResult()}function j(D){return D==="text_done"?S:x}async function ee(D){if(D==="text_done"?g=void 0:E=void 0,k()||w!==null)return;P??=Date.now();let X=j(D);if(e.holdOpen){let jt=(e.holdOpen.maxHoldMs??cn)-(Date.now()-P),Kn=jt>0?await dn(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),jt,e.signal):!1;if(k()||(D==="text_done"?g!==void 0:E!==void 0))return;if(Kn===!0){b({event:"transport_stall_grace_deferred",provider:i,grace_kind:D,grace_ms:X,reason:"outstanding_dispatched_work"}),G(D);return}}I=D,w=D==="text_done"?`${i} finished responding but never emitted its closing result event (${X}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${X}ms of silence)`,b({event:"transport_stall_grace_fired",provider:i,grace_kind:D,grace_ms:X}),Y(c).catch(()=>{})}function G(D){let X=setTimeout(()=>{ee(D)},j(D));X.unref?.(),D==="text_done"?(A(),g=X):(N(),E=X)}let ae=un({onEvent:D=>{f=Date.now(),T=D.type!=="result",D.type==="system"&&D.subtype==="init"&&(p=D.session_id||p),D.type==="assistant"?(y=!yl(D),v=y&&D.message?.stop_reason==="pause_turn"):(D.type==="result"||D.type==="user")&&(y=!1,v=!1),A(),i==="claude"&&y&&!v&&!ae.sawResult()&&G("text_done"),N(),i==="claude"&&!ae.sawResult()&&G("tool_use_silence"),e.onEvent?.(D)},onText:D=>{_+=D,e.onText?.(D)}});function pe(){h||(h=!0,Ye(e.holdOpen,{isAborted:()=>u,hasChildExited:()=>m,isTurnInFlight:()=>T,lastEventAtMs:()=>f,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function J(D){let X=ae.sawResult();ae.processLine(D),!X&&ae.sawResult()&&pe()}c.stdout?.on("data",D=>{d+=D.toString();let X=d.split(`
|
|
1923
|
+
`);d=X.pop()||"";for(let Ir of X)J(Ir)});let le="";c.stderr?.on("data",D=>{le+=D.toString()}),c.on("error",D=>{b({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:D.message}),n(new K(`Failed to spawn ${o}: ${D.message}`,{cause:D}))}),c.on("exit",D=>{if(m=!0,A(),N(),u)return;d.trim()&&J(d);let X=ae.finalize();X?.isError?(b({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:X.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${X.errorMessage??"unknown error"}`))):X?(ie(`stream-json: result ${X.result.slice(0,80)}${X.result.length>80?"...":""} (${X.durationMs}ms)`),t({result:X.result,sessionId:X.sessionId,durationMs:X.durationMs,numTurns:X.numTurns,exitCode:D})):w!==null&&I==="text_done"&&_.trim().length>0?(b({event:"transport_stall_finalized",provider:i,reason:w,text_len:_.length}),t({result:_,sessionId:p||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:D,warnings:[w]})):w!==null&&I==="tool_use_silence"?(b({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:D,stderr_tail:le.slice(0,500)}),n(new Error(`${w} \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})`:"")))):(b({event:"transport_error",provider:i,error_class:"Error",reason:w!==null?"provider_stalled_no_content":"provider_no_result",exit_code:D,stderr_tail:le.slice(0,500)}),n(new Error(w!==null?`${w} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):$p({tool:i,exitCode:D,stderr:le}))))});let Ue=JSON.stringify({type:"user",message:{role:"user",content:r}});c.stdin?.write(Ue+`
|
|
1924
|
+
`),ie(`stream-json: prompt sent (${r.length} chars)`)})}function Bp(r){return r==="qwen"?[mn(U,".qwen","projects")]:[mn(U,".claude","projects")]}async function pl(r,e,t){let n=t??Bp(r),s=null;for(let a of n){let l;try{l=await Pp(a)}catch{continue}for(let c of l){for(let u of[mn(a,c,`${e}.jsonl`),mn(a,c,"chats",`${e}.jsonl`)])if(gl(u)){s=u;break}if(s!==null)break}if(s!==null)break}if(s===null)throw new Error(`stream-json bundle: no session file for session "${e}" under ${n.join(", ")} \u2014 the session must exist on disk before a bundle can resume it`);let o=(await ye(s,5).catch(()=>[])).map(a=>a?.sessionId).find(a=>typeof a=="string"&&a.length>0);if(o!==e)throw new Error(`stream-json bundle: session file ${s} header does not match the requested session (expected "${e}", header carries ${o??"no sessionId"}) \u2014 the session was likely re-seeded externally; aborting instead of writing into the wrong session`)}async function vl(r){let{tool:e,binary:t,args:n,spawnEnv:s}=Tl(r),i=hl(t,n,{cwd:r.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",R=>{ie(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${R.message}`)});let a={exited:!1,exitCode:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=r.sessionId||"",c=null,u="";i.stderr?.on("data",R=>{u+=R.toString()});let d="",m="",h=!1,f=!1,T=null,_=null,p=null,g,E,w=_l(),I=El(),y=null,v=[],S=()=>a.exited?Promise.resolve():new Promise(R=>{v.push(R)}),x=()=>new Error(`stream-json bundle process (${e}) exited${a.exitCode!==null?` with code ${a.exitCode}`:""} after ${a.completedTurns} completed prompt(s); the bundle cannot continue`);function A(){g!==void 0&&(clearTimeout(g),g=void 0)}function N(){E!==void 0&&(clearTimeout(E),E=void 0)}function P(){return a.exited||y===null||y.aborted||y.processor.sawResult()}function k(R){return R==="text_done"?w:I}async function j(R){if(R==="text_done"?g=void 0:E=void 0,P()||T!==null)return;p??=Date.now();let F=k(R);if(r.holdOpen){let Et=(r.holdOpen.maxHoldMs??cn)-(Date.now()-p),xr=Et>0?await dn(Promise.resolve(r.holdOpen.hasOutstandingWork()).catch(()=>!1),Et,void 0):!1;if(P()||(R==="text_done"?g!==void 0:E!==void 0))return;if(xr===!0){b({event:"transport_stall_grace_deferred",provider:e,grace_kind:R,grace_ms:F,reason:"outstanding_dispatched_work"}),ee(R);return}}_=R,T=R==="text_done"?`${e} finished responding but never emitted its closing result event (${F}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${F}ms of silence)`,b({event:"transport_stall_grace_fired",provider:e,grace_kind:R,grace_ms:F}),Y(i).catch(()=>{})}function ee(R){let F=setTimeout(()=>{j(R)},k(R));F.unref?.(),R==="text_done"?(A(),g=F):(N(),E=F)}let G=!1,ae,pe,J=new Promise((R,F)=>{ae=R,pe=F});J.catch(()=>{});let le=setTimeout(()=>{G||(G=!0,pe(new Error(`stream-json bundle: ${e} emitted no init event within the open timeout \u2014 cannot verify the resumed session identity`)))},r.closeTimeoutMs!==void 0?Math.max(r.closeTimeoutMs,5e3):3e4);le.unref?.();function Ue(R){G||(G=!0,clearTimeout(le),R?pe(R):ae())}let D="";function X(R){if(a.lastEventAtMs=Date.now(),R.type==="system"&&R.subtype==="init"){if(m=R.session_id||m,r.sessionId&&typeof R.session_id=="string"&&R.session_id.length>0&&R.session_id!==r.sessionId){let ne=new Error(`stream-json bundle: provider resumed a different session (init reported "${R.session_id}", expected "${r.sessionId}")`);Ue(ne),Y(i).catch(()=>{});return}Ue()}let F=y?.processor.sawResult()??!0;R.type==="assistant"?(h=!yl(R),f=h&&R.message?.stop_reason==="pause_turn"):(R.type==="result"||R.type==="user")&&(h=!1,f=!1),A(),e==="claude"&&a.turnActive&&h&&!f&&!F&&ee("text_done"),N(),e==="claude"&&a.turnActive&&!F&&ee("tool_use_silence")}function Ir(){let R=y;if(R===null)return;let F=R.processor.finalize();if(F!==null){if(y=null,a.turnActive=!1,A(),N(),F.isError){b({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:F.errorMessage}),R.reject(new Error(`${e} reported an error for this turn (no assistant output)`+(r.sessionId?` \u2014 session=${r.sessionId}`:"")+`: ${F.errorMessage??"unknown error"}`));return}a.completedTurns+=1,l=F.sessionId||l,ie(`stream-json bundle: result ${F.result.slice(0,80)}${F.result.length>80?"...":""} (${F.durationMs}ms)`),R.resolve({result:F.result,sessionId:F.sessionId||l,durationMs:F.durationMs,numTurns:F.numTurns})}}function jt(R){if(!R.trim())return;let F;try{F=JSON.parse(R)}catch{return}X(F);let ne=y;if(ne!==null){let Et=ne.processor.sawResult();ne.processor.processLine(R),ne.onEventForward?.(F),!Et&&ne.processor.sawResult()&&Ir()}}i.stdout?.on("data",R=>{D+=R.toString();let F=D.split(`
|
|
1925
|
+
`);D=F.pop()||"";for(let ne of F)jt(ne)}),i.on("error",R=>{if(c=new K(`Failed to spawn ${t}: ${R.message}`,{cause:R}),b({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:R.message}),Ue(c),y!==null){let F=y;y=null,a.turnActive=!1,F.reject(c)}}),i.on("exit",R=>{a.exited=!0,a.exitCode=R,A(),N(),D.trim()&&jt(D),Ue(a.exited&&!G?new Error(`stream-json bundle: ${e} exited (code ${String(R)}) before its init event`):void 0);let F=y;F!==null&&(y=null,a.turnActive=!1,F.aborted||(T!==null&&_==="text_done"&&d.trim().length>0?(b({event:"transport_stall_finalized",provider:e,reason:T,text_len:d.length}),F.resolve({result:d,sessionId:m||r.sessionId||"",durationMs:Date.now()-F.startMs,numTurns:1,warnings:[T]})):T!==null&&_==="tool_use_silence"?(b({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:R,stderr_tail:u.slice(0,500)}),F.reject(new Error(`${T} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(r.sessionId?` (session=${r.sessionId})`:"")))):(b({event:"transport_error",provider:e,error_class:"Error",reason:T!==null?"provider_stalled_no_content":"provider_no_result",exit_code:R,stderr_tail:u.slice(0,500)}),F.reject(x()))));for(let ne of v.splice(0))ne()});try{r.sessionId&&await pl(e,r.sessionId,r.sessionFileRoots),await J}catch(R){let F=c??(R instanceof Error?R:new Error(String(R))),ne=r.closeTimeoutMs??2e3;throw await Y(i,{softDelayMs:Math.min(1e3,ne),killDelayMs:Math.min(1e3,ne)}).catch(()=>{}),F}let Kn=R=>new Promise(F=>{setTimeout(F,R).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(R,F={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw x();if(y!==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 ne=()=>(a.closed=!0,Y(i).catch(()=>{}),new Error("Aborted"));if(F.signal?.aborted)throw ne();if(r.sessionId&&(await pl(e,r.sessionId,r.sessionFileRoots),a.exited))throw x();if(F.signal?.aborted)throw ne();return d="",h=!1,f=!1,T=null,_=null,p=null,new Promise((Et,xr)=>{let Yn={processor:un({onText:eo=>{d+=eo,F.onText?.(eo)}}),resolve:Et,reject:xr,startMs:Date.now(),aborted:!1,onEventForward:F.onEvent};y=Yn,a.turnActive=!0;let Kd=()=>{Yn.aborted=!0,b({event:"transport_abort",provider:e}),a.closed=!0,Y(i).catch(()=>{}),y===Yn&&(y=null,a.turnActive=!1),xr(new Error("Aborted"))};F.signal?.addEventListener("abort",Kd,{once:!0});let Yd=JSON.stringify({type:"user",message:{role:"user",content:R}});i.stdin?.write(`${Yd}
|
|
1926
|
+
`),ie(`stream-json bundle: prompt sent (${R.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(r.holdOpen!==void 0?await new Promise(R=>{Ye(r.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),R()},label:e})}):i.stdin?.end(),!a.exited)){let R=r.closeTimeoutMs??2e3;await Promise.race([S(),Kn(R)]),a.exited||await Y(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,R),killDelayMs:Math.min(1e3,R)}).catch(()=>{})}})()),a.closing}}}import{spawn as xl}from"node:child_process";import{createInterface as Al}from"node:readline";import{existsSync as Hp,readFileSync as Xp}from"node:fs";import{fileURLToPath as qp}from"node:url";function Ms(r={}){return[]}function Fs(r){return r==="plan"?"read-only":"danger-full-access"}function wl(r="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:r},capabilities:{experimentalApi:!1}}}function fn(){return{agentItems:new Map,resultText:""}}function Lt(r,e,t,n){let s=r.method;if(!s)return!1;let i=r.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),t?.(o),l.phase&&i&&(i._lmctlItemPhase=l.phase)):(e.resultText+=o,t?.(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(n&&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;n({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 pn(r){for(let[,e]of r.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(r.resultText+=e.buffer);r.agentItems.clear()}function Il(r){let e=r.params,t=e?.error,n=typeof t?.message=="string"?t.message:void 0,s=n&&n.length>0?n:"(no message)";return e?.willRetry===!0?{willRetry:!0}:{willRetry:!1,turnError:new Error(`Turn errored: ${s}`)}}function hn(){return{pendingCodexError:null}}function gn(r,e){let t=Il(r);return t.willRetry||(e.pendingCodexError=t.turnError),t}function _n(r,e){if(e.pendingCodexError){let i=e.pendingCodexError;return e.pendingCodexError=null,{shouldReject:!0,turnError:i}}let n=r.params?.turn;if((typeof n?.status=="string"?n.status:void 0)==="failed"){let i=n?.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 Gp=(()=>{try{let r=new URL("../../../package.json",import.meta.url),e=JSON.parse(Xp(qp(r),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})();function bl(){return wl(Gp)}function ze(r,e){ie(`[codex:${r}] ${JSON.stringify(e)}`)}function Jp(r){let e=r.stderr.trim().slice(0,500),t=`lmctl: codex app-server exited with code ${r.exitCode} before completing the turn.
|
|
1927
1927
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1928
1928
|
${e}
|
|
1929
1929
|
|
|
1930
|
-
${t}`:t}function Rl(r){let e=r.binaryPath||"codex",t=["app-server","--listen","stdio://"];r.model&&t.push("-c",`model=${JSON.stringify(r.model)}`);let n=r.isLead??r.alias?.toLowerCase()==="lead",s=n?Ms():[];t.push(...s),z()&&
|
|
1931
|
-
`)})}function
|
|
1932
|
-
`)}c.on("line",
|
|
1933
|
-
`),b({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:
|
|
1934
|
-
`)})}function
|
|
1935
|
-
`)}let
|
|
1930
|
+
${t}`:t}function Rl(r){let e=r.binaryPath||"codex",t=["app-server","--listen","stdio://"];r.model&&t.push("-c",`model=${JSON.stringify(r.model)}`);let n=r.isLead??r.alias?.toLowerCase()==="lead",s=n?Ms():[];t.push(...s),z()&&_e(JSON.stringify({event:"codex_mcp_inject",alias:r.alias??null,isLead:n,injected:s.length>0}));let i=r.permissionMode??"yolo",o=Fs(i);if(oe("codex",t,i),r.cwd&&!Hp(r.cwd))throw b({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${r.cwd}`}),new K(`sessiondir missing: ${r.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:e,codexArgs:t,sandbox:o,permissionMode:i,spawnEnv:ce(r.env,r.cwd,r.threadId)}}function Nl(r,e){return new Promise((t,n)=>{let s,i,o;try{({binary:s,codexArgs:i,sandbox:o}=Rl(e))}catch(y){return n(y instanceof Error?y:new Error(String(y)))}let a=xl(s,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:ce(e.env,e.cwd,e.threadId)}),l=!1;if(e.signal){if(e.signal.aborted)return l=!0,b({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),Y(a).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{l=!0,b({event:"transport_abort",provider:"codex"}),Y(a).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let c=Al({input:a.stdout}),u=new Map,d=1,m=e.threadId||"",h="",f=!1,T=!1,_=Date.now(),p=fn(),g=hn();function E(y,v={}){return new Promise((S,x)=>{let A=d++;u.set(A,{resolve:S,reject:x});let N=JSON.stringify({jsonrpc:"2.0",id:A,method:y,params:v});a.stdin?.write(N+`
|
|
1931
|
+
`)})}function w(y,v={}){let S=JSON.stringify({jsonrpc:"2.0",method:y,params:v});a.stdin?.write(S+`
|
|
1932
|
+
`)}c.on("line",y=>{let v;try{v=JSON.parse(y)}catch{return}if(typeof v.id=="number"&&u.has(v.id)){let A=u.get(v.id);if(u.delete(v.id),v.error){let N=v.error,P=typeof N?.message=="string"&&N.message.length>0?N.message:JSON.stringify(v.error);A.reject(rr(`codex app-server error: ${P}`,N))}else A.resolve(v);e.onEvent?.(v);return}let S=v.method;if(!S){e.onEvent?.(v);return}if(S==="thread/started"){let N=v.params?.thread;N?.id&&(m=N.id)}let x=z()?A=>{ze("item.text/buffer-mismatch",{itemId:A.itemId,threadId:A.threadId??null,turnId:A.turnId??null,expectedFromItemText:A.expectedFromItemText,gotFromBuffer:A.gotFromBuffer,expectedLen:A.expectedFromItemText.length,gotLen:A.gotFromBuffer.length})}:void 0;if(S==="turn/started"){let A=v.params,N=A?.turn;N?.id&&(h=N.id),Lt(v,p,e.onDelta,x),z()&&ze("turn/started",{params:A??null})}if(z()&&(S==="item/started"||S==="item/completed")){let A=v.params;A?.item?.type==="agentMessage"&&ze(S,{params:A??null})}if(S==="item/started"||S==="item/agentMessage/delta"||S==="item/completed"){if(S==="item/agentMessage/delta"){let A=v.params;z()&&ze("agentMessage/delta",{params:A??null})}Lt(v,p,e.onDelta,x)}if(S==="turn/completed"){let A=v.params;if(z())for(let[P,k]of p.agentItems.entries())k.buffer&&ze("turn/completed/unflushed-item",{itemId:P,phase:k.phase,bufferLen:k.buffer.length});pn(p),z()&&ze("turn/completed",{params:A??null});let N=_n(v,g);N.shouldReject?(z()&&ze("turn/completed/terminal-reject",{message:N.turnError.message}),T=!0,f=!0,a.stdin?.end(),n(N.turnError)):(f=!0,a.stdin?.end())}if(S==="error"){let A=gn(v,g);if(z()){let N=v.params,P=N?.error,k=typeof P?.message=="string"?P.message:"(no message)";ze(A.willRetry?"error/retry":"error/terminal-deferred",{message:k,willRetry:A.willRetry,params:N??null})}}e.onEvent?.(v)});let I="";a.stderr?.on("data",y=>{I+=y.toString()}),a.on("error",y=>{b({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:y.message}),n(new K(`Failed to spawn codex app-server: ${y.message}`,{cause:y}))}),a.on("exit",y=>{if(!l&&!T){if(f){t({result:p.resultText,threadId:m,turnId:h,durationMs:Date.now()-_,exitCode:y});return}if(g.pendingCodexError){n(g.pendingCodexError);return}b({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:y,stderr_tail:I.slice(0,500)}),n(new Error(Jp({exitCode:y,stderr:I})))}}),(async()=>{try{if(await E("initialize",bl()),w("initialized",{}),e.threadId)try{let y=E("thread/resume",{threadId:e.threadId,sandbox:o,approvalPolicy:"never",...e.model?{model:e.model}:{}}),v=new Promise((S,x)=>setTimeout(()=>x(new Error("resume timeout")),3e4));await Promise.race([y,v]),m=e.threadId}catch(y){process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1933
|
+
`),b({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:y instanceof Error?y.message:String(y)});let S=(await E("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;S?.id&&(m=S.id)}else{let v=(await E("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;v?.id&&(m=v.id)}await E("turn/start",{threadId:m,input:[{type:"text",text:r}],...e.model?{model:e.model}:{}})}catch(y){Y(a).catch(()=>{}),n(y instanceof Error?y:new Error(String(y)))}})()})}async function kl(r){let{binary:e,codexArgs:t,sandbox:n}=Rl(r),s=xl(e,t,{cwd:r.cwd,stdio:["pipe","pipe","pipe"],env:ce(r.env,r.cwd,r.threadId)}),i=Date.now(),o={exited:!1,exitCode:null,completedTurns:0,closed:!1,closing:null},a=r.threadId||"",l=null,c="";s.stderr?.on("data",I=>{c+=I.toString()});let u=Al({input:s.stdout}),d=new Map,m=1;function h(I,y={}){return new Promise((v,S)=>{let x=m++;d.set(x,{resolve:v,reject:S});let A=JSON.stringify({jsonrpc:"2.0",id:x,method:I,params:y});s.stdin?.write(A+`
|
|
1934
|
+
`)})}function f(I,y={}){let v=JSON.stringify({jsonrpc:"2.0",method:I,params:y});s.stdin?.write(v+`
|
|
1935
|
+
`)}let T=[],_=()=>o.exited?Promise.resolve():new Promise(I=>{T.push(I)}),p=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),g=null;function E(I){let y=g;y===null||y.settled||(y.settled=!0,g=null,I&&y.reject(I))}u.on("line",I=>{let y;try{y=JSON.parse(I)}catch{return}if(typeof y.id=="number"&&d.has(y.id)){let x=d.get(y.id);if(d.delete(y.id),y.error){let A=y.error,N=typeof A?.message=="string"&&A.message.length>0?A.message:JSON.stringify(y.error);x.reject(rr(`codex app-server error: ${N}`,A))}else x.resolve(y);g?.onEvent?.(y);return}let v=y.method;if(!v){g?.onEvent?.(y);return}if(v==="thread/started"){let A=y.params?.thread;A?.id&&(a=A.id)}let S=g;if(v==="turn/started"&&S!==null){let A=y.params?.turn;A?.id&&(S.turnId=A.id),Lt(y,S.agentState,S.onDelta,void 0)}if(S!==null&&(v==="item/started"||v==="item/agentMessage/delta"||v==="item/completed")&&Lt(y,S.agentState,S.onDelta,void 0),v==="turn/completed"&&S!==null&&!S.settled){pn(S.agentState);let x=_n(y,S.turnState);S.settled=!0,g=null,x.shouldReject?S.reject(x.turnError):(o.completedTurns+=1,S.resolve({text:S.agentState.resultText,sessionId:a,turnId:S.turnId,durationMs:Date.now()-S.startMs}))}v==="error"&&S!==null&&gn(y,S.turnState),S?.onEvent?.(y)}),s.on("error",I=>{l=new K(`Failed to spawn codex app-server: ${I.message}`,{cause:I}),b({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:I.message});for(let y of d.values())y.reject(l);d.clear(),E(l)}),s.on("exit",I=>{o.exited=!0,o.exitCode=I;let y=p();for(let S of d.values())S.reject(y);d.clear();let v=g;v!==null&&!v.settled&&(v.settled=!0,g=null,v.turnState.pendingCodexError?v.reject(v.turnState.pendingCodexError):(b({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:I,stderr_tail:c.slice(0,500)}),v.reject(y)));for(let S of T.splice(0))S()});try{if(await h("initialize",bl()),f("initialized",{}),r.threadId){let I;try{I=await h("thread/resume",{threadId:r.threadId,sandbox:n,approvalPolicy:"never",...r.model?{model:r.model}:{}})}catch(v){throw new Error(`Cannot resume codex thread ${r.threadId} for a bundle: ${v instanceof Error?v.message:String(v)} (the thread/start fallback is disabled in bundle mode)`)}let y=I.result?.thread;if(typeof y?.id=="string"&&y.id.length>0){if(y.id!==r.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${r.threadId}", received "${y.id}"`);a=y.id}}else{let y=(await h("thread/start",{cwd:r.cwd,approvalPolicy:"never",sandbox:n,...r.model?{model:r.model}:{}})).result?.thread;y?.id&&(a=y.id)}}catch(I){let y=l??(I instanceof Error?I:new Error(String(I))),v=r.closeTimeoutMs??2e3;throw await Y(s,{softDelayMs:Math.min(1e3,v),killDelayMs:Math.min(1e3,v)}).catch(()=>{}),y}let w=I=>new Promise(y=>{setTimeout(y,I).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(I,y={}){if(o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw p();if(g!==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(y.signal?.aborted)throw new Error("Aborted");return new Promise((v,S)=>{let x={agentState:fn(),turnState:hn(),resolve:v,reject:S,startMs:Date.now(),turnId:"",onDelta:y.onDelta,onEvent:y.onEvent,settled:!1};g=x;let A=()=>{x.settled||(x.settled=!0,g=null,x.turnId&&h("turn/interrupt",{threadId:a,turnId:x.turnId}).catch(()=>{}),S(new Error("Aborted")))};y.signal?.addEventListener("abort",A,{once:!0}),h("turn/start",{threadId:a,input:[{type:"text",text:I}],...r.model?{model:r.model}:{}}).catch(N=>{x.settled||(x.settled=!0,g=null,y.signal?.removeEventListener("abort",A),S(o.exited?p():N instanceof Error?N:new Error(String(N))))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,!o.exited&&(r.holdOpen!==void 0?await new Promise(I=>{Ye(r.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>g!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),I()},label:"codex"})}):s.stdin?.end(),!o.exited)){let I=r.closeTimeoutMs??2e3;await Promise.race([_(),w(I)]),o.exited||await Y(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,I),killDelayMs:Math.min(1e3,I)}).catch(()=>{})}})()),o.closing}}}import{spawn as Yl}from"node:child_process";import{existsSync as vh}from"node:fs";var Cl="(?:png|jpe?g|webp|heic|pdf)",Vp=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${Cl}\\s*`,"gi"),Kp=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${Cl}\\s*`,"i"),Yp=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,zp=/^STANCE:\s+\S+\s*$/gim,Qp=/\[Thought:\s*true\]\s*/gi;function En(r){let e=[...r.matchAll(Vp)];if(e.length>0){let t=e[e.length-1],n=(t.index??0)+t[0].length;return Ll(r.slice(n).trimStart())}return Ll(Zp(r.replace(Kp,"")))}function Zp(r){let e=Yp.exec(r);if(e===null)return r;let t=r.slice(e[0].length),n=[...t.matchAll(zp)];if(n.length<2)return r;let s=n[0],i=(s.index??0)+s[0].length;return t.slice(i).trimStart()}function Ll(r){let e=[...r.matchAll(Qp)];if(e.length===0)return r;let t=e[e.length-1],n=(t.index??0)+t[0].length;return r.slice(n).trimStart()}function Qe(r,e=""){let t=r.result;return typeof t?.sessionId=="string"&&t.sessionId.length>0?t.sessionId:e}function Ol(r){let e=r.result;return typeof e?.stopReason=="string"?e.stopReason:""}var eh=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"]);function yn(r={}){let e="",t="",n="",s=!1,i=!1,o=!1,a=r.isolateResult??(r.tool==="gemini"?En:void 0),l=()=>({result:a?a(t):t,sessionId:e,stopReason:n,sawActivity:o});return{setSessionId(c){e=c},beginTurn(){t="",n="",s=!1,i=!0,o=!1},completeTurn(c){return n=Ol(c),s=!0,i=!1,l()},cancelTurn(){t="",n="",i=!1},processMessage(c){if(c.method!=="session/update")return!1;let d=c.params?.update,m=d?.sessionUpdate;if(typeof m!="string"||(i&&eh.has(m)&&(o=!0),m!=="agent_message_chunk"))return!1;let h=d?.content,f=typeof h?.text=="string"?h.text:"";return f&&i&&(t+=f,r.onDelta?.(f)),!0},finalize(){return s?l():null}}}import{createInterface as th}from"node:readline";var rh=1;function nr(r,e){let t=th({input:r.stdout}),n=new Map,s=(o,a={})=>new Promise((l,c)=>{let u=rh++;n.set(u,{resolve:l,reject:c});let d=JSON.stringify({jsonrpc:"2.0",id:u,method:o,params:a});ge({event:"acp_send",direction:"SEND",provider:e.provider,method:o,id:u,params:a}),r.stdin?.write(`${d}
|
|
1936
1936
|
`)}),i=(o,a={})=>{r.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:o,params:a})}
|
|
1937
|
-
`)};return t.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(
|
|
1938
|
-
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new K("ACP RPC channel closed")){t.close();for(let a of n.values())a.reject(o);n.clear()}}}import{readFileSync as nh,readdirSync as Dl}from"node:fs";import{join as Tn}from"node:path";function Ml(r,e){let t=e.GEMINI_DIR??process.env.GEMINI_DIR??Tn(
|
|
1937
|
+
`)};return t.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(ge({event:"acp_recv",direction:"RECV",provider:e.provider,id:typeof a.id=="number"?a.id:void 0,method:typeof a.method=="string"?a.method:void 0,preview:JSON.stringify(a).slice(0,300)}),e.onEvent?.(a),typeof a.id=="number"&&n.has(a.id)){let c=n.get(a.id);if(n.delete(a.id),a.error){let u=a.error,d=typeof u?.message=="string"&&u.message.length>0?u.message:JSON.stringify(a.error);c.reject(rr(`ACP RPC error: ${d}`,u))}else c.resolve(a);return}let l=a.method;if(l){if(typeof a.id=="number"){b({event:"acp_unhandled_request",provider:e.provider,method:l,id:a.id,params:a.params});let c=JSON.stringify({jsonrpc:"2.0",id:a.id,error:{code:-32601,message:`Method not found: ${l} (lmctl does not implement server-side ACP methods)`}});ge({event:"acp_send",direction:"SEND",provider:e.provider,replyTo:a.id,error:"method not found"}),r.stdin?.write(`${c}
|
|
1938
|
+
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new K("ACP RPC channel closed")){t.close();for(let a of n.values())a.reject(o);n.clear()}}}import{readFileSync as nh,readdirSync as Dl}from"node:fs";import{join as Tn}from"node:path";function Ml(r,e){let t=e.GEMINI_DIR??process.env.GEMINI_DIR??Tn(U,".gemini"),n=Tn(t,"tmp"),s;try{s=Dl(n)}catch{throw new Error(`gemini bundle: cannot read the gemini session store at ${n} \u2014 cannot verify session "${r}"`)}let i=`"sessionId": "${r}"`,o=`"sessionId":"${r}"`;for(let a of s){let l=Tn(n,a,"chats"),c;try{c=Dl(l)}catch{continue}for(let u of c){if(!u.endsWith(".json"))continue;let d;try{d=nh(Tn(l,u),"utf8").slice(0,8192)}catch{continue}if(d.includes(i)||d.includes(o))return}}throw new Error(`gemini bundle: no session "${r}" in the gemini chats store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var sr={name:"gemini",binary:"gemini",baseArgs:["--acp","-y","--skip-trust"],argv(r){let e=[...sr.baseArgs];if(r.permissionMode==="plan"){let t=Ke("gemini","plan"),n=Ke("gemini","yolo");e=e.filter(s=>!(n??[]).includes(s)),t&&e.push(...t)}return r.model&&e.push("--model",r.model),e},isolateResult:En,sessionIdentity:{verifyLoadedSession:r=>{Ml(r.requestedSessionId,r.env)},recheckSession:r=>{Ml(r.requestedSessionId,r.env)}}};import{existsSync as sh,readFileSync as ih}from"node:fs";import{join as Ps}from"node:path";function Fl(r,e){let t=e.COPILOT_HOME??process.env.COPILOT_HOME??Ps(U,".copilot"),n=Ps(t,"session-state",r),s=Ps(n,"workspace.yaml");if(!sh(s))throw new Error(`copilot bundle: no session "${r}" in the copilot session store (${n}) \u2014 the session must exist on disk before a bundle can resume it`);let i;try{i=ih(s,"utf8").slice(0,4096)}catch(a){throw new Error(`copilot bundle: cannot read ${s} \u2014 cannot verify session "${r}": `+(a instanceof Error?a.message:String(a)))}let o=/^id:\s*(\S+)\s*$/m.exec(i);if(o===null||o[1]!==r)throw new Error(`copilot bundle: session store entry ${s} belongs to ${o?.[1]??"no recorded id"}, not "${r}"`)}var ir={name:"copilot",binary:"copilot",baseArgs:["--acp","--yolo"],argv(r){return r.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.
|
|
1939
1939
|
`),b({event:"acp_plan_mode_unsupported",provider:"copilot",requested_mode:"plan",effective_mode:"yolo"})),r.model&&(process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${r.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
1940
1940
|
`),b({event:"acp_model_unsupported",provider:"copilot",model:r.model})),[...ir.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:r=>{Fl(r.requestedSessionId,r.env)},recheckSession:r=>{Fl(r.requestedSessionId,r.env)}}};import{spawn as ph}from"node:child_process";import{resolve as Gl}from"node:path";import{existsSync as oh,mkdirSync as ah,readFileSync as lh,writeFileSync as Pl}from"node:fs";import{join as Ul,resolve as $v}from"node:path";var $l={yellow:r=>r};function ch(r){if(r==="allow")return!0;if(r&&typeof r=="object"&&!Array.isArray(r)){let e=Object.entries(r);if(e.length===1&&e[0][0]==="*"&&e[0][1]==="allow")return!0}return!1}function jl(r,e={}){let t=Ul(r,".opencode"),n=Ul(t,"opencode.json");if(!oh(n)){ah(t,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return Pl(n,o+`
|
|
1941
1941
|
`,"utf-8"),!0}let s;try{s=JSON.parse(lh(n,"utf-8"))}catch{return console.log($l.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log($l.yellow(` .opencode/opencode.json at ${n} is not an object \u2014 skipping opencode config install.`)),!1;let i=!1;return s.permission===void 0&&(s.permission="allow",i=!0),ch(s.permission)||b({event:"opencode_yolo_override",provider:"opencode",config_path:n,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&&Pl(n,JSON.stringify(s,null,2)+`
|
|
1942
|
-
`,"utf-8"),i}import{existsSync as $s,readdirSync as dh,statSync as Bl}from"node:fs";import{join as
|
|
1942
|
+
`,"utf-8"),i}import{existsSync as $s,readdirSync as dh,statSync as Bl}from"node:fs";import{join as Ze}from"node:path";import{createRequire as uh}from"node:module";var Us=null;function js(){return Us===null&&(Us=uh(import.meta.url)("node:sqlite").DatabaseSync),Us}function Wl(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalCacheWriteInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Hl(r,e){if(!e)return;r.observed=!0;let t=e.input??0,n=e.output??0,s=e.reasoning??0,i=e.cache?.read??0,o=e.cache?.write??0;if(r.totalInputTokens+=t,r.totalCachedInputTokens+=i,r.totalCacheWriteInputTokens+=o,r.totalOutputTokens+=n,r.totalReasoningOutputTokens+=s,t+n+s+i+o>0){let a=t+i+o;r.lastInputTokens=a,r.lastTokenUsage={inputTokens:t,cachedInputTokens:i,cacheWriteInputTokens:o,outputTokens:n,reasoningOutputTokens:s,totalTokens:a+n+s}}}function Xl(r){return r.observed?{totalInputTokens:r.totalInputTokens,totalCachedInputTokens:r.totalCachedInputTokens,totalCacheWriteInputTokens:r.totalCacheWriteInputTokens,totalOutputTokens:r.totalOutputTokens,totalReasoningOutputTokens:r.totalReasoningOutputTokens,lastInputTokens:r.lastInputTokens,lastTokenUsage:r.lastTokenUsage}:{}}function ql(){let r=process.env.XDG_DATA_HOME||Ze(U,".local","share"),e=process.env.XDG_CONFIG_HOME||Ze(U,".config");return[Ze(r,"opencode","opencode.db"),Ze(e,"opencode","opencode.db")]}function mh(){if(process.env.OPENCODE_DB)return[process.env.OPENCODE_DB];let r=process.env.XDG_DATA_HOME||Ze(U,".local","share"),e=Ze(r,"lmplayer"),t=Ze(e,"opencode-local.db"),n=[t];try{let s=dh(e).filter(i=>/^opencode.*\.db$/u.test(i)).map(i=>Ze(e,i)).filter(i=>i!==t).sort((i,o)=>{try{return Bl(o).mtimeMs-Bl(i).mtimeMs}catch{return 0}});n.push(...s)}catch{}return n}function fh(r){return r==="lmplayer"?mh():ql()}var Ct=class{name;startCommand;dbPaths;busyTimeoutMs;constructor(e){this.name=e?.providerName??"opencode",this.startCommand=e?.startCommand??this.name,this.busyTimeoutMs=e?.busyTimeoutMs??5e3,e?.dbPath?this.dbPaths=[e.dbPath]:this.dbPaths=fh(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>$s(e))}openDb(e){if(!$s(e))return null;let t=new(js())(e,{open:!0,readOnly:!0});return t.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),t}async discoverSessions(){let e=[];for(let t of this.existingDbPaths()){let n=this.openDb(t);if(n)try{let s=new Map,i=n.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=n.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1943
1943
|
s.time_created, s.time_updated
|
|
1944
1944
|
FROM session s
|
|
1945
1945
|
ORDER BY s.time_updated DESC`).all();for(let a of o){let l=s.get(a.project_id),c=a.directory||l?.worktree||"(unknown)",u=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
1946
|
-
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),d=0,
|
|
1947
|
-
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(t.id),a=[],l=[],c=0,u,d,
|
|
1946
|
+
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),d=0,m,h,f,T=Wl(),_=[];for(let g of u){let E;try{E=JSON.parse(g.data)}catch{continue}f||(f=E.model?.modelID||E.modelID),(E.role==="user"||E.role==="assistant")&&d++,E.role==="user"&&_.push(g.id),E.role==="assistant"&&Hl(T,E.tokens)}let p=[..._.length>0?[_[0]]:[],..._.length>1?[_[_.length-1]]:[]];for(let g of p){let E=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(g),w=this.extractText(E);w&&(m||(m=M(w,80)),h=M(w,80))}e.push({provider:this.name,sessionId:a.id,slug:a.slug,cwd:c,createdAt:new Date(a.time_created),modifiedAt:new Date(a.time_updated),model:f,startCommand:this.startCommand,firstUserMessage:m,lastUserMessage:h,messageCount:d,filePath:t,...Xl(T)})}}catch(s){b({event:"opencode_discover_sessions_failed",provider:this.name,db_path:t,error_message:s instanceof Error?s.message:String(s)})}finally{n.close()}}return e.sort((t,n)=>n.modifiedAt.getTime()-t.modifiedAt.getTime())}async loadSession(e){for(let t of this.existingDbPaths()){let n=this.openDb(t);if(n)try{let s=this.findSessionRow(n,e);if(!s)continue;return this.buildSessionDetail(n,s,t)}catch{}finally{n.close()}}return null}buildSessionDetail(e,t,n){let s=e.prepare("SELECT id, worktree, name FROM project WHERE id = ?").get(t.project_id),i=t.directory||s?.worktree||"(unknown)",o=e.prepare(`SELECT id, session_id, time_created, time_updated, data
|
|
1947
|
+
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(t.id),a=[],l=[],c=0,u,d,m,h=Wl();for(let f of o){let T;try{T=JSON.parse(f.data)}catch{continue}u||(u=T.model?.modelID||T.modelID);let _=T.model?.modelID||T.modelID,p=new Date(T.time?.created||f.time_created),g=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(f.id);if(T.role==="user"){let E=this.extractText(g),w=this.extractText(g,!0);w&&l.push(w),E&&(d||(d=M(E,80)),m=M(E,80)),a.push({role:"user",timestamp:p,content:E||"(empty)"}),c++}else if(T.role==="assistant"){Hl(h,T.tokens);for(let E of g){let w;try{w=JSON.parse(E.data)}catch{continue}w.type==="text"&&w.text?a.push({role:"assistant",timestamp:p,content:w.text,model:_}):w.type==="reasoning"&&w.text?a.push({role:"thinking",timestamp:p,content:w.text}):w.type==="tool"&&w.tool&&(a.push({role:"tool_use",timestamp:p,content:`${w.tool}`,toolName:w.tool,toolCallId:w.callID,toolInput:w.state?.input?JSON.stringify(w.state.input):void 0,toolInputData:Ie(w.state?.input)}),w.state&&(w.state.status==="completed"||w.state.status==="error"||w.state.output!==void 0||w.state.error!==void 0)&&a.push({role:"tool_result",timestamp:p,content:w.state.error??w.state.output??"",toolCallId:w.callID}))}c++}}return{provider:this.name,sessionId:t.id,slug:t.slug,cwd:i,createdAt:new Date(t.time_created),modifiedAt:new Date(t.time_updated),model:u,startCommand:this.startCommand,firstUserMessage:d,lastUserMessage:m,messageCount:c,filePath:n,...Xl(h),messages:a,userPrompts:l}}extractText(e,t=!1){let n=[];for(let s of e){let i;try{i=JSON.parse(s.data)}catch{continue}t&&(i.synthetic===!0||i.ignored===!0)||i.type==="text"&&i.text&&n.push(i.text)}return n.join(`
|
|
1948
1948
|
`).trim()}async resolveSessionPath(e){for(let t of this.existingDbPaths()){let n=this.openDb(t);if(n)try{if(this.findSessionRow(n,e))return t}catch{}finally{n.close()}}return null}async deleteSession(e){for(let t of this.existingDbPaths()){let n=new(js())(t,{open:!0});try{let s=this.findSessionRow(n,e);if(!s)continue;return n.prepare("DELETE FROM session WHERE id = ?").run(s.id).changes>0}catch{}finally{n.close()}}return!1}findSessionRow(e,t){let n=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1949
1949
|
s.time_created, s.time_updated
|
|
1950
1950
|
FROM session s WHERE s.id = ?`).get(t);if(n)return n;let s=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
@@ -1953,89 +1953,89 @@ ${t}`:t}function Rl(r){let e=r.binaryPath||"codex",t=["app-server","--listen","s
|
|
|
1953
1953
|
WHERE s.id LIKE ?
|
|
1954
1954
|
ORDER BY s.time_updated DESC
|
|
1955
1955
|
LIMIT 2`).all(`${t}%`);return s.length!==1?null:s[0]}};function Bs(r,e){let t=e?.dbPath!==void 0?[e.dbPath]:ql();for(let n of t){if(!$s(n))continue;let s=new(js())(n,{open:!0,readOnly:!0});try{s.exec("PRAGMA busy_timeout = 5000");let i=s.prepare("SELECT directory FROM session WHERE id = ?").get(r);if(i!==void 0)return{directory:typeof i.directory=="string"?i.directory:""}}finally{s.close()}}return null}function or(r){return{id:r.id,onFailure:"non-fatal",applies:e=>r.value(e)!==void 0,run:async e=>{await e.sendRpc("session/set_config_option",{sessionId:e.sessionId,configId:r.configId,value:r.value(e)})},describeFailure:(e,t)=>{let n=r.value(e),s=t instanceof Error?t.message:String(t);return{event:"acp_config_option_failed",fields:{config_id:r.configId,value:n,error_message:s},stderrLine:`[acp] set_config_option(${r.configId}=${n}) failed: ${s}
|
|
1956
|
-
`,warning:`${r.provider} ignored ${r.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${r.configId}=${r.value(e)}) ok`}}var
|
|
1956
|
+
`,warning:`${r.provider} ignored ${r.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${r.configId}=${r.value(e)}) ok`}}var mt={name:"opencode",binary:"opencode",baseArgs:["acp"],argv:()=>[...mt.baseArgs],preSpawn(r){try{jl(r.cwd)}catch(e){b({event:"opencode_config_install_failed",cwd:r.cwd,error_message:e instanceof Error?e.message:String(e)})}},sessionSetup:[or({id:"model",provider:"opencode",configId:"model",value:r=>r.model}),or({id:"effort",provider:"opencode",configId:"effort",value:r=>r.effort})],probe:Jl,sessionIdentity:{verifyLoadedSession:r=>{let e=Bs(r.requestedSessionId,{...r.env.OPENCODE_DB!==void 0?{dbPath:r.env.OPENCODE_DB}:{}});if(e===null)throw new Error(`opencode bundle: no session "${r.requestedSessionId}" in the opencode session store \u2014 the session must exist on disk before a bundle can resume it`);if(Gl(e.directory)!==Gl(r.cwd))throw new Error(`opencode bundle: session "${r.requestedSessionId}" belongs to ${e.directory}, not ${r.cwd} \u2014 refusing to resume another workspace's session`)},recheckSession:r=>{if(Bs(r.requestedSessionId,{...r.env.OPENCODE_DB!==void 0?{dbPath:r.env.OPENCODE_DB}:{}})===null)throw new Error(`opencode bundle: session "${r.requestedSessionId}" disappeared from the session store mid-bundle`)}}};function Jl(r){let e;try{e=ph(r.binaryPath??mt.binary,[...mt.baseArgs],{cwd:r.cwd,stdio:["pipe","pipe","pipe"],env:ce(r.env,r.cwd,void 0,"unknown")})}catch(s){return Promise.resolve({status:"unavailable",reason:"spawn",error:s instanceof Error?s.message:String(s)})}let t=nr(e,{provider:"opencode"}),n=r.timeoutMs??5e3;return new Promise(s=>{let i=!1,o=(u,d=!0)=>{if(!i){if(i=!0,clearTimeout(c),e.removeListener("error",a),e.removeListener("exit",l),t.close(),!d){s(u);return}Y(e,{softDelayMs:100,killDelayMs:100}).finally(()=>s(u))}},a=u=>{o({status:"unavailable",reason:"spawn",error:u.message},!1)},l=(u,d)=>{o({status:"unavailable",reason:"handshake",error:`opencode ACP exited before verification (code=${String(u)}, signal=${String(d)})`},!1)};e.once("error",a),e.once("exit",l);let c=setTimeout(()=>{o({status:"unavailable",reason:"timeout"})},n);(async()=>{try{await t.sendRpc("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),t.sendNotification("notifications/initialized");let u=await t.sendRpc("session/new",{cwd:r.cwd,mcpServers:[]}),d=Qe(u);try{await t.sendRpc("session/set_config_option",{sessionId:d,configId:"model",value:r.model})}catch(m){o({status:"rejected",option:"model",value:r.model,error:m instanceof Error?m.message:String(m)});return}if(r.effort!==void 0)try{await t.sendRpc("session/set_config_option",{sessionId:d,configId:"effort",value:r.effort})}catch(m){o({status:"rejected",option:"effort",value:r.effort,error:m instanceof Error?m.message:String(m)});return}o({status:"verified"})}catch(u){o({status:"unavailable",reason:"handshake",error:u instanceof Error?u.message:String(u)})}})()})}import{existsSync as hh}from"node:fs";import{readdir as gh}from"node:fs/promises";import{join as Ws,resolve as _h}from"node:path";var Eh=/runtime\s+\S+\s+does not exist in workspace\s+\S+/;function Kl(r){let e=Eh.exec(r);return e?e[0]:null}function yh(r){if(!r.includes("notifications/initialized"))return r;let e=r.split(/\r?\n/),t=[];for(let n=0;n<e.length;n++){let s=e[n];if(s.includes("Error handling notification")&&s.includes("notifications/initialized")){let i=[s],o=n;for(;o+1<e.length&&i.length<8&&(o++,i.push(e[o]),e[o].trim()!=="}"););let a=i.join(`
|
|
1957
1957
|
`);if(/\bcode:\s*-32601\b/.test(a)&&/Method not found[^]*notifications\/initialized/.test(a)){n=o;continue}}t.push(s)}return t.join(`
|
|
1958
|
-
`)}var Hs=r=>r.permissionMode==="plan"?"plan":"auto";async function Vl(r,e){let t=_h(e.KIMI_CODE_HOME??process.env.KIMI_CODE_HOME??Ws(
|
|
1959
|
-
`,message:`Cannot set Hermes ACP model to ${String(r.model)}: ${t}`}},successLog:r=>`acp: set_model(modelId=${String(r.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}};var Th={gemini:sr,copilot:ir,opencode:
|
|
1958
|
+
`)}var Hs=r=>r.permissionMode==="plan"?"plan":"auto";async function Vl(r,e){let t=_h(e.KIMI_CODE_HOME??process.env.KIMI_CODE_HOME??Ws(U,".kimi-code")),n=Ws(t,"sessions"),s;try{s=await gh(n,{withFileTypes:!0})}catch{throw new Error(`kimi bundle: cannot read the kimi session store at ${n} \u2014 cannot verify session "${r}"`)}for(let i of s)if(i.isDirectory()&&hh(Ws(n,i.name,r,"agents","main","wire.jsonl")))return;throw new Error(`kimi bundle: no session "${r}" in the kimi session store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var ar={name:"kimi",binary:"kimi",baseArgs:["acp"],argv:()=>[...ar.baseArgs],sessionSetup:[{id:"permission-mode",onFailure:"fail-closed",applies:()=>!0,run:async r=>{await r.sendRpc("session/set_config_option",{sessionId:r.sessionId,configId:"mode",value:Hs(r)})},describeFailure:(r,e)=>{let t=Hs(r),n=e instanceof Error?e.message:String(e);return{event:"acp_permission_mode_failed",fields:{config_id:"mode",value:t,error_message:n},message:`Cannot set Kimi ACP permission mode to ${t}: ${n}`}},successLog:r=>`acp: set_config_option(mode=${Hs(r)}) ok`},or({id:"model",provider:"kimi",configId:"model",value:r=>r.model})],onExitFinalization(r){let e=Kl(r.result);e!==null&&b({event:"kimi_runtime_dead",provider:"kimi",session_id:r.sessionId,matched_text:e})},filterExpectedStderr:yh,sessionIdentity:{verifyLoadedSession:async r=>{await Vl(r.requestedSessionId,r.env)},recheckSession:async r=>{await Vl(r.requestedSessionId,r.env)}}};var lr={name:"hermes",binary:"hermes",baseArgs:["acp"],argv(r){if(r.permissionMode==="plan")throw new Error('provider "hermes" does not support --permission-mode plan');return[...lr.baseArgs]},preSpawn(r){r.permissionMode==="yolo"&&(r.env.HERMES_YOLO_MODE="1")},modeVocabulary:{known:["default","accept_edits","dont_ask"],selectable:["accept_edits","dont_ask"]},sessionSetup:[{id:"session-mode",onFailure:"fail-closed",applies:r=>r.acpMode!==void 0,run:async r=>{await r.sendRpc("session/set_mode",{sessionId:r.sessionId,modeId:r.acpMode})},describeFailure:(r,e)=>{let t=e instanceof Error?e.message:String(e);return{event:"acp_session_mode_failed",fields:{mode_id:r.acpMode,error_message:t},message:`Cannot set hermes ACP session mode to ${String(r.acpMode)}: ${t}`}},successLog:r=>`acp: set_mode(modeId=${String(r.acpMode)}) ok`},{id:"model",onFailure:"fail-closed",applies:r=>{if(r.model===void 0)return!1;let e=r.response.result?.models?.currentModelId;return r.model!==e},run:async r=>{await r.sendRpc("session/set_model",{sessionId:r.sessionId,modelId:r.model})},describeFailure:(r,e)=>{let t=e instanceof Error?e.message:String(e);return{event:"acp_config_option_failed",fields:{config_id:"model",value:r.model,error_message:t},stderrLine:`[acp] set_model(modelId=${String(r.model)}) failed: ${t}
|
|
1959
|
+
`,message:`Cannot set Hermes ACP model to ${String(r.model)}: ${t}`}},successLog:r=>`acp: set_model(modelId=${String(r.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}};var Th={gemini:sr,copilot:ir,opencode:mt,kimi:ar,hermes:lr};function cr(r){return Th[r]}var Sh={gemini:{binary:sr.binary,args:sr.baseArgs},copilot:{binary:ir.binary,args:ir.baseArgs},opencode:{binary:mt.binary,args:mt.baseArgs},kimi:{binary:ar.binary,args:ar.baseArgs},hermes:{binary:lr.binary,args:lr.baseArgs}};function zl(r,e){let t=cr(r)?.modeVocabulary;if(!t)throw new K(`ACP mode "${e}" requested for provider "${r}", which declares no ACP mode vocabulary. Add the provider's mode ids to its AcpProviderProfile modeVocabulary before setting a mode.`);if(!t.known.includes(e))throw new K(`provider "${r}" has no ACP mode "${e}" (known: ${t.known.join(", ")}).`);if(!t.selectable.includes(e))throw new K(`provider "${r}" ACP mode "${e}" is not selectable by lmctl (selectable: ${t.selectable.join(", ")}).`)}function wh(r){let e=r.stderr.trim().slice(0,500),t=`lmctl: ${r.tool} ACP process exited with code ${r.exitCode} before completing the prompt.
|
|
1960
1960
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1961
1961
|
${e}
|
|
1962
1962
|
|
|
1963
|
-
${t}`:t}function Ih(r,e){return cr(r)?.filterExpectedStderr?.(e)??e}function Ql(r){if(r.method!=="session/update")return!1;let t=r.params?.update;if(t===void 0)return!1;let n=t.sessionUpdate;if(n!=="tool_call"&&n!=="tool_call_update")return!1;let s=t.status;return s!==void 0&&s!=="pending"&&s!=="in_progress"?!1:t.rawInput?.background===!0}async function Zl(r,e,t,n){for(let s of r.sessionSetup??[]){let i={...e,sessionId:t.sessionId,response:t.response,sendRpc:n};if(s.applies(i))try{await s.run(i),s.successLog&&ie(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(b({event:a.event,provider:r.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 ec(r,e,t){let n=
|
|
1964
|
-
`),b({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let u=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=ze(u),s.setSessionId(o),{sessionId:o,sessionResponse:u}}if(i){let c=ze(l);if(c!==""&&c!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${c}"`);if(c===""){if(r.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await r.verifyLoadResponse(l)}o=n.sessionId}else o=ze(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=ze(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function rc(r,e){let t=cr(e.tool);if(!t)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{zl(e.tool,e.acpMode)}catch(n){return Promise.reject(n)}return new Promise((n,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:S=>{o.push(S)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=ec(t,e,a))}catch(S){return s(S instanceof Error?S:new Error(String(S)))}let d=Yl(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),p=Date.now(),m=!1,h=!1,g=0,T=!1,f=!1;if(e.signal){if(e.signal.aborted)return m=!0,b({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),Y(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{m=!0,b({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-p}),Y(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let E=e.sessionId||"",y=yn({tool:e.tool,onDelta:e.onDelta,...t.isolateResult?{isolateResult:t.isolateResult}:{}});y.setSessionId(E);let I=nr(d,{provider:e.tool,onEvent:S=>{g=Date.now(),Ql(S)&&(f=!0),e.onEvent?.(S)},onNotification:S=>{g=Date.now(),y.processMessage(S)}}),{sendRpc:w,sendNotification:_}=I,v="";d.stderr?.on("data",S=>{v+=S.toString()}),d.on("error",S=>{I.close(S),b({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-p}),s(new K(`Failed to spawn ${t.binary} ${t.baseArgs.join(" ")}: ${S.message}`,{cause:S}))}),d.on("exit",S=>{if(h=!0,I.close(new K(`ACP process exited with code ${String(S)}`)),m)return;let x=y.finalize();if(x!==null)t.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-p,stopReason:x.stopReason,exitCode:S,sawActivity:x.sawActivity,...o.length>0?{warnings:o}:{}});else{let A=Ih(e.tool,v);b({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:A.slice(0,500),elapsed_ms:Date.now()-p}),s(new Error(wh({tool:e.tool,exitCode:S,stderr:A})))}}),(async()=>{try{let S=await tc({sendRpc:w,sendNotification:_,opts:e,outputProcessor:y});E=S.sessionId;let x=S.sessionResponse;await Zl(t,a,{sessionId:E,response:x},w),y.beginTurn(),T=!0,ie(`acp: prompt sent (${r.length} chars)`);let A=await w("session/prompt",{sessionId:E,prompt:[{type:"text",text:r}]}),R=y.completeTurn(A);T=!1,ie(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),Ke(e.holdOpen,{isAborted:()=>m,hasChildExited:()=>h,isTurnInFlight:()=>T,lastEventAtMs:()=>g,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>f})}catch(S){Y(d).catch(()=>{}),s(S instanceof Error?S:new Error(String(S)))}})()})}async function nc(r){let e=cr(r.tool);if(!e)throw new Error(`No ACP config for tool "${r.tool}"`);r.acpMode!==void 0&&zl(r.tool,r.acpMode);let t=r.permissionMode??"yolo",n=[],s=!0,i={permissionMode:t,...r.model!==void 0?{model:r.model}:{},...r.effort!==void 0?{effort:r.effort}:{},...r.acpMode!==void 0?{acpMode:r.acpMode}:{},purpose:"chat",warnings:{push:S=>{n.push(S)}}},{binary:o,spawnArgs:a,spawnEnv:l}=ec(e,r,i),c=Yl(o,a,{cwd:r.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},p=r.sessionId||"",m=null,h="";c.stderr?.on("data",S=>{h+=S.toString()});let g,T,f=yn({tool:r.tool,onDelta:S=>g?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});f.setSessionId(p);let E=nr(c,{provider:r.tool,onEvent:S=>{d.lastEventAtMs=Date.now(),Ql(S)&&(d.backgroundJobLaunched=!0),T?.(S)},onNotification:S=>{d.lastEventAtMs=Date.now(),f.processMessage(S)}}),y=()=>new Error(`ACP bundle process (${r.tool}) exited${d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`),I=[],w=()=>d.exited?Promise.resolve():new Promise(S=>{I.push(S)}),_=null;c.on("error",S=>{m=new K(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),b({event:"transport_error",provider:r.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-u}),E.close(S)}),c.on("exit",S=>{if(d.exited=!0,d.exitCode=S,E.close(new K(`ACP process exited with code ${String(S)}`)),!d.telemetryFired){d.telemetryFired=!0;let x=f.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S})}if(_!==null){let x=_;_=null,x(y())}for(let x of I.splice(0))x()});try{let S=await tc({sendRpc:E.sendRpc,sendNotification:E.sendNotification,opts:r,outputProcessor:f,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:r.sessionId,loadResponse:x,cwd:r.cwd,env:l})});p=S.sessionId,await Zl(e,i,{sessionId:S.sessionId,response:S.sessionResponse},E.sendRpc)}catch(S){let x=m??(S instanceof Error?S:new Error(String(S)));throw Y(c).catch(()=>{}),x}let v=S=>new Promise(x=>{setTimeout(x,S).unref?.()});return{tool:r.tool,get sessionId(){return p},get completedTurns(){return d.completedTurns},async sendTurn(S,x={}){if(d.closed||d.closing!==null)throw new Error(`ACP bundle session (${r.tool}) is closed`);if(d.exited)throw y();if(d.turnInFlight)throw new Error(`ACP bundle session (${r.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:p,cwd:r.cwd,env:l}),d.exited)throw y();if(x.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,g=x.onDelta,T=x.onEvent;let A=Date.now();try{f.beginTurn(),ie(`acp: bundle prompt sent (${S.length} chars)`);let R=await new Promise((B,V)=>{_=V;let ee=()=>{f.cancelTurn(),E.sendNotification("session/cancel",{sessionId:p}),V(new Error("Aborted"))},ae=x.signal;ae?.addEventListener("abort",ee,{once:!0}),E.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:S}]}).then(W=>{ae?.removeEventListener("abort",ee),B(W)},W=>{ae?.removeEventListener("abort",ee),V(W instanceof Error?W:new Error(String(W)))})});_=null;let $=f.completeTurn(R);d.turnInFlight=!1,d.completedTurns+=1,ie(`acp: bundle result received (${$.result.length} chars, stopReason=${$.stopReason})`);let C=s&&n.length>0?[...n]:void 0;return s=!1,{result:$.result,sessionId:$.sessionId,stopReason:$.stopReason,durationMs:Date.now()-A,sawActivity:$.sawActivity,...C!==void 0?{warnings:C}:{}}}catch(R){throw _=null,f.cancelTurn(),d.turnInFlight=!1,d.exited?y():R}finally{g=void 0,T=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(r.holdOpen!==void 0?await new Promise(x=>{Ke(r.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:r.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let S=r.closeTimeoutMs??2e3;await Promise.race([w(),v(S)]),d.exited||await Y(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),d.closing}}}function Q(r,e=120){let t=r.replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}var xh=256;function oc(r,e){return t=>{if(t.kind==="tool_use"&&typeof t.id=="string"){if(r.size>=xh){let n=r.keys().next().value;n!==void 0&&r.delete(n)}r.set(t.id,Date.now()),e(t);return}if(t.kind==="tool_result"&&typeof t.id=="string"&&t.elapsedMs===void 0){let n=r.get(t.id);if(n!==void 0){e({...t,elapsedMs:Date.now()-n}),r.delete(t.id);return}}e(t)}}function Ah(){let r=new Map;return(e,t)=>{bh(e,oc(r,t))}}function bh(r,e){let t=r.type;if(t==="system"){let n=r.subtype;if(n==="api_retry"){let s=typeof r.attempt=="number"?r.attempt:void 0,i=typeof r.max_retries=="number"?r.max_retries:void 0,o=typeof r.error_status=="number"?r.error_status:void 0,a=typeof r.error=="string"?r.error:void 0,l=typeof r.retry_delay_ms=="number"?r.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(Q(a,60));let u=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:u});return}if(n==="api_error"){let s=typeof r.error_status=="number"?r.error_status:void 0,i=typeof r.error=="string"?r.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(Q(i,80)),e({kind:"other",summary:o.join(": "),raw:r});return}e({kind:"system",summary:n||"system",raw:r});return}if(t==="assistant"||t==="user"){let s=r.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:Q(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=Q(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:Q(u),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:Q(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(`
|
|
1965
|
-
`).length} lines, ${d.length} chars`;else if(Array.isArray(d)){let
|
|
1966
|
-
`).length} lines, ${
|
|
1963
|
+
${t}`:t}function Ih(r,e){return cr(r)?.filterExpectedStderr?.(e)??e}function Ql(r){if(r.method!=="session/update")return!1;let t=r.params?.update;if(t===void 0)return!1;let n=t.sessionUpdate;if(n!=="tool_call"&&n!=="tool_call_update")return!1;let s=t.status;return s!==void 0&&s!=="pending"&&s!=="in_progress"?!1:t.rawInput?.background===!0}async function Zl(r,e,t,n){for(let s of r.sessionSetup??[]){let i={...e,sessionId:t.sessionId,response:t.response,sendRpc:n};if(s.applies(i))try{await s.run(i),s.successLog&&ie(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(b({event:a.event,provider:r.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 ec(r,e,t){let n=ce(e.env,e.cwd,e.sessionId);r.preSpawn?.({...t,cwd:e.cwd,env:n});let s=e.binaryPath||r.binary,i=r.argv(t),o=r.yoloAssertion==="always-yolo"?"yolo":t.permissionMode;if(oe(e.tool,i,o),e.cwd&&!vh(e.cwd))throw b({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new K(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:n}}async function tc(r){let{sendRpc:e,sendNotification:t,opts:n,outputProcessor:s}=r,i=r.strictSessionIdentity===!0;await e("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),t("notifications/initialized");let o=n.sessionId||"",a;if(n.sessionId){let l;try{l=await e("session/load",{sessionId:n.sessionId,cwd:n.cwd,mcpServers:[]})}catch(c){if(i||n.requireResume)throw new Error(`Cannot resume session ${n.sessionId} via ACP: ${c instanceof Error?c.message:String(c)}`);process.stderr.write(`[acp] session/load failed for ${n.sessionId}, creating new session
|
|
1964
|
+
`),b({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let u=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=Qe(u),s.setSessionId(o),{sessionId:o,sessionResponse:u}}if(i){let c=Qe(l);if(c!==""&&c!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${c}"`);if(c===""){if(r.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await r.verifyLoadResponse(l)}o=n.sessionId}else o=Qe(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=Qe(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function rc(r,e){let t=cr(e.tool);if(!t)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{zl(e.tool,e.acpMode)}catch(n){return Promise.reject(n)}return new Promise((n,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:S=>{o.push(S)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=ec(t,e,a))}catch(S){return s(S instanceof Error?S:new Error(String(S)))}let d=Yl(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),h=!1,f=!1,T=0,_=!1,p=!1;if(e.signal){if(e.signal.aborted)return h=!0,b({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),Y(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{h=!0,b({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),Y(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let g=e.sessionId||"",E=yn({tool:e.tool,onDelta:e.onDelta,...t.isolateResult?{isolateResult:t.isolateResult}:{}});E.setSessionId(g);let w=nr(d,{provider:e.tool,onEvent:S=>{T=Date.now(),Ql(S)&&(p=!0),e.onEvent?.(S)},onNotification:S=>{T=Date.now(),E.processMessage(S)}}),{sendRpc:I,sendNotification:y}=w,v="";d.stderr?.on("data",S=>{v+=S.toString()}),d.on("error",S=>{w.close(S),b({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-m}),s(new K(`Failed to spawn ${t.binary} ${t.baseArgs.join(" ")}: ${S.message}`,{cause:S}))}),d.on("exit",S=>{if(f=!0,w.close(new K(`ACP process exited with code ${String(S)}`)),h)return;let x=E.finalize();if(x!==null)t.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-m,stopReason:x.stopReason,exitCode:S,sawActivity:x.sawActivity,...o.length>0?{warnings:o}:{}});else{let A=Ih(e.tool,v);b({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:A.slice(0,500),elapsed_ms:Date.now()-m}),s(new Error(wh({tool:e.tool,exitCode:S,stderr:A})))}}),(async()=>{try{let S=await tc({sendRpc:I,sendNotification:y,opts:e,outputProcessor:E});g=S.sessionId;let x=S.sessionResponse;await Zl(t,a,{sessionId:g,response:x},I),E.beginTurn(),_=!0,ie(`acp: prompt sent (${r.length} chars)`);let A=await I("session/prompt",{sessionId:g,prompt:[{type:"text",text:r}]}),N=E.completeTurn(A);_=!1,ie(`acp: result received (${N.result.length} chars, stopReason=${N.stopReason})`),Ye(e.holdOpen,{isAborted:()=>h,hasChildExited:()=>f,isTurnInFlight:()=>_,lastEventAtMs:()=>T,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>p})}catch(S){Y(d).catch(()=>{}),s(S instanceof Error?S:new Error(String(S)))}})()})}async function nc(r){let e=cr(r.tool);if(!e)throw new Error(`No ACP config for tool "${r.tool}"`);r.acpMode!==void 0&&zl(r.tool,r.acpMode);let t=r.permissionMode??"yolo",n=[],s=!0,i={permissionMode:t,...r.model!==void 0?{model:r.model}:{},...r.effort!==void 0?{effort:r.effort}:{},...r.acpMode!==void 0?{acpMode:r.acpMode}:{},purpose:"chat",warnings:{push:S=>{n.push(S)}}},{binary:o,spawnArgs:a,spawnEnv:l}=ec(e,r,i),c=Yl(o,a,{cwd:r.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m=r.sessionId||"",h=null,f="";c.stderr?.on("data",S=>{f+=S.toString()});let T,_,p=yn({tool:r.tool,onDelta:S=>T?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});p.setSessionId(m);let g=nr(c,{provider:r.tool,onEvent:S=>{d.lastEventAtMs=Date.now(),Ql(S)&&(d.backgroundJobLaunched=!0),_?.(S)},onNotification:S=>{d.lastEventAtMs=Date.now(),p.processMessage(S)}}),E=()=>new Error(`ACP bundle process (${r.tool}) exited${d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`),w=[],I=()=>d.exited?Promise.resolve():new Promise(S=>{w.push(S)}),y=null;c.on("error",S=>{h=new K(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),b({event:"transport_error",provider:r.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-u}),g.close(S)}),c.on("exit",S=>{if(d.exited=!0,d.exitCode=S,g.close(new K(`ACP process exited with code ${String(S)}`)),!d.telemetryFired){d.telemetryFired=!0;let x=p.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S})}if(y!==null){let x=y;y=null,x(E())}for(let x of w.splice(0))x()});try{let S=await tc({sendRpc:g.sendRpc,sendNotification:g.sendNotification,opts:r,outputProcessor:p,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:r.sessionId,loadResponse:x,cwd:r.cwd,env:l})});m=S.sessionId,await Zl(e,i,{sessionId:S.sessionId,response:S.sessionResponse},g.sendRpc)}catch(S){let x=h??(S instanceof Error?S:new Error(String(S)));throw Y(c).catch(()=>{}),x}let v=S=>new Promise(x=>{setTimeout(x,S).unref?.()});return{tool:r.tool,get sessionId(){return m},get completedTurns(){return d.completedTurns},async sendTurn(S,x={}){if(d.closed||d.closing!==null)throw new Error(`ACP bundle session (${r.tool}) is closed`);if(d.exited)throw E();if(d.turnInFlight)throw new Error(`ACP bundle session (${r.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:m,cwd:r.cwd,env:l}),d.exited)throw E();if(x.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,T=x.onDelta,_=x.onEvent;let A=Date.now();try{p.beginTurn(),ie(`acp: bundle prompt sent (${S.length} chars)`);let N=await new Promise((j,ee)=>{y=ee;let G=()=>{p.cancelTurn(),g.sendNotification("session/cancel",{sessionId:m}),ee(new Error("Aborted"))},ae=x.signal;ae?.addEventListener("abort",G,{once:!0}),g.sendRpc("session/prompt",{sessionId:m,prompt:[{type:"text",text:S}]}).then(pe=>{ae?.removeEventListener("abort",G),j(pe)},pe=>{ae?.removeEventListener("abort",G),ee(pe instanceof Error?pe:new Error(String(pe)))})});y=null;let P=p.completeTurn(N);d.turnInFlight=!1,d.completedTurns+=1,ie(`acp: bundle result received (${P.result.length} chars, stopReason=${P.stopReason})`);let k=s&&n.length>0?[...n]:void 0;return s=!1,{result:P.result,sessionId:P.sessionId,stopReason:P.stopReason,durationMs:Date.now()-A,sawActivity:P.sawActivity,...k!==void 0?{warnings:k}:{}}}catch(N){throw y=null,p.cancelTurn(),d.turnInFlight=!1,d.exited?E():N}finally{T=void 0,_=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(r.holdOpen!==void 0?await new Promise(x=>{Ye(r.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:r.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let S=r.closeTimeoutMs??2e3;await Promise.race([I(),v(S)]),d.exited||await Y(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),d.closing}}}function Q(r,e=120){let t=r.replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e-1)+"\u2026":t}var xh=256;function oc(r,e){return t=>{if(t.kind==="tool_use"&&typeof t.id=="string"){if(r.size>=xh){let n=r.keys().next().value;n!==void 0&&r.delete(n)}r.set(t.id,Date.now()),e(t);return}if(t.kind==="tool_result"&&typeof t.id=="string"&&t.elapsedMs===void 0){let n=r.get(t.id);if(n!==void 0){e({...t,elapsedMs:Date.now()-n}),r.delete(t.id);return}}e(t)}}function Ah(){let r=new Map;return(e,t)=>{bh(e,oc(r,t))}}function bh(r,e){let t=r.type;if(t==="system"){let n=r.subtype;if(n==="api_retry"){let s=typeof r.attempt=="number"?r.attempt:void 0,i=typeof r.max_retries=="number"?r.max_retries:void 0,o=typeof r.error_status=="number"?r.error_status:void 0,a=typeof r.error=="string"?r.error:void 0,l=typeof r.retry_delay_ms=="number"?r.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(Q(a,60));let u=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:u});return}if(n==="api_error"){let s=typeof r.error_status=="number"?r.error_status:void 0,i=typeof r.error=="string"?r.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(Q(i,80)),e({kind:"other",summary:o.join(": "),raw:r});return}e({kind:"system",summary:n||"system",raw:r});return}if(t==="assistant"||t==="user"){let s=r.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:Q(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=Q(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:Q(u),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:Q(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(`
|
|
1965
|
+
`).length} lines, ${d.length} chars`;else if(Array.isArray(d)){let m=d.map(h=>typeof h=="object"&&h&&"text"in h?h.text:"").filter(Boolean).join("");m&&(u=`${m.split(`
|
|
1966
|
+
`).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(t==="result"){e({kind:"system",summary:"result",raw:r});return}}async function Sn(r,e){let t=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?Ah():void 0;if(e.bundleSession!==void 0){let i=e.bundleSession;if(i.provider!==t)throw new Error(`bundle session provider mismatch: session serves "${i.provider}", turn targets "${t}"`);let o=await i.sendTurn(r,{onDelta:e.onDelta,onEvent:n?a=>n(a,e.onProgress):void 0,signal:e.signal});return{text:o.text,sessionId:o.sessionId,durationMs:o.durationMs,...o.warnings!==void 0&&o.warnings.length>0?{warnings:o.warnings}:{}}}let s=await Sl(r,{sessionId:e.sessionId,cwd:e.cwd,env:e.env,tool:t,binaryPath:e.progPath,model:e.model,permissionMode:e.permissionMode,onText:e.onDelta,onEvent:n?i=>n(i,e.onProgress):void 0,signal:e.signal,holdOpen:e.holdOpen});return{text:s.result,sessionId:s.sessionId,durationMs:s.durationMs,numTurns:s.numTurns,...s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{}}}async function vn(r){let e=r.binary==="qwen"?"qwen":"claude",t=await vl({tool:e,sessionId:r.sessionId,cwd:r.cwd,env:r.env,binaryPath:r.progPath,model:r.model,permissionMode:r.permissionMode,holdOpen:r.holdOpen,closeTimeoutMs:r.closeTimeoutMs,sessionFileRoots:r.sessionFileRoots});return{provider:e,get sessionId(){return t.sessionId},get completedTurns(){return t.completedTurns},async sendTurn(n,s={}){let i=await t.sendTurn(n,{onText:s.onDelta,onEvent:s.onEvent,signal:s.signal});return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>t.close()}}function Rh(){let r=new Map;return(e,t)=>{Nh(e,oc(r,t))}}function Nh(r,e){if(r.method!=="session/update")return;let s=r.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:Q(a)});return}if(i==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:Q(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=Q(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:Q(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 ${Q(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:i})}}function sc(r,e){if(e!==void 0)return r===""&&!e?"empty":void 0}async function Ce(r,e){let t=e.acpTool||e.binary,n=e.onProgress?Rh():void 0;if(e.bundleSession!==void 0){let a=e.bundleSession;if(a.provider!==t)throw new Error(`bundle session provider mismatch: session serves "${a.provider}", turn targets "${t}"`);let l=await a.sendTurn(r,{onDelta:e.onDelta,onEvent:n?c=>n(c,e.onProgress):void 0,signal:e.signal});return{text:l.text,sessionId:l.sessionId,durationMs:l.durationMs,stopReason:l.stopReason,...sc(l.text,l.sawActivity)!==void 0?{status:"empty"}:{},...l.warnings!==void 0?{warnings:l.warnings}:{}}}let s=[];if(e.model&&t==="copilot"){let a="copilot --acp does not implement per-session model selection";ge({event:"model_ignored",provider:t,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await rc(r,{tool:t,sessionId:e.sessionId,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:n?a=>n(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,...sc(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function Oe(r){let e=r.acpTool||r.binary,t=await nc({tool:e,sessionId:r.sessionId,cwd:r.cwd,env:r.env,binaryPath:r.progPath,model:r.model,effort:r.effort,alias:r.alias,permissionMode:r.permissionMode,acpMode:r.acpMode,requireResume:!0,holdOpen:r.holdOpen,closeTimeoutMs:r.closeTimeoutMs});return{provider:e,get sessionId(){return t.sessionId},get completedTurns(){return t.completedTurns},async sendTurn(n,s){let i=await t.sendTurn(n,s);return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>t.close()}}function ic(r,e){let t=r.method;if(!t)return;let n=r.params;if(t==="turn/started"){e({kind:"system",summary:"turn started"});return}if(t==="turn/completed"){e({kind:"system",summary:"turn completed"});return}if(t==="error"){let s=n?.error,i=typeof s?.message=="string"?s.message:void 0,o=i&&i.length>0?i:"(no message)",a=n?.willRetry===!0;e(a?{kind:"api_retry",summary:`codex retry: ${Q(o,120)}`}:{kind:"other",summary:`codex error: ${Q(o,120)}`});return}if(t==="item/started"||t==="item/completed"){let s=n?.item;if(!s)return;let i=s.type,o=t==="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:Q(c||"(command)"),id:a});else{let u=s.exitCode,d=s.status||"",m=typeof s.durationMs=="number"?s.durationMs:void 0,h=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:h,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:Q(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:Q(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(t==="item/agentMessage/delta"){let s=n?.delta||"";if(s){let i=typeof n?._lmctlItemPhase=="string"?n._lmctlItemPhase:void 0;e(i==="commentary"?{kind:"thinking",summary:Q(s)}:{kind:"text",summary:Q(s)})}return}if(t==="item/reasoning/summaryTextDelta"||t==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:Q(s)});return}if(t==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let i=s.split(`
|
|
1967
1967
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${Q(o,60)}`:Q(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(t==="item/commandExecution/terminalInteraction"||t==="item/commandExecution/outputChunk"||t==="item/commandExecution/output"){let s=(typeof n?.stdin=="string"?n.stdin:"")||(typeof n?.delta=="string"?n.delta:"")||(typeof n?.output=="string"?n.output:"")||(typeof n?.text=="string"?n.text:"")||(typeof n?.content=="string"?n.content:"")||(typeof n?.chunk=="string"?n.chunk:"")||"";if(s){let i=s.split(`
|
|
1968
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${Q(o,60)}`:Q(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(t.startsWith("item/")){e({kind:"other",summary:t.slice(5)});return}}async function ac(r,e){if(e.bundleSession!==void 0){let n=e.bundleSession;if(n.provider!=="codex")throw new Error(`bundle session provider mismatch: session serves "${n.provider}", turn targets "codex"`);let s=await n.sendTurn(r,{onDelta:e.onDelta,onEvent:e.onProgress?i=>ic(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let t=await Nl(r,{threadId:e.sessionId,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?n=>ic(n,e.onProgress):void 0,signal:e.signal});return{text:t.result,sessionId:t.threadId,durationMs:t.durationMs}}async function lc(r){let e=await kl({threadId:r.sessionId,cwd:r.cwd,env:r.env,binaryPath:r.progPath,model:r.model,alias:r.alias,isLead:r.isLead,permissionMode:r.permissionMode,holdOpen:r.holdOpen,closeTimeoutMs:r.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(t,n){let s=await e.sendTurn(t,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}function qs(r){return new Xs(r)}var Xs=class extends
|
|
1969
|
-
`);try{return JSON.stringify(r)}catch{return String(r)}}function Mh(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch{return}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Fh(r,e){if(e===void 0)return;let t={input:e};if(r!=="apply_patch"||typeof e!="string")return t;let n=[...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 n.length>0&&(t.path=n[0].path,t.paths=n.map(s=>s.path),t.kinds=n.map(s=>s.kind)),t}async function mc(r){let e=0,t=0,n=0,s=0,i=0,o,a,l;for await(let c of Z(r)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let u=c.payload.message||c.payload.text;u&&(l=M(u.trim(),80))}if(c.type==="response_item"&&c.payload){let u=c.payload;if(u.type==="message"&&u.role==="user"&&u.content)for(let d of u.content)d.type==="input_text"&&typeof d.text=="string"&&d.text&&(e++,l=M(d.text.trim(),80));else if(u.type==="message"&&u.role==="assistant"&&u.content)for(let d of u.content)d.type==="output_text"&&typeof d.text=="string"&&d.text&&e++}if(c.payload&&typeof c.payload.model_context_window=="number"&&(a=c.payload.model_context_window),c.type==="event_msg"&&c.payload?.type==="token_count"&&c.payload.info?.total_token_usage){let u=c.payload.info.total_token_usage;t=u.input_tokens??t,n=u.cached_input_tokens??u.cache_read_input_tokens??n,s=u.output_tokens??s,i=u.reasoning_output_tokens??i;let d=Dh(c.payload.info.last_token_usage);d&&(o=d),typeof c.payload.info.model_context_window=="number"&&(a=c.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:t,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:a,lastUserMessage:l}}var wn=class{name="codex";codexDirs;constructor(e={}){let t=[dr(
|
|
1970
|
-
`);S.includes("user.text")&&x&&(!v.id||!
|
|
1971
|
-
`);S.trim()&&ur(s,
|
|
1972
|
-
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:ac})}openSession(e){return lc({...e,model:e.model??Gs})}seedArgsFor(e){let t=super.seedArgsFor(e),n=e?.model??Gs;return[...t.slice(0,-1),"--model",n,t[t.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Gs}}};import{readFileSync as Gh,writeFileSync as Jh,mkdirSync as Vh}from"node:fs";import{join as Kh,dirname as Yh}from"node:path";import{randomUUID as zh}from"node:crypto";import{createHash as Uh}from"node:crypto";import{readdir as fr,readFile as hc,stat as xn,unlink as $h}from"node:fs/promises";import{join as
|
|
1968
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${Q(o,60)}`:Q(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(t.startsWith("item/")){e({kind:"other",summary:t.slice(5)});return}}async function ac(r,e){if(e.bundleSession!==void 0){let n=e.bundleSession;if(n.provider!=="codex")throw new Error(`bundle session provider mismatch: session serves "${n.provider}", turn targets "codex"`);let s=await n.sendTurn(r,{onDelta:e.onDelta,onEvent:e.onProgress?i=>ic(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let t=await Nl(r,{threadId:e.sessionId,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?n=>ic(n,e.onProgress):void 0,signal:e.signal});return{text:t.result,sessionId:t.threadId,durationMs:t.durationMs}}async function lc(r){let e=await kl({threadId:r.sessionId,cwd:r.cwd,env:r.env,binaryPath:r.progPath,model:r.model,alias:r.alias,isLead:r.isLead,permissionMode:r.permissionMode,holdOpen:r.holdOpen,closeTimeoutMs:r.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(t,n){let s=await e.sendTurn(t,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}function qs(r){return new Xs(r)}var Xs=class extends V{claudeDir;constructor(e){super({provider:new sn(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",W,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:Sn}),this.claudeDir=e?.claudeDir??cc(U,".claude")}openSession(e){return vn({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[cc(this.claudeDir,"projects")]})}seedArgsFor(e){let t=super.seedArgsFor(e);return e?.model?[...t,"--model",e.model]:t}};import{readdir as kh,stat as dc,unlink as Lh}from"node:fs/promises";import{join as dr,basename as Ch}from"node:path";function Oh(r,e,t){return`${r}|${e.toISOString()}|${t}`}function ur(r,e,t){let n=Oh(t.role,t.timestamp,t.content);e.has(n)||(e.add(n),r.push(t))}function uc(r,e){return e==="exec"||r==="codex_exec"?"codex exec":"codex"}function Dh(r){if(!r)return;let e=r.cached_input_tokens??r.cache_read_input_tokens;return{inputTokens:r.input_tokens,cachedInputTokens:e,outputTokens:r.output_tokens,reasoningOutputTokens:r.reasoning_output_tokens,totalTokens:r.total_tokens}}function Ot(r){if(r==null)return"";if(typeof r=="string")return r;if(typeof r=="number"||typeof r=="boolean")return String(r);if(Array.isArray(r))return r.map(t=>{if(typeof t=="string")return t;if(t&&typeof t=="object"){let n=t;if(typeof n.text=="string")return n.text;if(typeof n.image_url=="string")return"[input_image]";if(typeof n.type=="string")return`[${n.type}]`}return Ot(t)}).filter(t=>t.length>0).join(`
|
|
1969
|
+
`);try{return JSON.stringify(r)}catch{return String(r)}}function Mh(r){let e=r;if(typeof r=="string")try{e=JSON.parse(r)}catch{return}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Fh(r,e){if(e===void 0)return;let t={input:e};if(r!=="apply_patch"||typeof e!="string")return t;let n=[...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 n.length>0&&(t.path=n[0].path,t.paths=n.map(s=>s.path),t.kinds=n.map(s=>s.kind)),t}async function mc(r){let e=0,t=0,n=0,s=0,i=0,o,a,l;for await(let c of Z(r)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let u=c.payload.message||c.payload.text;u&&(l=M(u.trim(),80))}if(c.type==="response_item"&&c.payload){let u=c.payload;if(u.type==="message"&&u.role==="user"&&u.content)for(let d of u.content)d.type==="input_text"&&typeof d.text=="string"&&d.text&&(e++,l=M(d.text.trim(),80));else if(u.type==="message"&&u.role==="assistant"&&u.content)for(let d of u.content)d.type==="output_text"&&typeof d.text=="string"&&d.text&&e++}if(c.payload&&typeof c.payload.model_context_window=="number"&&(a=c.payload.model_context_window),c.type==="event_msg"&&c.payload?.type==="token_count"&&c.payload.info?.total_token_usage){let u=c.payload.info.total_token_usage;t=u.input_tokens??t,n=u.cached_input_tokens??u.cache_read_input_tokens??n,s=u.output_tokens??s,i=u.reasoning_output_tokens??i;let d=Dh(c.payload.info.last_token_usage);d&&(o=d),typeof c.payload.info.model_context_window=="number"&&(a=c.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:t,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:a,lastUserMessage:l}}var wn=class{name="codex";codexDirs;constructor(e={}){let t=[dr(U,".codex"),dr(U,".code")];if(e.codexDirs&&e.codexDirs.length>0){this.codexDirs=[...new Set(e.codexDirs)];return}let n=[e.codexDir||t[0],e.codeDir||t[1]];this.codexDirs=[...new Set(n)]}getWatchPaths(){return this.codexDirs.map(e=>({directory:dr(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let t of this.codexDirs){let n=dr(t,"sessions");try{await dc(n),e.push(n)}catch{}}return e}async discoverSessions(){let e=[],t=await this.getSessionsDirs();for(let n of t){let s=await this.findSessionFiles(n);for(let i of s)try{let o=await this.extractSummary(i);o&&e.push(o)}catch{}}return e}async findSessionFiles(e){let t=[],n;try{n=await kh(e)}catch{return t}for(let s of n){let i=dr(e,s),o=await dc(i).catch(()=>null);if(o)if(o.isDirectory()){let a=await this.findSessionFiles(i);t.push(...a)}else s.endsWith(".jsonl")&&t.push(i)}return t}extractSessionIdFromFilename(e){let t=Ch(e,".jsonl"),n=t.match(/rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(.+)$/);return n?n[1]:t}async extractSummary(e){let t=await ye(e,30),n=await te(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,u,d,m;for(let f of t){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 T=f.payload.message||f.payload.text;T&&(c||(c=M(T.trim(),80)),u=M(T.trim(),80))}if(f.type==="response_item"&&f.payload?.type==="message"&&f.payload.role==="user"&&f.payload.content){let T=f.payload.content.find(_=>_.type==="input_text"&&typeof _.text=="string"&&_.text);typeof T?.text=="string"&&(c||(c=M(T.text.trim(),80)),u=M(T.text.trim(),80))}}if(!i)return null;let h=await mc(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:uc(d,m),firstUserMessage:c,lastUserMessage:h.lastUserMessage??u,messageCount:h.messageCount,filePath:e,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:h.lastTokenUsage,modelContextWindow:h.modelContextWindow}}async loadSession(e){let t=await this.resolveSessionFile(e);if(!t)return null;let n=await te(t),s=[],i="",o,a,l,c,u,d=e,m,h,f=new Set,T=[],_=new Set,p=[],g=(I,y)=>{let v=p.find(S=>!S.mirrored&&S.source!==y&&S.text===I);v?v.mirrored=!0:p.push({text:I,source:y,mirrored:!1})},E=()=>{T.push(...p.map(I=>I.text)),p=[]};for await(let I of Z(t)){let y=I.timestamp?new Date(I.timestamp):new Date;if(I.type==="session_meta"&&I.payload){I.payload.id&&(d=I.payload.id),I.payload.cwd&&(i=I.payload.cwd),I.payload.cli_version&&(o=I.payload.cli_version),I.payload.timestamp&&(l=new Date(I.payload.timestamp)),m=uc(I.payload.originator,I.payload.source);continue}if(I.type==="turn_context"&&I.payload){I.payload.model&&(a=I.payload.model),!i&&I.payload.cwd&&(i=I.payload.cwd);continue}if(I.type==="response_item"&&I.payload){let v=I.payload;if(v.type==="message"){if(v.role==="user"&&v.content){let S=v.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(S)){let x=v.content.filter((A,N)=>S[N]==="user.text"&&typeof A.text=="string").map(A=>A.text).join(`
|
|
1970
|
+
`);S.includes("user.text")&&x&&(!v.id||!_.has(v.id))&&(g(x,"metadata"),v.id&&_.add(v.id))}for(let x of v.content)if(x.type==="input_text"&&typeof x.text=="string"&&x.text){let A=x.text.trim();c||(c=M(A,80)),u=M(A,80),ur(s,f,{role:"user",timestamp:y,content:q(A)})}continue}if(v.role==="assistant"&&v.content){for(let S of v.content)S.type==="output_text"&&typeof S.text=="string"&&S.text&&ur(s,f,{role:"assistant",timestamp:y,content:q(S.text),model:a});continue}if(v.role!=="user"&&v.role!=="assistant"&&v.content){for(let S of v.content)(S.type==="input_text"||S.type==="output_text")&&typeof S.text=="string"&&S.text&&ur(s,f,{role:"system",timestamp:y,content:q(S.text.trim())});continue}}if(v.type==="function_call"){s.push({role:"tool_use",timestamp:y,content:v.name||"unknown tool",toolName:v.name,toolInput:v.arguments!==void 0?q(Ot(v.arguments)):void 0,toolInputData:Mh(v.arguments),toolCallId:v.call_id});continue}if(v.type==="function_call_output"){s.push({role:"tool_result",timestamp:y,content:q(Ot(v.output)),toolCallId:v.call_id});continue}if(v.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:y,content:v.name||"unknown tool",toolName:v.name,toolInput:v.input!==void 0?q(Ot(v.input)):void 0,toolInputData:Fh(v.name,v.input),toolCallId:v.call_id});continue}if(v.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:y,content:q(Ot(v.output)),toolCallId:v.call_id});continue}if(v.type==="reasoning"&&v.summary){let S=v.summary.map(x=>Ot(x.text)).join(`
|
|
1971
|
+
`);S.trim()&&ur(s,f,{role:"thinking",timestamp:y,content:q(S)});continue}}if(I.type==="event_msg"&&I.payload&&(I.payload.type==="task_started"?(E(),h="in_progress"):I.payload.type==="task_complete"?h="complete":I.payload.type==="turn_aborted"&&(h="aborted"),I.payload.type==="user_message"&&typeof I.payload.message=="string"&&g(I.payload.message,"event"),I.payload.type==="agent_reasoning")){let v=I.payload.message||I.payload.text;v&&ur(s,f,{role:"thinking",timestamp:y,content:q(v)})}}if(!i)return null;E();let w=await mc(t);return{provider:"codex",sessionId:d,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:m,turnStatus:h,firstUserMessage:c,lastUserMessage:u,messageCount:w.messageCount,filePath:t,totalInputTokens:w.totalInputTokens||void 0,totalCachedInputTokens:w.totalCachedInputTokens||void 0,totalOutputTokens:w.totalOutputTokens||void 0,totalReasoningOutputTokens:w.totalReasoningOutputTokens||void 0,lastInputTokens:w.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:w.lastTokenUsage,modelContextWindow:w.modelContextWindow,messages:s,userPrompts:T}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let t=await this.resolveSessionFile(e);return t?(await Lh(t),!0):!1}async resolveSessionFile(e){let t=await this.getSessionsDirs(),n=[];for(let i of t){let o=await this.findSessionFiles(i);n.push(...o)}for(let i of n)if(this.extractSessionIdFromFilename(i)===e)return i;let s=[];for(let i of n)this.extractSessionIdFromFilename(i).startsWith(e)&&s.push(i);if(s.length===1)return s[0];for(let i of n){let o=await ye(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}};function Vs(r){return new Js(r)}var Gs="gpt-5.6-sol",Js=class extends V{constructor(e){super({provider:new wn(e),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:`${W}
|
|
1972
|
+
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:ac})}openSession(e){return lc({...e,model:e.model??Gs})}seedArgsFor(e){let t=super.seedArgsFor(e),n=e?.model??Gs;return[...t.slice(0,-1),"--model",n,t[t.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Gs}}};import{readFileSync as Gh,writeFileSync as Jh,mkdirSync as Vh}from"node:fs";import{join as Kh,dirname as Yh}from"node:path";import{randomUUID as zh}from"node:crypto";import{createHash as Uh}from"node:crypto";import{readdir as fr,readFile as hc,stat as xn,unlink as $h}from"node:fs/promises";import{join as Te,basename as jh,dirname as Bh}from"node:path";import{cwd as Wh}from"node:process";function mr(r){if(!r.trim())return"unknown";let e=r.split(/\r?\n/).filter(n=>n.trim().length>0);if(e.length>1)try{let n=JSON.parse(e[0]);if(n!==null&&typeof n=="object"&&!Array.isArray(n)&&"kind"in n)return"jsonl"}catch{}let t;try{t=JSON.parse(r)}catch{return"unknown"}if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let n=t;if(Array.isArray(n.messages))return"json";if("kind"in n)return"jsonl"}return"unknown"}function In(r){let e=mr(r);if(e==="unknown")throw new Error("gemini session content matches neither known format (old .json with messages[] or new .jsonl with kind metadata)");if(e==="json"){let a=JSON.parse(r);return{sessionId:a.sessionId,projectHash:a.projectHash,startTime:a.startTime,lastUpdated:a.lastUpdated,kind:a.kind,messages:Array.isArray(a.messages)?a.messages:[]}}let t=r.split(`
|
|
1973
1973
|
`).map(a=>a).filter(a=>a.trim().length>0);if(t.length===0)throw new Error("gemini session file is empty");let n=t[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<t.length;a++){let l;try{l=JSON.parse(t[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let u=c;if(typeof u.id=="string"){let d=o.get(u.id);d?Ph(d,u):(i.push(u),o.set(u.id,u))}else i.push(u)}}return{sessionId:typeof s.sessionId=="string"?s.sessionId:void 0,projectHash:typeof s.projectHash=="string"?s.projectHash:void 0,startTime:typeof s.startTime=="string"?s.startTime:void 0,lastUpdated:typeof s.lastUpdated=="string"?s.lastUpdated:void 0,kind:typeof s.kind=="string"?s.kind:void 0,messages:i}}function Ph(r,e){for(let[t,n]of Object.entries(e))if(n!==void 0){if(t==="tokens"&&fc(r.tokens)&&fc(n)){r.tokens={...r.tokens,...n};continue}r[t]=n}}function fc(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function pc(r,e){if(e==="json")return JSON.stringify(r,null,2);let{messages:t,...n}=r,s=[JSON.stringify(n)];for(let i of t)s.push(JSON.stringify(i));return s.join(`
|
|
1974
1974
|
`)+`
|
|
1975
|
-
`}function Ks(r){return r?typeof r=="string"?r:Array.isArray(r)?r.map(e=>e.text||"").join(""):"":""}function gc(r){return r==="user"}function Ys(r){return r==="gemini"||r==="assistant"}function
|
|
1976
|
-
`).trim();v&&i.push({role:"thinking",timestamp:
|
|
1977
|
-
`)}seedArgsFor(e){let t=super.seedArgsFor(e);return e?.model?[...t,"--model",e.model]:t}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:an,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,t){let n=await this.resolvePath(e);if(!n)return{success:!1,error:`Session file not found for ${e}`};try{let s=Gh(n,"utf-8"),i=mr(s),o=In(s),a=zh();o.sessionId=a,o.kind="main";let l=Yh(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,
|
|
1978
|
-
`)){let n=t.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[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
|
|
1979
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${n.toolCallId}`;t.set(u,d),n.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=t.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function ig(r){let e=new Map;for(let t of r)t.role==="tool_result"&&t.toolCallId!==void 0&&e.set(t.toolCallId,t);return e}function ti(r){return new ei(r)}var ei=class extends
|
|
1980
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return
|
|
1981
|
-
`).trim():""}function Ac(r){if(r!==void 0)try{return JSON.stringify(r)}catch{return String(r)}}function gg(r){return r&&typeof r=="object"&&"output"in r&&typeof r.output=="string"?r.output:Ac(r)??""}function _g(r){let e=Eg(r),t=new Set;for(let n of r){if(n.role!=="tool_use"||n.toolName!=="Bash"||n.toolInputData?.run_in_background!==!0||n.toolCallId===void 0)continue;let s=e.get(n.toolCallId);if(s===void 0)continue;let i=s.content.match(/(?:^|\n)task_id:\s*([^\s]+)/)?.[1];i!==void 0&&(t.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of r){if(n.role!=="tool_use"||n.toolName!=="TaskOutput"&&n.toolName!=="TaskStop"||n.toolCallId===void 0)continue;let s=n.toolInputData?.task_id;if(typeof s!="string"||!t.has(s))continue;n.backgroundTaskId=s;let i=e.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function Eg(r){let e=new Map;for(let t of r)t.role==="tool_result"&&t.toolCallId!==void 0&&e.set(t.toolCallId,t);return e}function ai(r){return new oi(r)}var oi=class extends
|
|
1982
|
-
`);for(;
|
|
1983
|
-
`)}}),i.stderr?.on("data",
|
|
1975
|
+
`}function Ks(r){return r?typeof r=="string"?r:Array.isArray(r)?r.map(e=>e.text||"").join(""):"":""}function gc(r){return r==="user"}function Ys(r){return r==="gemini"||r==="assistant"}function ft(r,e=new Date(0)){if(!r)return e;let t=new Date(r);return Number.isNaN(t.getTime())?e:t}function Hh(r){return`${r.sessionId}\0${r.cwd}`}function Xh(r,e){let t=r.filePaths??[r.filePath],n=e.filePaths??[e.filePath],s=[...new Set([...t,...n])],i=e.modifiedAt.getTime()>=r.modifiedAt.getTime()?e:r;return{...i,createdAt:r.createdAt.getTime()<=e.createdAt.getTime()?r.createdAt:e.createdAt,modifiedAt:i.modifiedAt,filePath:i.filePath,filePaths:s}}function An(r){let e=Number(r??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function _c(r){let e=0,t=0,n=0,s=0,i=0,o;for(let a of r){if(!Ys(a.type)||!a.tokens)continue;let l=An(a.tokens.input),c=An(a.tokens.cached),u=Math.max(l-c,0),d=An(a.tokens.output),m=An(a.tokens.thoughts);e+=l,t+=c,n+=d,s+=m,i=l,o={inputTokens:u,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:d,reasoningOutputTokens:m,totalTokens:l+d+m}}return{totalInputTokens:e,totalCachedInputTokens:t,totalOutputTokens:n,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function qh(r){return Uh("sha256").update(r).digest("hex")}function pr(r,e){let t=e;for(;t&&!r.has(t);){r.add(t);let n=Bh(t);if(n===t)break;t=n}}var bn=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let t=e.geminiDir||Te(U,".gemini");this.geminiProjectsFile=Te(t,"projects.json"),this.geminiTmpDir=Te(t,"tmp");let n=e.claudeDir||Te(U,".claude");this.claudeProjectsDir=Te(n,"projects");let s=[Te(U,".codex"),Te(U,".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=>Te(o,"sessions")),this.extraWorkspacePaths=e.extraWorkspacePaths||[]}getWatchPaths(){return[{directory:this.geminiTmpDir,filePattern:/\.jsonl?$/}]}async discoverSessions(){let e=await this.findSessionFiles(),t=new Map;for(let n of e)try{let s=await this.extractSummary(n);if(!s)continue;let i=Hh(s),o=t.get(i);t.set(i,o?Xh(o,s):s)}catch{}return[...t.values()]}async loadSession(e){let t=await this.resolveSessionFile(e);if(!t)return null;let n;try{n=await this.readSessionFile(t)}catch{return null}if(!n)return null;let s=await te(t),i=[],o=[],a=n.messages||[],l=n.sessionId||this.extractSessionIdFromFilename(t),c=n.projectHash||"",u=await this.resolveWorkspace(c),d,m,h;for(let p of a){let g=ft(p.timestamp),E=p.type,w=q(Ks(p.content));if(gc(E)){let y=Ks(p.content);y&&o.push(y);let v=w.trim();v&&(d||(d=M(v,80)),m=M(v,80)),i.push({role:"user",timestamp:g,content:v||w});continue}if(Ys(E)){p.model&&(h=p.model);for(let y of p.thoughts||[]){let v=[y.subject,y.description].filter(Boolean).join(`
|
|
1976
|
+
`).trim();v&&i.push({role:"thinking",timestamp:ft(y.timestamp,g),content:q(v)})}i.push({role:"assistant",timestamp:g,content:w,model:p.model});continue}let I=E?`[${E}] `:"";i.push({role:"system",timestamp:g,content:`${I}${w}`.trim()})}let f=ft(n.startTime,s.createdAt),T=ft(n.lastUpdated,s.modifiedAt),_=_c(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:f,modifiedAt:T,model:h,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:t,totalInputTokens:_.totalInputTokens||void 0,totalCachedInputTokens:_.totalCachedInputTokens||void 0,totalOutputTokens:_.totalOutputTokens||void 0,totalReasoningOutputTokens:_.totalReasoningOutputTokens||void 0,lastInputTokens:_.lastInputTokens||void 0,lastTokenUsage:_.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let t=await this.readSessionFile(e);if(!t)return null;let n=await te(e),s=t.messages||[],i=t.sessionId||this.extractSessionIdFromFilename(e),o=t.projectHash||"",a=await this.resolveWorkspace(o),l,c,u,d=0;for(let h of s)if(gc(h.type)){d++;let f=Ks(h.content).trim();f&&(l||(l=M(q(f),80)),c=M(q(f),80))}else Ys(h.type)&&(d++,h.model&&(u=h.model));let m=_c(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:ft(t.startTime,n.createdAt),modifiedAt:ft(t.lastUpdated,n.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 t=await hc(e,"utf-8");if(mr(t)==="unknown")return b({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:t.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 In(t)}catch{return null}}extractSessionIdFromFilename(e){let t=jh(e).replace(/\.jsonl?$/,""),n=t.match(/session-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-(.+)$/);return n?n[1]:t}async findSessionFiles(){let e=[],t;try{t=await fr(this.geminiTmpDir)}catch{return e}for(let n of t){let s=Te(this.geminiTmpDir,n,"chats");if(!(await xn(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await fr(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(Te(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let t=await this.resolveSessionFile(e);return t?(await $h(t),!0):!1}async resolveSessionFile(e){let t=await this.findSessionFiles(),n=[];for(let s of t){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 te(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:ft(i?.lastUpdated,u.modifiedAt)})}return n.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),n[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;pr(e,Wh());for(let n of this.extraWorkspacePaths)pr(e,n);for(let n of await this.collectGeminiProjectPaths())pr(e,n);for(let n of await this.collectCodexCwds())pr(e,n);for(let n of await this.collectClaudeCwds())pr(e,n);let t=new Map;for(let n of e)t.set(qh(n),n);return this.workspaceHashMap=t,t}async collectGeminiProjectPaths(){let e;try{e=await hc(this.geminiProjectsFile,"utf-8")}catch{return[]}try{let n=JSON.parse(e).projects;return!n||typeof n!="object"||Array.isArray(n)?[]:Object.keys(n)}catch{return[]}}async collectCodexCwds(){let e=new Set;for(let t of this.codexSessionDirs){let n=await this.findJsonlFiles(t);for(let s of n){let o=(await ye(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,t;try{t=await fr(this.claudeProjectsDir)}catch{return[]}for(let n of t){let s=Te(this.claudeProjectsDir,n);if(!(await xn(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await fr(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Te(s,a),u=(await ye(l,1).catch(()=>[]))[0]?.cwd;u&&e.add(u)}}return[...e]}async findJsonlFiles(e){let t=[];if(!(await xn(e).catch(()=>null))?.isDirectory())return t;let s;try{s=await fr(e)}catch{return t}for(let i of s){let o=Te(e,i),a=await xn(o).catch(()=>null);if(a)if(a.isDirectory()){let l=await this.findJsonlFiles(o);t.push(...l)}else i.endsWith(".jsonl")&&t.push(o)}return t}};function Qs(r){return new zs(r)}var zs=class extends V{geminiDir;constructor(e){super({provider:new bn(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!0,forkSupport:"automatic",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"skill-file",leaderSetupHint:"Place skill files in the project's .gemini/ directory"},binary:"gemini",seedArgs:["-p",W,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(t,n)=>Ce(t,{...n,acpTool:"gemini"})}),this.geminiDir=e?.geminiDir}openSession(e){return Oe({...e,env:this.geminiDir!==void 0?{...e.env??process.env,GEMINI_DIR:this.geminiDir}:e.env,binary:"gemini",acpTool:"gemini"})}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(`
|
|
1977
|
+
`)}seedArgsFor(e){let t=super.seedArgsFor(e);return e?.model?[...t,"--model",e.model]:t}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:an,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,t){let n=await this.resolvePath(e);if(!n)return{success:!1,error:`Session file not found for ${e}`};try{let s=Gh(n,"utf-8"),i=mr(s),o=In(s),a=zh();o.sessionId=a,o.kind="main";let l=Yh(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,m=Kh(l,d);return Vh(l,{recursive:!0}),Jh(m,pc(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 Ec,readFile as Qh,rm as Zh,stat as Dt}from"node:fs/promises";import{basename as eg,join as be}from"node:path";function tg(r){if(!r)return null;let e={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,reasoningTokens:0},t=!1;for(let n of Object.values(r))n?.usage&&(t=!0,e.inputTokens+=n.usage.inputTokens??0,e.outputTokens+=n.usage.outputTokens??0,e.cacheReadTokens+=n.usage.cacheReadTokens??0,e.cacheWriteTokens+=n.usage.cacheWriteTokens??0,e.reasoningTokens+=n.usage.reasoningTokens??0);return t?e:null}function Zs(){return{shutdownTotals:null,assistantOutputSum:0}}function Tc(r,e){if(e.type==="assistant.message"){let t=e.data?.outputTokens;typeof t=="number"&&(r.assistantOutputSum+=t,r.lastAssistantOutputTokens=t)}else if(e.type==="session.shutdown"){let t=tg(e.data?.modelMetrics);t&&(r.shutdownTotals=t)}}function yc(r){let e=r.shutdownTotals,t=r.lastAssistantOutputTokens!==void 0?{outputTokens:r.lastAssistantOutputTokens}:void 0;return{totalInputTokens:e?.inputTokens,totalCachedInputTokens:e?.cacheReadTokens,totalCacheWriteInputTokens:e?.cacheWriteTokens,totalOutputTokens:e?.outputTokens??(r.lastAssistantOutputTokens===void 0?void 0:r.assistantOutputSum),totalReasoningOutputTokens:e?.reasoningTokens,lastTokenUsage:t}}function rg(r){let e={};for(let t of r.split(`
|
|
1978
|
+
`)){let n=t.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[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 pt(r){if(!r)return;let e=new Date(r);return Number.isNaN(e.getTime())?void 0:e}async function ng(r){let e=0,t=Zs(),n;for await(let s of Z(r)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=M(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;Tc(t,s)}return{messageCount:e,tokens:t,lastUserMessage:n}}var Rn=class{name="copilot";sessionStateDir;constructor(e={}){let t=e.copilotDir||be(U,".copilot");this.sessionStateDir=be(t,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],t;try{t=await Ec(this.sessionStateDir)}catch{return e}for(let n of t){let s=be(this.sessionStateDir,n);if((await Dt(s).catch(()=>null))?.isDirectory())try{let o=await this.extractSummary(s,n);o&&e.push(o)}catch{}}return e}async loadSession(e){let t=await this.resolveSessionDir(e);if(!t)return null;let n=await this.readWorkspaceYaml(t),s=be(t,"events.jsonl"),i=await Dt(s).catch(()=>null),o=i?s:be(t,"workspace.yaml"),a=await te(i?s:t),l=[],c=[],u=n?.cwd||"(unknown workspace)",d,m,h,f,T,_,p=n?.id||eg(t)||e,g=Zs();if(i)for await(let E of Z(s)){let w=pt(E.timestamp)||a.modifiedAt;if(Tc(g,E),E.type==="session.start"&&E.data){E.data.sessionId&&(p=E.data.sessionId),E.data.copilotVersion&&(m=E.data.copilotVersion),E.data.startTime&&(_=pt(E.data.startTime)),E.data.selectedModel&&(d=E.data.selectedModel),E.data.context&&(E.data.context.cwd&&(u=E.data.context.cwd),E.data.context.branch&&(h=E.data.context.branch));continue}if(E.type==="session.model_change"&&E.data?.newModel){d=E.data.newModel;continue}if(E.type==="user.message"&&E.data){let I=E.data.content||"";I&&c.push(I);let y=I.trim();y&&(f||(f=M(y,80)),T=M(y,80)),l.push({role:"user",timestamp:w,content:q(y||I)});continue}if(E.type==="assistant.message"&&E.data){let I=(E.data.content||"").trim();if(I&&l.push({role:"assistant",timestamp:w,content:q(I),model:d}),E.data.toolRequests)for(let y of E.data.toolRequests)l.push({role:"tool_use",timestamp:w,content:y.name||"unknown tool",toolName:y.name,toolInput:y.arguments?JSON.stringify(y.arguments,null,2):void 0,toolInputData:Ie(y.arguments),toolCallId:y.toolCallId});continue}if(E.type==="tool.execution_complete"&&E.data){let I=E.data.result?.content||"",y=E.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:w,content:q(I),toolDetailedContent:y?q(y):void 0,toolCallId:E.data.toolCallId});continue}if(E.type==="assistant.reasoning"&&E.data?.content){l.push({role:"thinking",timestamp:w,content:q(E.data.content)});continue}if(E.type==="session.error"||E.type==="session.warning"||E.type==="session.info"||E.type==="system.message"){let I=E.data?.message||"";I.trim()&&l.push({role:"system",timestamp:w,content:q(I)});continue}}if(!f){let E=(n?.summary||"").trim();E&&(f=M(E,80))}return sg(l),{provider:"copilot",sessionId:p,cwd:u,createdAt:_??pt(n?.created_at)??a.createdAt,modifiedAt:pt(n?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",gitBranch:h,firstUserMessage:f,lastUserMessage:T,messageCount:l.filter(E=>E.role==="user"||E.role==="assistant").length,filePath:o,...yc(g),messages:l,userPrompts:c}}async extractSummary(e,t){let n=await this.readWorkspaceYaml(e),s=be(e,"events.jsonl"),i=await Dt(s).catch(()=>null),o=i?s:be(e,"workspace.yaml"),a=await te(i?s:e),l=i?await ye(s,20):[],c=n?.id||t,u=n?.cwd||"(unknown workspace)",d,m,h,f,T;for(let p of l)if(p.type==="session.start"&&p.data&&(p.data.sessionId&&(c=p.data.sessionId),p.data.copilotVersion&&(m=p.data.copilotVersion),p.data.startTime&&(h=pt(p.data.startTime)),p.data.selectedModel&&(d=p.data.selectedModel),p.data.context?.cwd&&(u=p.data.context.cwd)),p.type==="session.model_change"&&p.data?.newModel&&(d||(d=p.data.newModel)),p.type==="user.message"&&p.data){let g=(p.data.content||"").trim();g&&(f||(f=M(g,80)),T=M(g,80))}if(!f){let p=(n?.summary||"").trim();p&&(f=M(p,80))}let _=i?await ng(s):{messageCount:0,tokens:Zs()};return{provider:"copilot",sessionId:c,cwd:u,createdAt:h??pt(n?.created_at)??a.createdAt,modifiedAt:pt(n?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",firstUserMessage:f,lastUserMessage:_.lastUserMessage??T,messageCount:_.messageCount,filePath:o,...yc(_.tokens)}}async readWorkspaceYaml(e){let t=be(e,"workspace.yaml");try{let n=await Qh(t,"utf-8");return rg(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let t=await this.resolveSessionDir(e);return t?(await Zh(t,{recursive:!0}),!0):!1}async resolveSessionDir(e){let t;try{t=await Ec(this.sessionStateDir)}catch{return null}if(t.includes(e)){let s=be(this.sessionStateDir,e);if((await Dt(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of t)if(s.startsWith(e)){let i=be(this.sessionStateDir,s);(await Dt(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of t){let i=be(this.sessionStateDir,s);if(!(await Dt(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 sg(r){let e=ig(r),t=new Map;for(let n of r){if(n.role!=="tool_use"||n.toolCallId===void 0)continue;if(n.toolName==="bash"){let l=e.get(n.toolCallId),u=[l?.content,l?.toolDetailedContent].filter(m=>typeof m=="string").join(`
|
|
1979
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${n.toolCallId}`;t.set(u,d),n.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=t.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function ig(r){let e=new Map;for(let t of r)t.role==="tool_result"&&t.toolCallId!==void 0&&e.set(t.toolCallId,t);return e}function ti(r){return new ei(r)}var ei=class extends V{copilotDir;constructor(e){super({provider:new Rn(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",W,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(t,n)=>Ce(t,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return Oe({...e,env:this.copilotDir!==void 0?{...e.env??process.env,COPILOT_HOME:this.copilotDir}:e.env,binary:"copilot",acpTool:"copilot"})}async seed(e,t){let n=await super.seed(e,t);if(t?.model===void 0||t.model.trim().length===0)return n;let s="copilot seed does not implement per-session model selection";return ge({event:"model_ignored",provider:"copilot",model:t.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${t.model}: ${s}`]}}};function ni(){return new ri}var ri=class extends V{constructor(){super({provider:new Ct,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",W],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,t)=>Ce(e,{...t,acpTool:"opencode"})})}openSession(e){return Oe({...e,binary:"opencode",acpTool:"opencode"})}seedArgsFor(e){let t=["run"];return e?.model&&t.push("--model",e.model),e?.effort&&t.push("--variant",e.effort),t.push(e?.prompt??W),t}};import{appendFile as og,mkdir as ag,readFile as Sc,readdir as vc,rm as lg,stat as wc}from"node:fs/promises";import{basename as cg,dirname as dg,isAbsolute as Ic,join as ht,relative as ug,resolve as si}from"node:path";var mg="1.4",fg="1.5",pg=new Set([mg,fg]),Nn=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=si(e?.kimiHome??process.env.KIMI_CODE_HOME??ht(U,".kimi-code")),this.sessionsDir=ht(this.homeDir,"sessions")}async discoverSessions(){let e=[];for(let t of await this.sessionFiles())try{let n=await this.summary(t);n&&e.push(n)}catch{}return e.sort((t,n)=>n.modifiedAt.getTime()-t.modifiedAt.getTime())}async loadSession(e){let t=await this.findSession(e);if(!t)return null;let n=await this.summary(t);if(!n)return null;let s=await this.parseWire(t.wirePath);return{...n,messages:s.messages,userPrompts:s.userPrompts}}async resolveSessionPath(e){return(await this.findSession(e))?.wirePath??null}async deleteSession(e){let t=await this.findSession(e);return t?(await lg(t.sessionDir,{recursive:!0,force:!0}),await ag(dg(this.indexPath()),{recursive:!0,mode:448}),await og(this.indexPath(),`${JSON.stringify({sessionId:t.sessionId,deleted:!0})}
|
|
1980
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return ht(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),t=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&t.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let n;try{n=await vc(this.sessionsDir,{withFileTypes:!0})}catch{return[...t.values()]}for(let s of n){if(!s.isDirectory())continue;let i=ht(this.sessionsDir,s.name),o;try{o=await vc(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||t.has(a.name))continue;let l=ht(i,a.name);t.set(a.name,this.filesFor(a.name,l))}}return[...t.values()]}async readIndex(){let e;try{e=await Sc(this.indexPath(),"utf-8")}catch{return new Map}let t=new Map;for(let n of e.split(/\r?\n/))if(n.trim())try{let s=JSON.parse(n);if(typeof s.sessionId!="string")continue;s.deleted===!0?t.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&t.set(s.sessionId,{sessionId:s.sessionId,sessionDir:si(s.sessionDir),workDir:s.workDir})}catch{}return t}filesFor(e,t,n){return{sessionId:e,sessionDir:t,statePath:ht(t,"state.json"),wirePath:ht(t,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,t){if(!Ic(e)||cg(e)!==t)return!1;let n=ug(this.sessionsDir,si(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Ic(n)}async findSession(e){let t=await this.sessionFiles(),n=t.find(i=>i.sessionId===e);if(n)return n;let s=t.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let t=JSON.parse(await Sc(e,"utf-8"));return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}async summary(e){let t=await this.readState(e.statePath);if(!t)return null;let n;try{n=await wc(e.wirePath)}catch{return null}let s=await wc(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=ii(t.createdAt)??s.birthtime,a=ii(t.updatedAt)??(s.mtime>n.mtime?s.mtime:n.mtime);return{provider:"kimi",sessionId:e.sessionId,slug:t.title,cwd:t.workDir??e.indexedWorkDir??"(unknown)",createdAt:o,modifiedAt:a,model:i.model,startCommand:"kimi",firstUserMessage:i.firstUserMessage,lastUserMessage:i.lastUserMessage??(t.lastPrompt?M(t.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 t=[],n=[],s=new Set,i=!0,o,a,l,c=0,u=0,d=0,m=0,h=!1,f=0,T,_;for await(let p of Z(e)){let g=hg(p.time??p.created_at);if(i&&(i=!1,p.type==="metadata"&&!pg.has(p.protocol_version))){let w=`Kimi transcript wire protocol version ${JSON.stringify(p.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:g,content:w}],userPrompts:[],messageCount:1,firstUserMessage:w,lastUserMessage:w}}if((p.type==="config.update"||p.type==="profile.bind")&&p.modelAlias&&(o=p.modelAlias),p.type==="usage.record"){p.model&&(o=p.model),h||=p.usage!==void 0;let w=p.usage?.inputOther??0,I=p.usage?.inputCacheRead??0,y=p.usage?.inputCacheCreation??0,v=p.usage?.output??0;c+=w,u+=I,d+=y,m+=v,p.usageScope==="turn"&&(T=w+I+y,_={inputTokens:w,cachedInputTokens:I,cacheWriteInputTokens:y,outputTokens:v,totalTokens:T+v});continue}if(p.type==="turn.prompt"&&p.origin?.kind==="user"){let w=xc(p.input);w&&((!p.promptId||!s.has(p.promptId))&&(n.push(w),p.promptId&&s.add(p.promptId)),a??=M(w,80),l=M(w,80),t.push({role:"user",timestamp:g,content:w}),f++);continue}if(p.type==="turn.steer"){let w=xc(p.input);w&&(t.push({role:"system",timestamp:g,content:w}),f++);continue}if(p.type!=="context.append_loop_event"||!p.event)continue;let E=p.event;E.type==="content.part"&&E.part?.type==="text"&&E.part.text?(t.push({role:"assistant",timestamp:g,content:E.part.text,model:o}),f++):E.type==="content.part"&&E.part?.type==="think"&&E.part.think?t.push({role:"thinking",timestamp:g,content:E.part.think,model:o}):E.type==="tool.call"?t.push({role:"tool_use",timestamp:g,content:E.name??"tool",toolName:E.name,toolInput:Ac(E.args),toolInputData:Ie(E.args),toolCallId:E.toolCallId,model:o}):E.type==="tool.result"&&t.push({role:"tool_result",timestamp:g,content:gg(E.result),toolCallId:E.toolCallId,model:o})}return _g(t),{messages:t,userPrompts:n,messageCount:f,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:h?c:void 0,totalCachedInputTokens:h?u:void 0,totalCacheWriteInputTokens:h?d:void 0,totalOutputTokens:h?m:void 0,lastInputTokens:T,lastTokenUsage:_}}};function ii(r){if(!r)return;let e=new Date(r);return Number.isNaN(e.getTime())?void 0:e}function hg(r){return typeof r=="number"?new Date(r):ii(r)??new Date(0)}function xc(r){return typeof r=="string"?r.trim():Array.isArray(r)?r.map(e=>e&&typeof e=="object"&&"text"in e&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
|
|
1981
|
+
`).trim():""}function Ac(r){if(r!==void 0)try{return JSON.stringify(r)}catch{return String(r)}}function gg(r){return r&&typeof r=="object"&&"output"in r&&typeof r.output=="string"?r.output:Ac(r)??""}function _g(r){let e=Eg(r),t=new Set;for(let n of r){if(n.role!=="tool_use"||n.toolName!=="Bash"||n.toolInputData?.run_in_background!==!0||n.toolCallId===void 0)continue;let s=e.get(n.toolCallId);if(s===void 0)continue;let i=s.content.match(/(?:^|\n)task_id:\s*([^\s]+)/)?.[1];i!==void 0&&(t.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of r){if(n.role!=="tool_use"||n.toolName!=="TaskOutput"&&n.toolName!=="TaskStop"||n.toolCallId===void 0)continue;let s=n.toolInputData?.task_id;if(typeof s!="string"||!t.has(s))continue;n.backgroundTaskId=s;let i=e.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function Eg(r){let e=new Map;for(let t of r)t.role==="tool_result"&&t.toolCallId!==void 0&&e.set(t.toolCallId,t);return e}function ai(r){return new oi(r)}var oi=class extends V{kimiHome;constructor(e){super({provider:new Nn(e),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",W,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(t,n)=>Ce(t,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return Oe({...e,env:this.kimiHome!==void 0?{...e.env??process.env,KIMI_CODE_HOME:this.kimiHome}:e.env,binary:"kimi",acpTool:"kimi"})}seedArgsFor(e){let t=[];return e?.model&&t.push("--model",e.model),t.push("-p",e?.prompt??W,"--output-format","stream-json"),t}};import{spawn as yg}from"node:child_process";import{mkdirSync as Tg}from"node:fs";function ci(r){return new li(r)}var li=class extends V{constructor(e){super({provider:new Ct({providerName:"lmplayer",startCommand:"lmplayer",dbPath:e?.lmplayerDbPath}),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",W],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:Sg})}seedArgsFor(e){return bc({prompt:e?.prompt??W,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,t){Tg(e,{recursive:!0});let n=this.seedArgsFor(t);oe("lmplayer",n);try{let s=await Nc(this.binary,n,{cwd:e,env:kt(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:Rc(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 "${W}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}};async function Sg(r,e){let t=Date.now(),n=bc({prompt:r,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});oe("lmplayer",n,e.permissionMode??"yolo");let s=await Nc(e.binary,n,{cwd:e.cwd,env:ce(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(Rc(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-t}}function bc(r){let e=["run"];return r.model&&e.push("--model",r.model),r.sessionId&&e.push("--session",r.sessionId),r.formatJson&&e.push("--format","json"),r.effort&&e.push("--effort",r.effort),e.push(...Ke("lmplayer",r.permissionMode)??[]),e.push("--",r.prompt),e}function Rc(r){if(r.error)return r.error;let e=er(r.stderr).trim();return e?e.slice(0,500):`exit code ${r.code}`}function Nc(r,e,t){return new Promise((n,s)=>{let i;try{i=yg(r,e,{cwd:t.cwd,env:t.env,stdio:["ignore","pipe","pipe"]})}catch(T){s(T);return}let o="",a="",l="",c,u,d,m=[],h=!1,f=T=>{let _=T.trim();if(!_)return;let p;try{p=JSON.parse(_)}catch{m.push(T),t.onText?.(T);return}if(!Mt(p))return;let g=kn(p,!1);c===void 0&&g!==void 0&&(c=g),u=kn(p,!0)??u;let E=vg(p);E!==void 0&&(d=E);let w=kc(p);w&&(m.push(w),t.onText?.(w))};i.stdout?.on("data",T=>{let _=T.toString("utf8");o+=_,l+=_;let p=l.indexOf(`
|
|
1982
|
+
`);for(;p>=0;){let g=l.slice(0,p);l=l.slice(p+1),f(g),p=l.indexOf(`
|
|
1983
|
+
`)}}),i.stderr?.on("data",T=>{a+=T.toString("utf8")}),t.signal&&(t.signal.aborted?i.kill():t.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",T=>{h||(h=!0,l.length>0&&f(l),n({code:T,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",T=>{h||(h=!0,s(T))})})}function vg(r){let e=r.error;if(typeof e=="string"&&e.length>0)return e;if(Mt(e)){let t=e.data;if(Mt(t)&&typeof t.message=="string"&&t.message.length>0)return typeof e.name=="string"?`${e.name}: ${t.message}`:t.message;if(typeof e.message=="string"&&e.message.length>0)return e.message}}function kc(r){for(let e of["text","content","delta","output","message"]){let t=r[e];if(typeof t=="string")return t}for(let e of["data","event","payload","part"]){let t=r[e];if(Mt(t)){let n=kc(t);if(n)return n}}}function kn(r,e){for(let n of["sessionID","sessionId","session_id"]){let s=r[n];if(typeof s=="string"&&s.length>0)return s}let t=r.session;if(typeof t=="string"&&t.length>0)return t;if(Mt(t)){let n=kn(t,e);if(n!==void 0)return n}if(e){let n=r.id;if(typeof n=="string"&&n.length>0)return n}for(let n of["data","event","payload","part"]){let s=r[n];if(Mt(s)){let i=kn(s,e);if(i!==void 0)return i}}}function Mt(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}import{readdir as Ln,readFile as wg,rm as Ig}from"node:fs/promises";import{basename as Lc,join as et}from"node:path";function xg(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function hr(r){let e=Number(r??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function Ag(r,e){if(!e)return;r.observed=!0;let t=hr(e.promptTokenCount),n=hr(e.cachedContentTokenCount),s=hr(e.candidatesTokenCount),i=hr(e.thoughtsTokenCount);r.totalInputTokens+=t,r.totalCachedInputTokens+=n,r.totalOutputTokens+=s,r.totalReasoningOutputTokens+=i,r.lastInputTokens=t,r.lastTokenUsage={inputTokens:Math.max(t-n,0),cachedInputTokens:n,outputTokens:s,reasoningOutputTokens:i,totalTokens:hr(e.totalTokenCount)||t+s}}function bg(r){return{totalInputTokens:r.observed?r.totalInputTokens:void 0,totalCachedInputTokens:r.observed?r.totalCachedInputTokens:void 0,totalOutputTokens:r.observed?r.totalOutputTokens:void 0,totalReasoningOutputTokens:r.observed?r.totalReasoningOutputTokens:void 0,lastInputTokens:r.lastInputTokens,lastTokenUsage:r.lastTokenUsage}}function Cc(r){return r.type==="user"||r.message?.role==="user"}function Oc(r){return r.type==="assistant"||r.message?.role==="assistant"||r.message?.role==="model"}function Dc(r){let e=r.message;return e?typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(t=>t.type==="text").map(t=>t.text||"").join(`
|
|
1984
1984
|
`):Array.isArray(e.parts)?e.parts.filter(t=>!t.thought&&t.type!=="thinking").map(t=>t.text||"").join(`
|
|
1985
|
-
`):"":""}function Mc(r){return r.model||r.message?.model}function Rg(r){let e=r.message?.content;return typeof e=="string"?e.length>0?1:0:Pc(r).filter(t=>!t.thought&&t.type!=="thinking"&&typeof t.text=="string"&&t.text.length>0).length}function gr(r,e=!1){if(r!==void 0){if(typeof r=="string")return r;try{return JSON.stringify(r,null,e?2:void 0)}catch{return String(r)}}}function Ng(r){if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let e=r;return gr(e.output??e.error??r)}return gr(r)}function Pc(r){return Array.isArray(r.message?.content)?r.message.content:r.message?.parts??[]}function Fc(r,e,t){let n=r.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:gr(r.args,!0),toolInputData:we(r.args),toolCallId:r.id,model:t}}var Cn=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Ze(P,".qwen")}async discoverSessions(){let e=Ze(this.baseDir,"projects"),t;try{t=await Ln(e)}catch{return[]}let n=[];for(let s of t){let i=Ze(e,s,"chats"),o;try{o=await Ln(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Ze(i,a);try{let u=await this.extractSummary(c,l);u&&n.push(u)}catch{}}}return n}async extractSummary(e,t){let n=!1,s=await te(e),i="(unknown)",o,a,l,c,u=0;for await(let d of Z(e)){if(n=!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)),Cc(d)){let p=Dc(d).trim();p&&(l||(l=M(p,80)),c=M(p,80),u++)}if(Oc(d)){let p=Mc(d);p&&(o=p),u+=Rg(d)}}return n?{provider:"qwen",sessionId:t,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 t=await this.resolveSessionPath(e);if(!t)return null;let n=Lc(t,".jsonl");return this.loadFromFile(t,n)}async loadFromFile(e,t){let n=await te(e),s="(unknown)",i,o,a,l,c,u,d=[],p=xg();for await(let m of Z(e)){if(Ag(p,m.usageMetadata),m.cwd&&(s=m.cwd,m.version&&(o=m.version),m.gitBranch&&(a=m.gitBranch)),m.type==="system"&&m.cwd&&(s=m.cwd,m.version&&(o=m.version),m.model&&(i=m.model),m.gitBranch&&(a=m.gitBranch)),!m.message)continue;let h=m.message,g=m.timestamp?new Date(m.timestamp):n.modifiedAt;if(m.type==="tool_result"){let T=Pc(m).filter(f=>f.functionResponse!==void 0);T.length===0&&m.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:g,content:gr(m.toolCallResult.resultDisplay??m.toolCallResult.error??m.toolCallResult.status)??"tool result",toolCallId:m.toolCallResult.callId});for(let f of T){let E=f.functionResponse,y=Ng(E.response),I=gr(m.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:g,content:I??y??m.toolCallResult?.status??"tool result",toolName:E.name,toolCallId:m.toolCallResult?.callId??E.id,...y!==void 0?{toolDetailedContent:y}:{}})}}else if(Cc(m)){let T=Dc(m);T.trim()&&(c||(c=M(T.trim(),80)),u=M(T.trim(),80)),d.push({role:"user",timestamp:g,content:T})}else if(Oc(m)){let T=Mc(m);if(T&&(i=T),Array.isArray(h.content))for(let f of h.content)f.type==="text"&&f.text?d.push({role:"assistant",timestamp:g,content:f.text,model:T}):f.type==="thinking"&&f.thinking?d.push({role:"thinking",timestamp:g,content:f.thinking}):f.functionCall&&d.push(Fc(f.functionCall,g,T));else if(typeof h.content=="string")d.push({role:"assistant",timestamp:g,content:h.content,model:T});else if(Array.isArray(h.parts))for(let f of h.parts)if(f.thought||f.type==="thinking"){let E=f.thinking||f.text;E&&d.push({role:"thinking",timestamp:g,content:E})}else f.functionCall?d.push(Fc(f.functionCall,g,T)):f.text&&d.push({role:"assistant",timestamp:g,content:f.text,model:T})}}return{provider:"qwen",sessionId:t,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:e,...bg(p),messages:d}}async resolveSessionPath(e){let t=Ze(this.baseDir,"projects");try{let n=await Ln(t),s=[];for(let i of n){let o=Ze(t,i,"chats",`${e}.jsonl`);try{return await wg(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Ze(t,i,"chats"),a;try{a=await Ln(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Lc(l,".jsonl").startsWith(e)&&s.push(Ze(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let t=await this.resolveSessionPath(e);if(!t)return!1;try{return await Ig(t),!0}catch{return!1}}};function ui(){return new di}var di=class extends J{constructor(){super({provider:new Cn,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",H,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:Sn})}openSession(e){return vn({...e,binary:"qwen"})}seedArgsFor(e){let t=super.seedArgsFor(e);return e?.model?[...t,"--model",e.model]:t}};import{readdir as Uc,readFile as $c,rm as jc,stat as Bc}from"node:fs/promises";import{basename as mi,join as Oe}from"node:path";import{fileURLToPath as kg}from"node:url";var On=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Oe(P,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Oe(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Oe(this.baseDir,"conversations"),t;try{t=await Uc(e)}catch{return[]}let n=[];for(let s of t){if(!s.endsWith(".db"))continue;let i=mi(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Oe(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,t){return Oe(this.baseDir,"brain",e,".system_generated","logs",t?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let t of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await Bc(t),t}catch{}return null}async extractSummary(e){let t=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??t,i=await Lg([t,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,u=0;if(n)for await(let d of Z(n)){let p=qc(d.content);if(p&&(a=p),Wc(d)){let m=Xc(d.content).trim();m&&(l||(l=M(m,80)),c=M(m,80)),u++}else Hc(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:n?[t,n]:[t]}}async loadSession(e){let t=await this.resolveSessionPath(e);if(!t)return null;let n=Jc(t);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,u=[],d=[];if(i)for await(let p of Z(i)){let m=Cg(p.created_at,s.modifiedAt),h=qc(p.content);if(h&&(a=h),Wc(p)){let g=Xc(p.content),T=g.trim();T&&(l||(l=M(T,80)),c=M(T,80)),o.push({role:"user",timestamp:m,content:g});continue}if(Array.isArray(p.tool_calls))for(let g of p.tool_calls){let T=g.name||"tool",f=Dg(g.args),E=we(g.args),y={role:"tool_use",timestamp:m,content:f,toolName:T,toolInput:f,toolInputData:E};o.push(y),u.push({name:T,stepIndex:p.step_index,input:E,message:y})}if(Hc(p)&&p.content)o.push({role:"assistant",timestamp:m,content:p.content,model:a});else if(Og(p)&&p.content){let g=Ug(p,n),T=g===void 0?null:await this.readTaskLog(n,g),f={role:"tool_result",timestamp:T?.modifiedAt??m,content:p.content,toolName:p.type?.toLowerCase(),backgroundTaskId:g,...T===null?{}:{toolDetailedContent:T.content}};o.push(f),d.push({event:p,message:f})}p.thinking&&o.push({role:"thinking",timestamp:m,content:p.thinking})}return $g(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(p=>p.role==="user"||p.role==="assistant").length,messages:o}}async resolveSessionPath(e){let t=this.conversationPath(e);try{return await Bc(t),t}catch{}let n=Oe(this.baseDir,"conversations");try{let s=[];for(let i of await Uc(n)){if(!i.endsWith(".db"))continue;mi(i,".db").startsWith(e)&&s.push(Oe(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let t=await this.resolveSessionPath(e);if(!t)return!1;let n=Jc(t);return n?(await jc(this.conversationPath(n),{force:!0}),await jc(Oe(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,t){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(t){let s=await Mg(t);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let t=Oe(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await $c(t,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}async readTaskLog(e,t){if(!/^task-\d+$/.test(t))return null;let n=Oe(this.baseDir,"brain",e,".system_generated","tasks",`${t}.log`);try{let[s,i]=await Promise.all([$c(n,"utf8"),te(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}};async function Lg(r){let e=await Promise.all(r.map(t=>te(t)));return{createdAt:new Date(Math.min(...e.map(t=>t.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(t=>t.modifiedAt.getTime())))}}function Cg(r,e){if(!r)return e;let t=new Date(r);return Number.isNaN(t.getTime())?e:t}function Wc(r){return r.type==="USER_INPUT"}function Hc(r){return r.source==="MODEL"&&r.type==="PLANNER_RESPONSE"}function Og(r){return r.source==="MODEL"&&r.type!=="PLANNER_RESPONSE"}function Xc(r){if(!r)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(r);return e?e[1]:r}function qc(r){if(!r)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(r);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function Dg(r){if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}}async function Mg(r){for await(let e of Z(r)){let t=e.tool_calls?.map(s=>s.args)??[];for(let s of t){let i=Fg(s);if(i)return i}let n=Pg(e.content);if(n)return n}return null}function Fg(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r,t=e.Cwd??e.cwd??e.DirectoryPath;return typeof t!="string"?null:t.replace(/^"|"$/g,"")}function Pg(r){return r?/"Cwd":"([^"]+)"/.exec(r)?.[1]??null:null}function Ug(r,e){if(r.status!=="RUNNING"||!r.content)return;let t=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(r.content);if(!(!t||t[1]!==e)&&!(r.step_index===void 0||Number(t[3])!==r.step_index))return t[2]}function $g(r,e){let t=new Set;for(let n of e){let s=jg(r,t,n);if(!s)continue;t.add(s);let i=n.event.step_index===void 0?void 0:`agy-step-${n.event.step_index}`;s.message.toolCallId=i,s.message.backgroundTaskId=n.message.backgroundTaskId,n.message.toolName=s.name,n.message.toolCallId=i}}function jg(r,e,t){let n=t.message.backgroundTaskId===void 0?void 0:Xg(t.event.content);if(n!==void 0)return Gc(r.filter(i=>!e.has(i)&&qg(i)===n),t.event.step_index);let s=Hg(t.event);if(s!==void 0)return Gc(r.filter(i=>!e.has(i)&&Bg(i.name,t.event.type)&&Vc(Wg(i))===s),t.event.step_index)}function Gc(r,e){if(r.length===0)return;if(r.length===1)return r[0];if(e===void 0)return;let t=r.map(n=>({call:n,distance:n.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(e-n.stepIndex)})).sort((n,s)=>n.distance-s.distance);return t[0].distance<t[1].distance?t[0].call:void 0}function Bg(r,e){return e==="VIEW_FILE"?r==="view_file":e!=="CODE_ACTION"?!1:r==="write_to_file"||r==="replace_file_content"||r==="multi_replace_file_content"}function Wg(r){let e=r.name==="view_file"?r.input?.AbsolutePath:r.input?.TargetFile;return typeof e=="string"?e:void 0}function Hg(r){if(!r.content)return;let e;return r.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(r.content)?.[1]:r.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(r.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(r.content)?.[1]),Vc(e)}function Vc(r){if(!r)return;let e=r.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return kg(e)}catch{return}}function Xg(r){if(r)return/Task Description:\s*([^\n]+)/.exec(r)?.[1]?.trim()}function qg(r){if(r.name==="run_command"){let e=r.input?.CommandLine;return typeof e=="string"?e:void 0}if(r.name==="schedule"){let e=r.input?.DurationSeconds,t=r.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof t!="string"?void 0:`Timer: ${e}s, Prompt: ${t}`}}function Jc(r){if(r.endsWith(".db"))return mi(r,".db");let e="/brain/",t=r.indexOf(e);return t===-1?null:r.slice(t+e.length).split("/")[0]||null}import{spawn as Gg}from"node:child_process";import{StringDecoder as Kc}from"node:string_decoder";function Dn(r){return async(e,t)=>{let n=Date.now(),s=r.buildArgs(e,t);r.assertArgs?.(s,t),t.onProgress?.({kind:"system",summary:`${r.label} -p one-shot started (no streaming events)`});let{stdout:i}=await Jg(r.label,t.binary,s,{cwd:t.cwd,env:le(t.env,t.cwd,t.sessionId),signal:t.signal});return t.onProgress?.({kind:"system",summary:`${r.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:t.sessionId,durationMs:Date.now()-n}}}function Jg(r,e,t,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${r} turn aborted`));return}let o;try{o=Gg(e,t,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(p){i(p);return}let a="",l="",c=new Kc("utf8"),u=new Kc("utf8");o.stdout?.on("data",p=>{a+=c.write(p)}),o.stderr?.on("data",p=>{l+=u.write(p)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${r} turn aborted`))};o.on("error",p=>{n.signal?.removeEventListener("abort",d),i(p)}),o.on("close",(p,m)=>{if(n.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),p===0){s({stdout:a,stderr:l});return}let h=m?`signal ${m}`:`exit code ${p}`,g=l.trim()||a.trim();i(new Error(`${r} failed (${h})${g?`: ${g}`:""}`))}),n.signal?.aborted?d():n.signal?.addEventListener("abort",d,{once:!0})})}function pi(r){return new fi(r)}var fi=class extends J{constructor(e){super({provider:new On(e),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",H,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:Vg})}seedArgsFor(e){let t=[...super.seedArgsFor(e)];return e?.model&&t.push("--model",e.model),t}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}`}}},Vg=Dn({label:"agy",buildArgs:(r,e)=>{let t=["--conversation",e.sessionId,"-p",r,"--dangerously-skip-permissions","--print-timeout",Kg(e.timeoutMs)];return e.model&&t.push("--model",e.model),t},assertArgs:(r,e)=>oe("agy",r,e.permissionMode??"yolo")});function Kg(r){return!r||r<=0?"8h":`${Math.max(1,Math.ceil(r/1e3))}s`}import{randomUUID as g_}from"node:crypto";import{existsSync as ed}from"node:fs";import{readFile as __,mkdir as E_}from"node:fs/promises";import{readdir as hi,rm as l_,stat as c_}from"node:fs/promises";import{join as et}from"node:path";import Yg from"node:zlib";var zg=Yg.zstdDecompressSync,Qg=40,Zg=181,e_=47,t_=253,r_=42,n_=77,s_=24;function i_(r,e){return r[e]===Qg&&r[e+1]===Zg&&r[e+2]===e_&&r[e+3]===t_}function Yc(r,e){return(r[e]&240)===80&&r[e+1]===r_&&r[e+2]===n_&&r[e+3]===s_}function o_(r,e){if(Yc(r,e))return e+8>r.length?void 0:8+r.readUInt32LE(e+4);if(!i_(r,e))return;let t=e+4;if(t+1>r.length)return;let n=r[t];t+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(t+=1),t+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(t+=l,!(t>r.length)){for(;;){if(t+3>r.length)return;let c=r[t]|r[t+1]<<8|r[t+2]<<16,u=(c&1)!==0,d=c>>1&3,p=c>>3;if(t+=3,d===3||(t+=d===1?1:p,t>r.length))return;if(u)break}if(o&&(t+=4),!(t>r.length))return t-e}}function a_(r){let e=[],t=0;for(;t+4<=r.length;){let n=o_(r,t);if(n===void 0||n<=0)break;e.push(r.subarray(t,t+n)),t+=n}return e}function Mn(r){let e=[];for(let t of a_(r))Yc(t,0)||e.push(zg(t).toString("utf8"));return e.join("")}var Pn=class{name="dsh";sessionsDir;constructor(e={}){let t=e.dshHome||et(P,".dsh");this.sessionsDir=et(t,"sessions")}async discoverSessions(){let e=[],t;try{t=await hi(this.sessionsDir)}catch{return[]}for(let n of t){let s;try{s=await hi(et(this.sessionsDir,n))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(n,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let t=await this.findSessionDir(e);if(!t)return null;let n=await this.readRecords(t.cwdDir,t.sessionDir);if(n.length===0)return null;let s=zc(n),i=Qc(n,t.filePath,s);return i?{...i,turnStatus:m_(n),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let t=await this.findSessionDir(e);return t?(await l_(et(this.sessionsDir,t.cwdDir,t.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,t){return et(this.sessionsDir,d_(e),t,"session.jsonl.zstd")}async findSessionDir(e){let t;try{t=await hi(this.sessionsDir)}catch{return null}for(let n of t){let s=e,i=et(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await c_(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,t){let{readFile:n}=await import("node:fs/promises"),s=et(this.sessionsDir,e,t,"session.jsonl.zstd"),i=await n(s),o=Mn(i),a=[];for(let l of o.split(`
|
|
1986
|
-
`))if(l.trim())try{let c=JSON.parse(l);if(c.type?.endsWith("-chunks")||c.type==="assistant/chunk")continue;a.push(c)}catch{}return a}async readSummary(e,t){let n=await this.readRecords(e,t);if(n.length===0)return null;let s=et(this.sessionsDir,e,t,"session.jsonl.zstd");return Qc(n,s,zc(n))}};function d_(r){return"--"+r.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function gi(r){if(typeof r=="string")return r;if(!Array.isArray(r))return"";let e=[];for(let t of r)t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string"&&e.push(t.text);return e.join("")}function u_(r){if(!Array.isArray(r))return[];let e=[];for(let t of r)t&&typeof t=="object"&&t.type==="reasoning"&&typeof t.text=="string"&&e.push(t.text);return e}function zc(r){let e=[];for(let t of r){let n=t.data??{},s=t.time?new Date(t.time):new Date(0);if(t.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:gi(i.content)})}else if(t.type==="assistant/message"){let i=n.message;for(let o of u_(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:gi(i?.content),model:i?.source?.model})}else if(t.type==="tool/call"){let i=n,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(t.type==="tool/result"){let i=n,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:gi(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function m_(r){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.type==="turn/end")return t.data?.reason?.kind==="completed"?"complete":"aborted";if(t.type==="turn/start")return"in_progress"}}function Qc(r,e,t){let n=r.find(m=>m.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let m of r)if(m.type==="request/header"){let h=m.data?.header;h?.config?.model&&(a=h.config.model)}let l=r.map(m=>m.time).filter(m=>typeof m=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,p=t.filter(m=>m.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:p[0]?.content,lastUserMessage:p.at(-1)?.content,messageCount:t.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:e,...f_(r)}}function f_(r){let e=!1,t=0,n=0,s=0,i=0,o,a;for(let l of r){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let u=Fn(c.inputTokens),d=Fn(c.cacheReadTokens),p=Fn(c.outputTokens),m=Fn(c.reasoningTokens);t+=u,n+=d,s+=p,i+=m,o=u+d,a={inputTokens:u,cachedInputTokens:d,outputTokens:p,reasoningOutputTokens:m,totalTokens:u+d+p}}return{totalInputTokens:e?t:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function Fn(r){let e=Number(r??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}import{spawn as p_}from"node:child_process";var h_=/dsh web:\s*(https?:\/\/\S+)/,Zc=2e4,Ft=class r extends Error{method;detail;constructor(e,t){super(`dsh RPC ${e} failed: ${JSON.stringify(t)}`),this.name="DshRpcCallError",this.method=e,this.detail=t,Object.setPrototypeOf(this,r.prototype)}},_i=class r{baseUrl;child;constructor(e,t){this.baseUrl=e,this.child=t}static forTesting(e){return new r(e,void 0)}async rpc(e,t){let n=`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s;try{s=await fetch(`${this.baseUrl}/api/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:n,method:e,payload:t})})}catch(a){throw new Ft(e,`transport error: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await s.json()}catch{i=void 0}if(!s.ok)throw new Ft(e,i??s.statusText);let o=i&&typeof i=="object"?i.result:void 0;if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new Ft(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new Ft(e,o.error??o);return"value"in o?o.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&&this.child.kill("SIGTERM")}static spawn(e){return new Promise((t,n)=>{let s=p_("dsh",["web","--no-open","--port","0"],{env:e,stdio:["ignore","pipe","pipe"]}),i=!1,o="",a="",l=setTimeout(()=>{i||(i=!0,s.kill("SIGTERM"),n(new Error(`dsh web sidecar did not report a boot URL within ${Zc}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},Zc);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let u=h_.exec(o);u&&(i=!0,clearTimeout(l),t(new r(u[1],s)))}),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("error",c=>{i||(i=!0,clearTimeout(l),n(c))}),s.on("exit",(c,u)=>{if(i)return;i=!0,clearTimeout(l);let d=u?`signal ${u}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${d}): ${a.slice(0,500)}`))})})}},tt;async function Un(r,e=t=>_i.spawn(t)){if(tt){let t=await tt.catch(()=>{});if(t?.alive)return t;tt=void 0}return tt=e(r),tt}async function _r(){if(!tt)return;(await tt.catch(()=>{}))?.shutdown(),tt=void 0}var y_=500,Ei=8*60*60*1e3;function Si(r){return new Ti(r)}var Ti=class extends J{dshProvider;constructor(e){let t=new Pn(e);super({provider:t,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:(n,s)=>this.dshPromptTurn(n,s)}),this.dshProvider=t}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,t){await E_(e,{recursive:!0});let n=`session-${g_()}`,s=yi(process.env);oe("dsh",[],"yolo");try{let i;try{i=await Un(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${$n(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${$n(a)}`}}if(t?.model)try{await i.rpc("session.selectModel",{sessionId:n,provider:"deepseek-official",model:t.model})}catch(a){return{success:!1,error:`session.selectModel("${t.model}") failed: ${$n(a)}`}}let o=t?.prompt??H;try{await this.promptAndWait(i,e,n,o,Ei)}catch(a){return{success:!1,error:`seed turn failed: ${$n(a)}`}}return{success:!0,sessionId:n}}finally{await _r()}}async dshPromptTurn(e,t){let n=Date.now();if(t.bundleSession!==void 0){let o=t.bundleSession;if(o.provider!=="dsh")throw new Error(`bundle session provider mismatch: session serves "${o.provider}", turn targets "dsh"`);let a=await o.sendTurn(e,{signal:t.signal});return{text:a.text,sessionId:a.sessionId,durationMs:a.durationMs,...a.warnings!==void 0?{warnings:a.warnings}:{}}}let s=yi(t.env??process.env);oe("dsh",[],t.permissionMode??"yolo");let i;try{let o=await Un(s);t.model&&(await o.rpc("session.selectModel",{sessionId:t.sessionId,provider:"deepseek-official",model:t.model}),t.onProgress?.({kind:"system",summary:`dsh model set to ${t.model}`})),t.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),i=await this.promptAndWait(o,t.cwd,t.sessionId,e,t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:Ei)}finally{await _r()}return t.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:t.sessionId,durationMs:Date.now()-n}}async openSession(e){let t=yi(e.env??process.env);oe("dsh",[],e.permissionMode??"yolo");let n=await Un(t),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!ed(s))throw await _r(),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 n.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let i=e.sessionId,o=this,a=0,l=!1,c=null,u=!1,d=!1,p=async()=>{d||(d=!0,await _r())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(m,h={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(u)throw new Error("dsh bundle session has a turn still in flight");if(h.signal?.aborted)throw new Error("Aborted");if(!ed(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);u=!0;let g=Date.now();try{let T=o.promptAndWait(n,e.cwd,i,m,Ei,h.signal);T.catch(()=>{});let f=await Promise.race([T,new Promise((E,y)=>{h.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await p()})().finally(()=>y(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:f,sessionId:i,durationMs:Date.now()-g}}finally{u=!1}},close(){return c!==null||(c=(async()=>{l=!0,await p()})()),c}}}async promptAndWait(e,t,n,s,i,o){let a=this.dshProvider.sessionFilePath(t,n),l=await S_(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=Date.now()+i;for(;;){if(o?.aborted)throw new Error("Aborted");let u=await td(a),d=u.find(p=>p.type==="turn/end"&&(p.seq??-1)>l);if(d){let p=d.data?.reason,m=[...u].reverse().find(g=>g.type==="assistant/message"),h=m?v_(m):"";if(p?.kind!=="completed"&&!h)throw new Error(T_(p));return h}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(p=>setTimeout(p,y_))}}};function yi(r){return{...r,DSH_PERMISSION_MODE:r.DSH_PERMISSION_MODE??"danger-full-access"}}function T_(r){let e=r?.kind??"unknown",t=r?.error?.message;return t?`dsh turn ended with reason=${e}: ${t}`:`dsh turn ended with reason=${e} and no assistant text`}function $n(r){return r instanceof Error?r.message:String(r)}async function S_(r){let e=await td(r),t=-1;for(let n of e)n.type==="turn/end"&&typeof n.seq=="number"&&n.seq>t&&(t=n.seq);return t}async function td(r){let e;try{e=await __(r)}catch{return[]}let t=Mn(e),n=[];for(let s of t.split(`
|
|
1987
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function v_(r){let t=r.data?.message?.content;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let n=[];for(let s of t)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&n.push(s.text);return n.join("")}import{mkdir as L_}from"node:fs/promises";import{existsSync as w_}from"node:fs";import{join as od,resolve as I_}from"node:path";import{createRequire as x_}from"node:module";var vi=null;function A_(){return vi===null&&(vi=x_(import.meta.url)("node:sqlite").DatabaseSync),vi}var rd="acp";function wi(r={}){return I_(r.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||od(
|
|
1985
|
+
`):"":""}function Mc(r){return r.model||r.message?.model}function Rg(r){let e=r.message?.content;return typeof e=="string"?e.length>0?1:0:Pc(r).filter(t=>!t.thought&&t.type!=="thinking"&&typeof t.text=="string"&&t.text.length>0).length}function gr(r,e=!1){if(r!==void 0){if(typeof r=="string")return r;try{return JSON.stringify(r,null,e?2:void 0)}catch{return String(r)}}}function Ng(r){if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let e=r;return gr(e.output??e.error??r)}return gr(r)}function Pc(r){return Array.isArray(r.message?.content)?r.message.content:r.message?.parts??[]}function Fc(r,e,t){let n=r.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:gr(r.args,!0),toolInputData:Ie(r.args),toolCallId:r.id,model:t}}var Cn=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||et(U,".qwen")}async discoverSessions(){let e=et(this.baseDir,"projects"),t;try{t=await Ln(e)}catch{return[]}let n=[];for(let s of t){let i=et(e,s,"chats"),o;try{o=await Ln(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=et(i,a);try{let u=await this.extractSummary(c,l);u&&n.push(u)}catch{}}}return n}async extractSummary(e,t){let n=!1,s=await te(e),i="(unknown)",o,a,l,c,u=0;for await(let d of Z(e)){if(n=!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)),Cc(d)){let m=Dc(d).trim();m&&(l||(l=M(m,80)),c=M(m,80),u++)}if(Oc(d)){let m=Mc(d);m&&(o=m),u+=Rg(d)}}return n?{provider:"qwen",sessionId:t,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 t=await this.resolveSessionPath(e);if(!t)return null;let n=Lc(t,".jsonl");return this.loadFromFile(t,n)}async loadFromFile(e,t){let n=await te(e),s="(unknown)",i,o,a,l,c,u,d=[],m=xg();for await(let h of Z(e)){if(Ag(m,h.usageMetadata),h.cwd&&(s=h.cwd,h.version&&(o=h.version),h.gitBranch&&(a=h.gitBranch)),h.type==="system"&&h.cwd&&(s=h.cwd,h.version&&(o=h.version),h.model&&(i=h.model),h.gitBranch&&(a=h.gitBranch)),!h.message)continue;let f=h.message,T=h.timestamp?new Date(h.timestamp):n.modifiedAt;if(h.type==="tool_result"){let _=Pc(h).filter(p=>p.functionResponse!==void 0);_.length===0&&h.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:T,content:gr(h.toolCallResult.resultDisplay??h.toolCallResult.error??h.toolCallResult.status)??"tool result",toolCallId:h.toolCallResult.callId});for(let p of _){let g=p.functionResponse,E=Ng(g.response),w=gr(h.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:T,content:w??E??h.toolCallResult?.status??"tool result",toolName:g.name,toolCallId:h.toolCallResult?.callId??g.id,...E!==void 0?{toolDetailedContent:E}:{}})}}else if(Cc(h)){let _=Dc(h);_.trim()&&(c||(c=M(_.trim(),80)),u=M(_.trim(),80)),d.push({role:"user",timestamp:T,content:_})}else if(Oc(h)){let _=Mc(h);if(_&&(i=_),Array.isArray(f.content))for(let p of f.content)p.type==="text"&&p.text?d.push({role:"assistant",timestamp:T,content:p.text,model:_}):p.type==="thinking"&&p.thinking?d.push({role:"thinking",timestamp:T,content:p.thinking}):p.functionCall&&d.push(Fc(p.functionCall,T,_));else if(typeof f.content=="string")d.push({role:"assistant",timestamp:T,content:f.content,model:_});else if(Array.isArray(f.parts))for(let p of f.parts)if(p.thought||p.type==="thinking"){let g=p.thinking||p.text;g&&d.push({role:"thinking",timestamp:T,content:g})}else p.functionCall?d.push(Fc(p.functionCall,T,_)):p.text&&d.push({role:"assistant",timestamp:T,content:p.text,model:_})}}return{provider:"qwen",sessionId:t,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(h=>h.role==="user"||h.role==="assistant").length,filePath:e,...bg(m),messages:d}}async resolveSessionPath(e){let t=et(this.baseDir,"projects");try{let n=await Ln(t),s=[];for(let i of n){let o=et(t,i,"chats",`${e}.jsonl`);try{return await wg(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=et(t,i,"chats"),a;try{a=await Ln(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Lc(l,".jsonl").startsWith(e)&&s.push(et(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let t=await this.resolveSessionPath(e);if(!t)return!1;try{return await Ig(t),!0}catch{return!1}}};function ui(){return new di}var di=class extends V{constructor(){super({provider:new Cn,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",W,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:Sn})}openSession(e){return vn({...e,binary:"qwen"})}seedArgsFor(e){let t=super.seedArgsFor(e);return e?.model?[...t,"--model",e.model]:t}};import{readdir as Uc,readFile as $c,rm as jc,stat as Bc}from"node:fs/promises";import{basename as mi,join as De}from"node:path";import{fileURLToPath as kg}from"node:url";var On=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||De(U,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:De(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=De(this.baseDir,"conversations"),t;try{t=await Uc(e)}catch{return[]}let n=[];for(let s of t){if(!s.endsWith(".db"))continue;let i=mi(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return De(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,t){return De(this.baseDir,"brain",e,".system_generated","logs",t?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let t of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await Bc(t),t}catch{}return null}async extractSummary(e){let t=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??t,i=await Lg([t,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,u=0;if(n)for await(let d of Z(n)){let m=qc(d.content);if(m&&(a=m),Wc(d)){let h=Xc(d.content).trim();h&&(l||(l=M(h,80)),c=M(h,80)),u++}else Hc(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:n?[t,n]:[t]}}async loadSession(e){let t=await this.resolveSessionPath(e);if(!t)return null;let n=Jc(t);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,u=[],d=[];if(i)for await(let m of Z(i)){let h=Cg(m.created_at,s.modifiedAt),f=qc(m.content);if(f&&(a=f),Wc(m)){let T=Xc(m.content),_=T.trim();_&&(l||(l=M(_,80)),c=M(_,80)),o.push({role:"user",timestamp:h,content:T});continue}if(Array.isArray(m.tool_calls))for(let T of m.tool_calls){let _=T.name||"tool",p=Dg(T.args),g=Ie(T.args),E={role:"tool_use",timestamp:h,content:p,toolName:_,toolInput:p,toolInputData:g};o.push(E),u.push({name:_,stepIndex:m.step_index,input:g,message:E})}if(Hc(m)&&m.content)o.push({role:"assistant",timestamp:h,content:m.content,model:a});else if(Og(m)&&m.content){let T=Ug(m,n),_=T===void 0?null:await this.readTaskLog(n,T),p={role:"tool_result",timestamp:_?.modifiedAt??h,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:T,..._===null?{}:{toolDetailedContent:_.content}};o.push(p),d.push({event:m,message:p})}m.thinking&&o.push({role:"thinking",timestamp:h,content:m.thinking})}return $g(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 t=this.conversationPath(e);try{return await Bc(t),t}catch{}let n=De(this.baseDir,"conversations");try{let s=[];for(let i of await Uc(n)){if(!i.endsWith(".db"))continue;mi(i,".db").startsWith(e)&&s.push(De(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let t=await this.resolveSessionPath(e);if(!t)return!1;let n=Jc(t);return n?(await jc(this.conversationPath(n),{force:!0}),await jc(De(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,t){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(t){let s=await Mg(t);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let t=De(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await $c(t,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}async readTaskLog(e,t){if(!/^task-\d+$/.test(t))return null;let n=De(this.baseDir,"brain",e,".system_generated","tasks",`${t}.log`);try{let[s,i]=await Promise.all([$c(n,"utf8"),te(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}};async function Lg(r){let e=await Promise.all(r.map(t=>te(t)));return{createdAt:new Date(Math.min(...e.map(t=>t.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(t=>t.modifiedAt.getTime())))}}function Cg(r,e){if(!r)return e;let t=new Date(r);return Number.isNaN(t.getTime())?e:t}function Wc(r){return r.type==="USER_INPUT"}function Hc(r){return r.source==="MODEL"&&r.type==="PLANNER_RESPONSE"}function Og(r){return r.source==="MODEL"&&r.type!=="PLANNER_RESPONSE"}function Xc(r){if(!r)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(r);return e?e[1]:r}function qc(r){if(!r)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(r);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function Dg(r){if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}}async function Mg(r){for await(let e of Z(r)){let t=e.tool_calls?.map(s=>s.args)??[];for(let s of t){let i=Fg(s);if(i)return i}let n=Pg(e.content);if(n)return n}return null}function Fg(r){if(!r||typeof r!="object"||Array.isArray(r))return null;let e=r,t=e.Cwd??e.cwd??e.DirectoryPath;return typeof t!="string"?null:t.replace(/^"|"$/g,"")}function Pg(r){return r?/"Cwd":"([^"]+)"/.exec(r)?.[1]??null:null}function Ug(r,e){if(r.status!=="RUNNING"||!r.content)return;let t=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(r.content);if(!(!t||t[1]!==e)&&!(r.step_index===void 0||Number(t[3])!==r.step_index))return t[2]}function $g(r,e){let t=new Set;for(let n of e){let s=jg(r,t,n);if(!s)continue;t.add(s);let i=n.event.step_index===void 0?void 0:`agy-step-${n.event.step_index}`;s.message.toolCallId=i,s.message.backgroundTaskId=n.message.backgroundTaskId,n.message.toolName=s.name,n.message.toolCallId=i}}function jg(r,e,t){let n=t.message.backgroundTaskId===void 0?void 0:Xg(t.event.content);if(n!==void 0)return Gc(r.filter(i=>!e.has(i)&&qg(i)===n),t.event.step_index);let s=Hg(t.event);if(s!==void 0)return Gc(r.filter(i=>!e.has(i)&&Bg(i.name,t.event.type)&&Vc(Wg(i))===s),t.event.step_index)}function Gc(r,e){if(r.length===0)return;if(r.length===1)return r[0];if(e===void 0)return;let t=r.map(n=>({call:n,distance:n.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(e-n.stepIndex)})).sort((n,s)=>n.distance-s.distance);return t[0].distance<t[1].distance?t[0].call:void 0}function Bg(r,e){return e==="VIEW_FILE"?r==="view_file":e!=="CODE_ACTION"?!1:r==="write_to_file"||r==="replace_file_content"||r==="multi_replace_file_content"}function Wg(r){let e=r.name==="view_file"?r.input?.AbsolutePath:r.input?.TargetFile;return typeof e=="string"?e:void 0}function Hg(r){if(!r.content)return;let e;return r.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(r.content)?.[1]:r.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(r.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(r.content)?.[1]),Vc(e)}function Vc(r){if(!r)return;let e=r.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return kg(e)}catch{return}}function Xg(r){if(r)return/Task Description:\s*([^\n]+)/.exec(r)?.[1]?.trim()}function qg(r){if(r.name==="run_command"){let e=r.input?.CommandLine;return typeof e=="string"?e:void 0}if(r.name==="schedule"){let e=r.input?.DurationSeconds,t=r.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof t!="string"?void 0:`Timer: ${e}s, Prompt: ${t}`}}function Jc(r){if(r.endsWith(".db"))return mi(r,".db");let e="/brain/",t=r.indexOf(e);return t===-1?null:r.slice(t+e.length).split("/")[0]||null}import{spawn as Gg}from"node:child_process";import{StringDecoder as Kc}from"node:string_decoder";function Dn(r){return async(e,t)=>{let n=Date.now(),s=r.buildArgs(e,t);r.assertArgs?.(s,t),t.onProgress?.({kind:"system",summary:`${r.label} -p one-shot started (no streaming events)`});let{stdout:i}=await Jg(r.label,t.binary,s,{cwd:t.cwd,env:ce(t.env,t.cwd,t.sessionId),signal:t.signal});return t.onProgress?.({kind:"system",summary:`${r.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:t.sessionId,durationMs:Date.now()-n}}}function Jg(r,e,t,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${r} turn aborted`));return}let o;try{o=Gg(e,t,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new Kc("utf8"),u=new Kc("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(`${r} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,h)=>{if(n.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let f=h?`signal ${h}`:`exit code ${m}`,T=l.trim()||a.trim();i(new Error(`${r} failed (${f})${T?`: ${T}`:""}`))}),n.signal?.aborted?d():n.signal?.addEventListener("abort",d,{once:!0})})}function pi(r){return new fi(r)}var fi=class extends V{constructor(e){super({provider:new On(e),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",W,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:Vg})}seedArgsFor(e){let t=[...super.seedArgsFor(e)];return e?.model&&t.push("--model",e.model),t}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}`}}},Vg=Dn({label:"agy",buildArgs:(r,e)=>{let t=["--conversation",e.sessionId,"-p",r,"--dangerously-skip-permissions","--print-timeout",Kg(e.timeoutMs)];return e.model&&t.push("--model",e.model),t},assertArgs:(r,e)=>oe("agy",r,e.permissionMode??"yolo")});function Kg(r){return!r||r<=0?"8h":`${Math.max(1,Math.ceil(r/1e3))}s`}import{randomUUID as g_}from"node:crypto";import{existsSync as ed}from"node:fs";import{readFile as __,mkdir as E_}from"node:fs/promises";import{readdir as hi,rm as l_,stat as c_}from"node:fs/promises";import{join as tt}from"node:path";import Yg from"node:zlib";var zg=Yg.zstdDecompressSync,Qg=40,Zg=181,e_=47,t_=253,r_=42,n_=77,s_=24;function i_(r,e){return r[e]===Qg&&r[e+1]===Zg&&r[e+2]===e_&&r[e+3]===t_}function Yc(r,e){return(r[e]&240)===80&&r[e+1]===r_&&r[e+2]===n_&&r[e+3]===s_}function o_(r,e){if(Yc(r,e))return e+8>r.length?void 0:8+r.readUInt32LE(e+4);if(!i_(r,e))return;let t=e+4;if(t+1>r.length)return;let n=r[t];t+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(t+=1),t+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(t+=l,!(t>r.length)){for(;;){if(t+3>r.length)return;let c=r[t]|r[t+1]<<8|r[t+2]<<16,u=(c&1)!==0,d=c>>1&3,m=c>>3;if(t+=3,d===3||(t+=d===1?1:m,t>r.length))return;if(u)break}if(o&&(t+=4),!(t>r.length))return t-e}}function a_(r){let e=[],t=0;for(;t+4<=r.length;){let n=o_(r,t);if(n===void 0||n<=0)break;e.push(r.subarray(t,t+n)),t+=n}return e}function Mn(r){let e=[];for(let t of a_(r))Yc(t,0)||e.push(zg(t).toString("utf8"));return e.join("")}var Pn=class{name="dsh";sessionsDir;constructor(e={}){let t=e.dshHome||tt(U,".dsh");this.sessionsDir=tt(t,"sessions")}async discoverSessions(){let e=[],t;try{t=await hi(this.sessionsDir)}catch{return[]}for(let n of t){let s;try{s=await hi(tt(this.sessionsDir,n))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(n,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let t=await this.findSessionDir(e);if(!t)return null;let n=await this.readRecords(t.cwdDir,t.sessionDir);if(n.length===0)return null;let s=zc(n),i=Qc(n,t.filePath,s);return i?{...i,turnStatus:m_(n),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let t=await this.findSessionDir(e);return t?(await l_(tt(this.sessionsDir,t.cwdDir,t.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,t){return tt(this.sessionsDir,d_(e),t,"session.jsonl.zstd")}async findSessionDir(e){let t;try{t=await hi(this.sessionsDir)}catch{return null}for(let n of t){let s=e,i=tt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await c_(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,t){let{readFile:n}=await import("node:fs/promises"),s=tt(this.sessionsDir,e,t,"session.jsonl.zstd"),i=await n(s),o=Mn(i),a=[];for(let l of o.split(`
|
|
1986
|
+
`))if(l.trim())try{let c=JSON.parse(l);if(c.type?.endsWith("-chunks")||c.type==="assistant/chunk")continue;a.push(c)}catch{}return a}async readSummary(e,t){let n=await this.readRecords(e,t);if(n.length===0)return null;let s=tt(this.sessionsDir,e,t,"session.jsonl.zstd");return Qc(n,s,zc(n))}};function d_(r){return"--"+r.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function gi(r){if(typeof r=="string")return r;if(!Array.isArray(r))return"";let e=[];for(let t of r)t&&typeof t=="object"&&t.type==="text"&&typeof t.text=="string"&&e.push(t.text);return e.join("")}function u_(r){if(!Array.isArray(r))return[];let e=[];for(let t of r)t&&typeof t=="object"&&t.type==="reasoning"&&typeof t.text=="string"&&e.push(t.text);return e}function zc(r){let e=[];for(let t of r){let n=t.data??{},s=t.time?new Date(t.time):new Date(0);if(t.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:gi(i.content)})}else if(t.type==="assistant/message"){let i=n.message;for(let o of u_(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:gi(i?.content),model:i?.source?.model})}else if(t.type==="tool/call"){let i=n,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(t.type==="tool/result"){let i=n,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:gi(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function m_(r){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.type==="turn/end")return t.data?.reason?.kind==="completed"?"complete":"aborted";if(t.type==="turn/start")return"in_progress"}}function Qc(r,e,t){let n=r.find(h=>h.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let h of r)if(h.type==="request/header"){let f=h.data?.header;f?.config?.model&&(a=f.config.model)}let l=r.map(h=>h.time).filter(h=>typeof h=="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=t.filter(h=>h.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:t.filter(h=>h.role==="user"||h.role==="assistant").length,filePath:e,...f_(r)}}function f_(r){let e=!1,t=0,n=0,s=0,i=0,o,a;for(let l of r){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let u=Fn(c.inputTokens),d=Fn(c.cacheReadTokens),m=Fn(c.outputTokens),h=Fn(c.reasoningTokens);t+=u,n+=d,s+=m,i+=h,o=u+d,a={inputTokens:u,cachedInputTokens:d,outputTokens:m,reasoningOutputTokens:h,totalTokens:u+d+m}}return{totalInputTokens:e?t:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function Fn(r){let e=Number(r??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}import{spawn as p_}from"node:child_process";var h_=/dsh web:\s*(https?:\/\/\S+)/,Zc=2e4,Ft=class r extends Error{method;detail;constructor(e,t){super(`dsh RPC ${e} failed: ${JSON.stringify(t)}`),this.name="DshRpcCallError",this.method=e,this.detail=t,Object.setPrototypeOf(this,r.prototype)}},_i=class r{baseUrl;child;constructor(e,t){this.baseUrl=e,this.child=t}static forTesting(e){return new r(e,void 0)}async rpc(e,t){let n=`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s;try{s=await fetch(`${this.baseUrl}/api/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:n,method:e,payload:t})})}catch(a){throw new Ft(e,`transport error: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await s.json()}catch{i=void 0}if(!s.ok)throw new Ft(e,i??s.statusText);let o=i&&typeof i=="object"?i.result:void 0;if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new Ft(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new Ft(e,o.error??o);return"value"in o?o.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&&this.child.kill("SIGTERM")}static spawn(e){return new Promise((t,n)=>{let s=p_("dsh",["web","--no-open","--port","0"],{env:e,stdio:["ignore","pipe","pipe"]}),i=!1,o="",a="",l=setTimeout(()=>{i||(i=!0,s.kill("SIGTERM"),n(new Error(`dsh web sidecar did not report a boot URL within ${Zc}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},Zc);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let u=h_.exec(o);u&&(i=!0,clearTimeout(l),t(new r(u[1],s)))}),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("error",c=>{i||(i=!0,clearTimeout(l),n(c))}),s.on("exit",(c,u)=>{if(i)return;i=!0,clearTimeout(l);let d=u?`signal ${u}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${d}): ${a.slice(0,500)}`))})})}},rt;async function Un(r,e=t=>_i.spawn(t)){if(rt){let t=await rt.catch(()=>{});if(t?.alive)return t;rt=void 0}return rt=e(r),rt}async function _r(){if(!rt)return;(await rt.catch(()=>{}))?.shutdown(),rt=void 0}var y_=500,Ei=8*60*60*1e3;function Si(r){return new Ti(r)}var Ti=class extends V{dshProvider;constructor(e){let t=new Pn(e);super({provider:t,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:(n,s)=>this.dshPromptTurn(n,s)}),this.dshProvider=t}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,t){await E_(e,{recursive:!0});let n=`session-${g_()}`,s=yi(process.env);oe("dsh",[],"yolo");try{let i;try{i=await Un(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${$n(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${$n(a)}`}}if(t?.model)try{await i.rpc("session.selectModel",{sessionId:n,provider:"deepseek-official",model:t.model})}catch(a){return{success:!1,error:`session.selectModel("${t.model}") failed: ${$n(a)}`}}let o=t?.prompt??W;try{await this.promptAndWait(i,e,n,o,Ei)}catch(a){return{success:!1,error:`seed turn failed: ${$n(a)}`}}return{success:!0,sessionId:n}}finally{await _r()}}async dshPromptTurn(e,t){let n=Date.now();if(t.bundleSession!==void 0){let o=t.bundleSession;if(o.provider!=="dsh")throw new Error(`bundle session provider mismatch: session serves "${o.provider}", turn targets "dsh"`);let a=await o.sendTurn(e,{signal:t.signal});return{text:a.text,sessionId:a.sessionId,durationMs:a.durationMs,...a.warnings!==void 0?{warnings:a.warnings}:{}}}let s=yi(t.env??process.env);oe("dsh",[],t.permissionMode??"yolo");let i;try{let o=await Un(s);t.model&&(await o.rpc("session.selectModel",{sessionId:t.sessionId,provider:"deepseek-official",model:t.model}),t.onProgress?.({kind:"system",summary:`dsh model set to ${t.model}`})),t.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),i=await this.promptAndWait(o,t.cwd,t.sessionId,e,t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:Ei)}finally{await _r()}return t.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:t.sessionId,durationMs:Date.now()-n}}async openSession(e){let t=yi(e.env??process.env);oe("dsh",[],e.permissionMode??"yolo");let n=await Un(t),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!ed(s))throw await _r(),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 n.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let i=e.sessionId,o=this,a=0,l=!1,c=null,u=!1,d=!1,m=async()=>{d||(d=!0,await _r())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(h,f={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(u)throw new Error("dsh bundle session has a turn still in flight");if(f.signal?.aborted)throw new Error("Aborted");if(!ed(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);u=!0;let T=Date.now();try{let _=o.promptAndWait(n,e.cwd,i,h,Ei,f.signal);_.catch(()=>{});let p=await Promise.race([_,new Promise((g,E)=>{f.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await m()})().finally(()=>E(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:p,sessionId:i,durationMs:Date.now()-T}}finally{u=!1}},close(){return c!==null||(c=(async()=>{l=!0,await m()})()),c}}}async promptAndWait(e,t,n,s,i,o){let a=this.dshProvider.sessionFilePath(t,n),l=await S_(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=Date.now()+i;for(;;){if(o?.aborted)throw new Error("Aborted");let u=await td(a),d=u.find(m=>m.type==="turn/end"&&(m.seq??-1)>l);if(d){let m=d.data?.reason,h=[...u].reverse().find(T=>T.type==="assistant/message"),f=h?v_(h):"";if(m?.kind!=="completed"&&!f)throw new Error(T_(m));return f}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(m=>setTimeout(m,y_))}}};function yi(r){return{...r,DSH_PERMISSION_MODE:r.DSH_PERMISSION_MODE??"danger-full-access"}}function T_(r){let e=r?.kind??"unknown",t=r?.error?.message;return t?`dsh turn ended with reason=${e}: ${t}`:`dsh turn ended with reason=${e} and no assistant text`}function $n(r){return r instanceof Error?r.message:String(r)}async function S_(r){let e=await td(r),t=-1;for(let n of e)n.type==="turn/end"&&typeof n.seq=="number"&&n.seq>t&&(t=n.seq);return t}async function td(r){let e;try{e=await __(r)}catch{return[]}let t=Mn(e),n=[];for(let s of t.split(`
|
|
1987
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function v_(r){let t=r.data?.message?.content;if(typeof t=="string")return t;if(!Array.isArray(t))return"";let n=[];for(let s of t)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&n.push(s.text);return n.join("")}import{mkdir as L_}from"node:fs/promises";import{existsSync as w_}from"node:fs";import{join as od,resolve as I_}from"node:path";import{createRequire as x_}from"node:module";var vi=null;function A_(){return vi===null&&(vi=x_(import.meta.url)("node:sqlite").DatabaseSync),vi}var rd="acp";function wi(r={}){return I_(r.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||od(U,".hermes"))}function b_(r={}){return od(wi(r),"state.db")}var nd=`id, source, model, model_config, started_at,
|
|
1988
1988
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
1989
1989
|
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;function Er(r){let e=typeof r=="number"&&Number.isFinite(r)?r:0;return new Date(e*1e3)}function fe(r){return typeof r=="string"&&r.length>0?r:void 0}function R_(r){if(!r)return{};try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function sd(r){return fe(r.cwd)??fe(R_(r.model_config).cwd)??"(unknown)"}var jn=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=b_(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!w_(this.dbPath))return null;let e=null;try{return e=new(A_())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(t){return e?.close(),b({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:t instanceof Error?t.message:String(t)}),null}}selectSessionRow(e,t){return e.prepare(`SELECT ${nd} FROM sessions WHERE id = ? AND source = ?`).get(t,rd)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let t=e.prepare(`SELECT ${nd} FROM sessions
|
|
1990
1990
|
WHERE source = ?
|
|
1991
1991
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
1992
1992
|
LIMIT ?`).all(rd,this.discoverLimit),n=[];for(let s of t){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:fe(s.title),cwd:sd(s),createdAt:Er(s.started_at),modifiedAt:Er(s.last_activity_at??s.started_at),model:fe(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...id(s)})}return n}catch(t){return b({event:"hermes_discover_sessions_failed",provider:this.name,db_path:this.dbPath,error_message:t instanceof Error?t.message:String(t)}),[]}finally{e.close()}}activeMessageRows(e,t){let n=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,
|
|
1993
1993
|
timestamp, finish_reason${["_compressed_summary","display_kind"].filter(a=>n.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(t)}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(t)}}previewTexts(e,t){try{let[n,s]=["ASC","DESC"].map(i=>{let o=`SELECT content FROM messages WHERE session_id = ?
|
|
1994
|
-
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(t)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(t)}return a?M(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let t=this.openDb();if(!t)return null;try{let n=this.selectSessionRow(t,e);if(!n)return null;let s=this.activeMessageRows(t,e),i=[],o=[],a,l;for(let c of s){let u=Er(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=M(d,80)),l=M(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:fe(c.tool_call_id),toolName:fe(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:fe(n.model),stopReason:fe(c.finish_reason)});for(let p of N_(c.tool_calls)){let m=k_(p.function?.arguments);i.push({role:"tool_use",timestamp:u,content:fe(p.function?.name)??"tool_call",toolName:fe(p.function?.name),toolCallId:fe(p.call_id)??fe(p.id),toolInput:typeof p.function?.arguments=="string"?p.function.arguments:JSON.stringify(p.function?.arguments??{}),toolInputData:we(m)})}}return{provider:this.name,sessionId:n.id,slug:fe(n.title),cwd:sd(n),createdAt:Er(n.started_at),modifiedAt:Er(n.last_activity_at??n.started_at),model:fe(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...id(n),messages:i,userPrompts:o}}catch(n){return b({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}finally{t.close()}}async resolveSessionPath(e){let t=this.openDb();if(!t)return null;try{return this.selectSessionRow(t,e)?this.dbPath:null}catch{return null}finally{t.close()}}async deleteSession(e){return!1}};function N_(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function k_(r){if(r!==null&&typeof r=="object"&&!Array.isArray(r))return r;if(typeof r!="string")return{};try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function id(r){let e=r.input_tokens??0,t=r.output_tokens??0,n=r.cache_read_tokens??0,s=r.cache_write_tokens??0,i=r.reasoning_tokens??0;return(r.message_count??0)>0&&e+t+n+s+i>0?{totalInputTokens:e,totalCachedInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:t,totalReasoningOutputTokens:i}:{}}var C_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function O_(r){return C_.test(r)}var D_="dont_ask";function ad(r){if(r==="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 D_}function xi(r){return new Ii(r)}var Ii=class extends J{hermesProvider;hermesHome;constructor(e){let t=new jn(e);super({provider:t,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(n,s)=>Le(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:ad(s.permissionMode)})}),this.hermesProvider=t,this.hermesHome=wi(e)}async openSession(e){return Ce({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:ad(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,t){await L_(e,{recursive:!0});let n=[];if(t?.effort){let i="hermes has no ACP-level effort surface";b({event:"hermes_effort_ignored",provider:this.name,effort:t.effort,reason:i}),n.push(`hermes seed ignored effort=${t.effort}: ${i}`)}let s;try{s=await this.sendTurn(t?.prompt??H,{sessionId:"",cwd:e,model:t?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return O_(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(b({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 ld,rm as M_,stat as F_}from"node:fs/promises";import{join as Ai}from"node:path";var Bn=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Ai(P,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let t of await this.listSessionFiles())try{let n=await this.extractSummary(t);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await ld(this.baseDir)}catch{return[]}let t=[];for(let n of e){let s=Ai(this.baseDir,n);try{if(!(await F_(s)).isDirectory())continue;for(let i of await ld(s))i.endsWith(".jsonl")&&t.push(Ai(s,i))}catch{}}return t}async readHeader(e){for await(let t of Z(e))return t.type==="session"?t:null;return null}async extractSummary(e){let t=await this.readHeader(e);if(!t)return null;let n=await te(e),s,i,o,a=0,l=0,c=0,u=0,d=0,p=0,m=0,h;for await(let g of Z(e)){if(g.type==="model_change"&&g.provider&&g.modelId){s=`${g.provider}/${g.modelId}`;continue}if(g.type!=="message"||!g.message)continue;let T=g.message;if(T.provider&&T.model&&(s=`${T.provider}/${T.model}`),T.role==="user"){let f=bi(T).trim();f&&(i||(i=M(f,80)),o=M(f,80)),a++}else if(T.role==="assistant"){a++;let f=T.usage;f&&(l+=f.input??0,c+=f.cacheRead??0,u+=f.cacheWrite??0,d+=f.output??0,p+=f.reasoning??0,m=f.input??0,h={inputTokens:f.input,cachedInputTokens:f.cacheRead,cacheWriteInputTokens:f.cacheWrite,outputTokens:f.output,reasoningOutputTokens:f.reasoning,totalTokens:f.totalTokens})}}return{provider:"pi",sessionId:t.id,cwd:t.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:u,totalOutputTokens:d,totalReasoningOutputTokens:p,lastInputTokens:m,lastTokenUsage:h}}async loadSession(e){let t=await this.resolveSessionPath(e);if(!t)return null;let n=await this.extractSummary(t);if(!n)return null;let s=[],i=n.model;for await(let o of Z(t)){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):n.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:bi(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:cd(c.arguments),toolName:c.name??"tool",toolInput:cd(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:bi(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...n,model:i,messages:s}}async resolveSessionPath(e){let t=`_${e}.jsonl`,n=[];for(let s of await this.listSessionFiles()){if(s.endsWith(t))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&n.push(s)}return n.length===1?n[0]:null}async deleteSession(e){let t=await this.resolveSessionPath(e);return t?(await M_(t,{force:!0}),!0):!1}};function bi(r){return typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function cd(r){if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}}function Ni(r){return new Ri(r)}var Ri=class extends J{constructor(e){super({provider:new Bn(e),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",H],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:P_})}seedArgsFor(e){let t=[...super.seedArgsFor(e)];return e?.model&&t.push("--model",e.model),t}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}`}}},P_=Dn({label:"pi",buildArgs:(r,e)=>{let t=["--session",e.sessionId,"-p",r];return e.model&&t.push("--model",e.model),t},assertArgs:(r,e)=>oe("pi",r,e.permissionMode??"yolo")});import{createHash as U_}from"node:crypto";import{existsSync as $_,mkdirSync as Li,readFileSync as j_,renameSync as B_,rmdirSync as _d,statSync as W_,writeFileSync as H_}from"node:fs";import{dirname as Mi,join as dd,resolve as ki}from"node:path";var Pt=new Map;function X_(r){return U_("sha256").update(r).digest("hex").slice(0,8)}function q_(r){let e=r.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function G_(r,e){let t=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(t);return n!==null?n[1]:r.split(/[\\/]/).filter(Boolean).pop()??"session"}function Ed(r){return r.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Wn(r){return Math.max(1,Math.ceil(r.length/4))}function Ut(r=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return ki(e);let t=process.env.LMCTL_DB;return t!==void 0&&t.trim().length>0?dd(Mi(ki(t)),".lmctl-claude-mock","sessions.json"):dd(ki(r),".lmctl-claude-mock","sessions.json")}function ud(){return{schemaVersion:1,sessions:{}}}function yr(r){if(!$_(r))return ud();try{let e=JSON.parse(j_(r,"utf8")),t=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=Ci(e.defaultDelayMs);return{schemaVersion:1,sessions:t,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return ud()}}function yd(r,e){Li(Mi(r),{recursive:!0});let t=`${r}.${process.pid}.${Date.now()}.tmp`;H_(t,`${JSON.stringify(e,null,2)}
|
|
1995
|
-
`,"utf8"),B_(t,r)}var J_=5e3,V_=15,md=1e4;function K_(r){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function Y_(r){let e=`${r}.lock`;Li(Mi(r),{recursive:!0});let t=Date.now()+md;for(;;)try{return Li(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-W_(e).mtimeMs>J_){try{_d(e)}catch{}continue}}catch{continue}if(Date.now()>=t)throw new Error(`ClaudeMock store lock timeout after ${md}ms: ${e}`);K_(V_)}}function z_(r){try{_d(r)}catch{}}function Td(r,e){let t=Y_(r);try{return e()}finally{z_(t)}}function Q_(r){return{...r,timestamp:r.timestamp.toISOString()}}function Z_(r){return{...r,timestamp:new Date(r.timestamp)}}function eE(r){return{...r,createdAt:r.createdAt.toISOString(),modifiedAt:r.modifiedAt.toISOString(),messages:r.messages.map(Q_)}}function Sd(r){return{...r,createdAt:new Date(r.createdAt),modifiedAt:new Date(r.modifiedAt),messages:r.messages.map(Z_)}}function Hn(r,e=process.cwd()){let t=Pt.get(r);if(t!==void 0)return t;let s=yr(Ut(e)).sessions[r];if(s===void 0)return;let i=Sd(s);return Pt.set(i.sessionId,i),i}function fd(r){Pt.set(r.sessionId,r);let e=Ut(r.cwd);Td(e,()=>{let t=yr(e);t.sessions[r.sessionId]=eE({...r,filePath:e}),yd(e,t)})}function tE(r,e=process.cwd()){let t=Ut(e);return Td(t,()=>{let n=yr(t),s=n.sessions[r]!==void 0;return s&&(delete n.sessions[r],yd(t,n)),s})}function rE(){let r=yr(Ut()),e=Object.values(r.sessions).map(Sd);for(let t of e)Pt.set(t.sessionId,t);return e}function Ci(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0}function pd(r){if(typeof r=="string")return{kind:"success",text:r};if(r!==void 0&&typeof r.text=="string"&&typeof r.error!="string"){let e=Ci(r.delayMs);return{kind:"success",text:r.text,...e!==void 0?{delayMs:e}:{}}}if(r!==void 0&&typeof r.error=="string"&&typeof r.text!="string"){let e=Ci(r.delayMs);return{kind:"error",error:r.error,...e!==void 0?{delayMs:e}:{}}}}async function hd(r){r!==void 0&&r>0&&await new Promise(e=>setTimeout(e,r))}function nE(r,e){let{script:t,scriptContains:n}=e;if(t!==void 0){let s=pd(t[r]??t[Ed(r)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(r.includes(s)){let i=pd(n[s]);if(i!==void 0)return i}}}function gd(r){return{provider:"ClaudeMock",sessionId:r.sessionId,cwd:r.cwd,createdAt:r.createdAt,modifiedAt:r.modifiedAt,messageCount:r.messages.length,filePath:r.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,lastTokenUsage:{totalTokens:r.totalInputTokens+r.totalOutputTokens}}}var Oi=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let t of rE())e.set(t.sessionId,t);for(let t of Pt.values())e.set(t.sessionId,t);return[...e.values()].map(gd)}async loadSession(e){let t=Hn(e);return t===void 0?null:{...gd(t),messages:t.messages.slice()}}async resolveSessionPath(e){return Hn(e)?.filePath??null}async deleteSession(e){let t=Pt.delete(e),n=tE(e);return t||n}},Di=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Oi;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,t){let n=q_(G_(e,t)),s=`mock-${n}-${X_(`${e}:${n}`)}`,i=new Date,o=Ut(e),a=Hn(s,e),l=t?.prompt??"ClaudeMock seed",c=Wn(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+=Wn("ACK: ClaudeMock seeded"),fd(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,t){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,t){let n=Date.now(),s=Hn(t.sessionId,t.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${t.sessionId}`);let i=new Date,o=yr(Ut(t.cwd)),a=nE(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await hd(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Ed(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:t.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=Wn(e),s.totalOutputTokens+=Wn(c),fd(s),t.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await hd(l),{text:c,sessionId:t.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}};function Fi(){return new Di}function ht(r){let e=[qs({claudeDir:r?.claudeDir}),Vs({codexDir:r?.codexDir,codeDir:r?.codeDir}),Qs({geminiDir:r?.geminiDir,claudeDir:r?.claudeDir,codexDir:r?.codexDir,codeDir:r?.codeDir}),ti({copilotDir:r?.copilotDir}),ni(),ai({kimiHome:r?.kimiHome}),ci({lmplayerDbPath:r?.lmplayerDbPath}),ui(),pi({agyDir:r?.agyDir}),Si({dshHome:r?.dshHome}),xi({hermesHome:r?.hermesHome}),Ni({piDir:r?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Fi()),e}var Pi=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],Ui=["agy","pi","lmplayer"];var $i=null;function Xn(){return $i===null&&($i=dt(ht())),$i}function ji(r,e){let t=r.getAdapter(e);if(!t)throw new Error(`provider "${e}" is not registered in this registry`);return t}async function qn(r){let e=r.registry??Xn(),t=ji(e,r.provider),n={sessionId:r.sessionId,cwd:r.cwd,env:r.env,onDelta:r.onDelta,onProgress:r.onProgress,signal:r.signal,timeoutMs:r.timeoutMs,model:r.model,effort:r.effort,progPath:r.progPath,alias:r.alias,isLead:r.isLead,permissionMode:r.permissionMode,holdOpen:r.holdOpen,requireResume:r.requireResume,bundleSession:r.bundleSession},s=await t.sendTurn(r.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs,...s.warnings!==void 0?{warnings:s.warnings}:{}}}function Bi(r){return(r??Xn()).getAllAdapters().filter(t=>t.openSession!==void 0).map(t=>t.name)}async function wd(r){let e=r.registry??Xn(),t=ji(e,r.provider);if(t.openSession===void 0)throw new Error(`provider "${r.provider}" does not support bundle sessions in this version (supported: ${Bi(e).join(", ")})`);return t.openSession(r)}async function Id(r){let e=r.registry??Xn(),t=ji(e,r.provider),n=await vd(e,r.provider,r.cwd),s=await t.seed(r.cwd,{model:r.model,effort:r.effort,prompt:r.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await vd(e,r.provider,r.cwd),a=sE(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function vd(r,e,t){let n=await r.listAll({provider:e,workspace:t}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function sE(r,e){let t=[];for(let n of e.keys())r.has(n)||t.push(n);return t.length===1?t[0]:void 0}var iE={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:[]};var rb=new Set(Object.keys(iE));var Wi=null;function xd(){return Wi===null&&(Wi=dt(ht())),Wi}function Ad(r,e){return xd().getSession(r,e)}async function bd(r){return(await xd().resolveSessions(r)).map(t=>t.provider.name)}var Rd=36e5;function oE(r=process.env){let e=r.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return Rd;let t=Number(e);return!Number.isFinite(t)||t<=0?Rd:t}async function aE(r,e,t){try{let n=st(e,t,r),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let c=await bd(s);if(c.length!==1)return null;i=c[0]}let o=await Ad(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 Nd(r,e,t,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??oE(),o=await aE(r,t,n),a=o!==null&&o>=i;return a&&b({event:"session_idle_reclaim",receiver_teamfile:t,receiver_alias:n,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 kd=ro(bs(),1);function lE(r){return r===null?null:_e(r)?"live":"dead"}function Hi(r){let e=r.nowMs??Date.now(),t=Date.parse(r.since);return{holder_pid:r.holderPid,holder_liveness:lE(r.holderPid),since:r.since,idle_ms:Number.isFinite(t)?Math.max(0,e-t):null}}function cE(r){return(0,kd.formatDuration)(r)}function Xi(r){let e=[];return r.idle_ms!==null&&e.push(`active ${cE(r.idle_ms)}`),e.push(`since ${r.since}`),e.push(r.holder_pid===null?"holder_pid=unavailable":`holder_pid=${r.holder_pid}, ${r.holder_liveness}`),`(${e.join("; ")})`}import{hostname as dE,networkInterfaces as ub}from"node:os";var uE=12e4;function mE(r=process.env){return fE(r.LMCTL_TERMINAL_LOCK_STALE_MS,uE)}function qi(r,e={}){let t=e.now??new Date,n=e.localHost??dE(),s=e.staleMs??mE();if(r.holder_host===n)return(e.isProcessAlive??pE)(r.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(r.last_heartbeat);return Number.isFinite(i)?t.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function Tr(r){return`${r.alias} is held by a terminal on ${r.holder_host} since ${r.started_at}; retry later`}function fE(r,e){if(r===void 0||r.trim()==="")return e;let t=r.trim(),n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0||String(n)!==t?e:n}function pE(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function Gn(r){return`lmctl ${r}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
1994
|
+
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(t)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(t)}return a?M(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let t=this.openDb();if(!t)return null;try{let n=this.selectSessionRow(t,e);if(!n)return null;let s=this.activeMessageRows(t,e),i=[],o=[],a,l;for(let c of s){let u=Er(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=M(d,80)),l=M(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:fe(c.tool_call_id),toolName:fe(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:fe(n.model),stopReason:fe(c.finish_reason)});for(let m of N_(c.tool_calls)){let h=k_(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:fe(m.function?.name)??"tool_call",toolName:fe(m.function?.name),toolCallId:fe(m.call_id)??fe(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Ie(h)})}}return{provider:this.name,sessionId:n.id,slug:fe(n.title),cwd:sd(n),createdAt:Er(n.started_at),modifiedAt:Er(n.last_activity_at??n.started_at),model:fe(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...id(n),messages:i,userPrompts:o}}catch(n){return b({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}finally{t.close()}}async resolveSessionPath(e){let t=this.openDb();if(!t)return null;try{return this.selectSessionRow(t,e)?this.dbPath:null}catch{return null}finally{t.close()}}async deleteSession(e){return!1}};function N_(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function k_(r){if(r!==null&&typeof r=="object"&&!Array.isArray(r))return r;if(typeof r!="string")return{};try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function id(r){let e=r.input_tokens??0,t=r.output_tokens??0,n=r.cache_read_tokens??0,s=r.cache_write_tokens??0,i=r.reasoning_tokens??0;return(r.message_count??0)>0&&e+t+n+s+i>0?{totalInputTokens:e,totalCachedInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:t,totalReasoningOutputTokens:i}:{}}var C_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function O_(r){return C_.test(r)}var D_="dont_ask";function ad(r){if(r==="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 D_}function xi(r){return new Ii(r)}var Ii=class extends V{hermesProvider;hermesHome;constructor(e){let t=new jn(e);super({provider:t,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(n,s)=>Ce(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:ad(s.permissionMode)})}),this.hermesProvider=t,this.hermesHome=wi(e)}async openSession(e){return Oe({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:ad(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,t){await L_(e,{recursive:!0});let n=[];if(t?.effort){let i="hermes has no ACP-level effort surface";b({event:"hermes_effort_ignored",provider:this.name,effort:t.effort,reason:i}),n.push(`hermes seed ignored effort=${t.effort}: ${i}`)}let s;try{s=await this.sendTurn(t?.prompt??W,{sessionId:"",cwd:e,model:t?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return O_(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(b({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 ld,rm as M_,stat as F_}from"node:fs/promises";import{join as Ai}from"node:path";var Bn=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Ai(U,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let t of await this.listSessionFiles())try{let n=await this.extractSummary(t);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await ld(this.baseDir)}catch{return[]}let t=[];for(let n of e){let s=Ai(this.baseDir,n);try{if(!(await F_(s)).isDirectory())continue;for(let i of await ld(s))i.endsWith(".jsonl")&&t.push(Ai(s,i))}catch{}}return t}async readHeader(e){for await(let t of Z(e))return t.type==="session"?t:null;return null}async extractSummary(e){let t=await this.readHeader(e);if(!t)return null;let n=await te(e),s,i,o,a=0,l=0,c=0,u=0,d=0,m=0,h=0,f;for await(let T of Z(e)){if(T.type==="model_change"&&T.provider&&T.modelId){s=`${T.provider}/${T.modelId}`;continue}if(T.type!=="message"||!T.message)continue;let _=T.message;if(_.provider&&_.model&&(s=`${_.provider}/${_.model}`),_.role==="user"){let p=bi(_).trim();p&&(i||(i=M(p,80)),o=M(p,80)),a++}else if(_.role==="assistant"){a++;let p=_.usage;p&&(l+=p.input??0,c+=p.cacheRead??0,u+=p.cacheWrite??0,d+=p.output??0,m+=p.reasoning??0,h=p.input??0,f={inputTokens:p.input,cachedInputTokens:p.cacheRead,cacheWriteInputTokens:p.cacheWrite,outputTokens:p.output,reasoningOutputTokens:p.reasoning,totalTokens:p.totalTokens})}}return{provider:"pi",sessionId:t.id,cwd:t.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:h,lastTokenUsage:f}}async loadSession(e){let t=await this.resolveSessionPath(e);if(!t)return null;let n=await this.extractSummary(t);if(!n)return null;let s=[],i=n.model;for await(let o of Z(t)){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):n.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:bi(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:cd(c.arguments),toolName:c.name??"tool",toolInput:cd(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:bi(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...n,model:i,messages:s}}async resolveSessionPath(e){let t=`_${e}.jsonl`,n=[];for(let s of await this.listSessionFiles()){if(s.endsWith(t))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&n.push(s)}return n.length===1?n[0]:null}async deleteSession(e){let t=await this.resolveSessionPath(e);return t?(await M_(t,{force:!0}),!0):!1}};function bi(r){return typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function cd(r){if(r===void 0)return"";try{return JSON.stringify(r)}catch{return String(r)}}function Ni(r){return new Ri(r)}var Ri=class extends V{constructor(e){super({provider:new Bn(e),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",W],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:P_})}seedArgsFor(e){let t=[...super.seedArgsFor(e)];return e?.model&&t.push("--model",e.model),t}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}`}}},P_=Dn({label:"pi",buildArgs:(r,e)=>{let t=["--session",e.sessionId,"-p",r];return e.model&&t.push("--model",e.model),t},assertArgs:(r,e)=>oe("pi",r,e.permissionMode??"yolo")});import{createHash as U_}from"node:crypto";import{existsSync as $_,mkdirSync as Li,readFileSync as j_,renameSync as B_,rmdirSync as _d,statSync as W_,writeFileSync as H_}from"node:fs";import{dirname as Mi,join as dd,resolve as ki}from"node:path";var Pt=new Map;function X_(r){return U_("sha256").update(r).digest("hex").slice(0,8)}function q_(r){let e=r.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function G_(r,e){let t=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(t);return n!==null?n[1]:r.split(/[\\/]/).filter(Boolean).pop()??"session"}function Ed(r){return r.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Wn(r){return Math.max(1,Math.ceil(r.length/4))}function Ut(r=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return ki(e);let t=process.env.LMCTL_DB;return t!==void 0&&t.trim().length>0?dd(Mi(ki(t)),".lmctl-claude-mock","sessions.json"):dd(ki(r),".lmctl-claude-mock","sessions.json")}function ud(){return{schemaVersion:1,sessions:{}}}function yr(r){if(!$_(r))return ud();try{let e=JSON.parse(j_(r,"utf8")),t=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=Ci(e.defaultDelayMs);return{schemaVersion:1,sessions:t,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return ud()}}function yd(r,e){Li(Mi(r),{recursive:!0});let t=`${r}.${process.pid}.${Date.now()}.tmp`;H_(t,`${JSON.stringify(e,null,2)}
|
|
1995
|
+
`,"utf8"),B_(t,r)}var J_=5e3,V_=15,md=1e4;function K_(r){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,r)}function Y_(r){let e=`${r}.lock`;Li(Mi(r),{recursive:!0});let t=Date.now()+md;for(;;)try{return Li(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-W_(e).mtimeMs>J_){try{_d(e)}catch{}continue}}catch{continue}if(Date.now()>=t)throw new Error(`ClaudeMock store lock timeout after ${md}ms: ${e}`);K_(V_)}}function z_(r){try{_d(r)}catch{}}function Td(r,e){let t=Y_(r);try{return e()}finally{z_(t)}}function Q_(r){return{...r,timestamp:r.timestamp.toISOString()}}function Z_(r){return{...r,timestamp:new Date(r.timestamp)}}function eE(r){return{...r,createdAt:r.createdAt.toISOString(),modifiedAt:r.modifiedAt.toISOString(),messages:r.messages.map(Q_)}}function Sd(r){return{...r,createdAt:new Date(r.createdAt),modifiedAt:new Date(r.modifiedAt),messages:r.messages.map(Z_)}}function Hn(r,e=process.cwd()){let t=Pt.get(r);if(t!==void 0)return t;let s=yr(Ut(e)).sessions[r];if(s===void 0)return;let i=Sd(s);return Pt.set(i.sessionId,i),i}function fd(r){Pt.set(r.sessionId,r);let e=Ut(r.cwd);Td(e,()=>{let t=yr(e);t.sessions[r.sessionId]=eE({...r,filePath:e}),yd(e,t)})}function tE(r,e=process.cwd()){let t=Ut(e);return Td(t,()=>{let n=yr(t),s=n.sessions[r]!==void 0;return s&&(delete n.sessions[r],yd(t,n)),s})}function rE(){let r=yr(Ut()),e=Object.values(r.sessions).map(Sd);for(let t of e)Pt.set(t.sessionId,t);return e}function Ci(r){return typeof r=="number"&&Number.isFinite(r)&&r>=0?r:void 0}function pd(r){if(typeof r=="string")return{kind:"success",text:r};if(r!==void 0&&typeof r.text=="string"&&typeof r.error!="string"){let e=Ci(r.delayMs);return{kind:"success",text:r.text,...e!==void 0?{delayMs:e}:{}}}if(r!==void 0&&typeof r.error=="string"&&typeof r.text!="string"){let e=Ci(r.delayMs);return{kind:"error",error:r.error,...e!==void 0?{delayMs:e}:{}}}}async function hd(r){r!==void 0&&r>0&&await new Promise(e=>setTimeout(e,r))}function nE(r,e){let{script:t,scriptContains:n}=e;if(t!==void 0){let s=pd(t[r]??t[Ed(r)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(r.includes(s)){let i=pd(n[s]);if(i!==void 0)return i}}}function gd(r){return{provider:"ClaudeMock",sessionId:r.sessionId,cwd:r.cwd,createdAt:r.createdAt,modifiedAt:r.modifiedAt,messageCount:r.messages.length,filePath:r.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:r.totalInputTokens,totalOutputTokens:r.totalOutputTokens,lastTokenUsage:{totalTokens:r.totalInputTokens+r.totalOutputTokens}}}var Oi=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let t of rE())e.set(t.sessionId,t);for(let t of Pt.values())e.set(t.sessionId,t);return[...e.values()].map(gd)}async loadSession(e){let t=Hn(e);return t===void 0?null:{...gd(t),messages:t.messages.slice()}}async resolveSessionPath(e){return Hn(e)?.filePath??null}async deleteSession(e){let t=Pt.delete(e),n=tE(e);return t||n}},Di=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Oi;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,t){let n=q_(G_(e,t)),s=`mock-${n}-${X_(`${e}:${n}`)}`,i=new Date,o=Ut(e),a=Hn(s,e),l=t?.prompt??"ClaudeMock seed",c=Wn(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+=Wn("ACK: ClaudeMock seeded"),fd(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,t){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,t){let n=Date.now(),s=Hn(t.sessionId,t.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${t.sessionId}`);let i=new Date,o=yr(Ut(t.cwd)),a=nE(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await hd(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Ed(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:t.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=Wn(e),s.totalOutputTokens+=Wn(c),fd(s),t.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await hd(l),{text:c,sessionId:t.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}};function Fi(){return new Di}function gt(r){let e=[qs({claudeDir:r?.claudeDir}),Vs({codexDir:r?.codexDir,codeDir:r?.codeDir}),Qs({geminiDir:r?.geminiDir,claudeDir:r?.claudeDir,codexDir:r?.codexDir,codeDir:r?.codeDir}),ti({copilotDir:r?.copilotDir}),ni(),ai({kimiHome:r?.kimiHome}),ci({lmplayerDbPath:r?.lmplayerDbPath}),ui(),pi({agyDir:r?.agyDir}),Si({dshHome:r?.dshHome}),xi({hermesHome:r?.hermesHome}),Ni({piDir:r?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Fi()),e}var Pi=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],Ui=["agy","pi","lmplayer"];var $i=null;function Xn(){return $i===null&&($i=ut(gt())),$i}function ji(r,e){let t=r.getAdapter(e);if(!t)throw new Error(`provider "${e}" is not registered in this registry`);return t}async function qn(r){let e=r.registry??Xn(),t=ji(e,r.provider),n={sessionId:r.sessionId,cwd:r.cwd,env:r.env,onDelta:r.onDelta,onProgress:r.onProgress,signal:r.signal,timeoutMs:r.timeoutMs,model:r.model,effort:r.effort,progPath:r.progPath,alias:r.alias,isLead:r.isLead,permissionMode:r.permissionMode,holdOpen:r.holdOpen,requireResume:r.requireResume,bundleSession:r.bundleSession},s=await t.sendTurn(r.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs,...s.warnings!==void 0?{warnings:s.warnings}:{}}}function Bi(r){return(r??Xn()).getAllAdapters().filter(t=>t.openSession!==void 0).map(t=>t.name)}async function wd(r){let e=r.registry??Xn(),t=ji(e,r.provider);if(t.openSession===void 0)throw new Error(`provider "${r.provider}" does not support bundle sessions in this version (supported: ${Bi(e).join(", ")})`);return t.openSession(r)}async function Id(r){let e=r.registry??Xn(),t=ji(e,r.provider),n=await vd(e,r.provider,r.cwd),s=await t.seed(r.cwd,{model:r.model,effort:r.effort,prompt:r.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await vd(e,r.provider,r.cwd),a=sE(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function vd(r,e,t){let n=await r.listAll({provider:e,workspace:t}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function sE(r,e){let t=[];for(let n of e.keys())r.has(n)||t.push(n);return t.length===1?t[0]:void 0}var iE={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:[]};var rb=new Set(Object.keys(iE));var Wi=null;function xd(){return Wi===null&&(Wi=ut(gt())),Wi}function Ad(r,e){return xd().getSession(r,e)}async function bd(r){return(await xd().resolveSessions(r)).map(t=>t.provider.name)}var Rd=36e5;function oE(r=process.env){let e=r.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return Rd;let t=Number(e);return!Number.isFinite(t)||t<=0?Rd:t}async function aE(r,e,t){try{let n=it(e,t,r),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let c=await bd(s);if(c.length!==1)return null;i=c[0]}let o=await Ad(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 Nd(r,e,t,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??oE(),o=await aE(r,t,n),a=o!==null&&o>=i;return a&&b({event:"session_idle_reclaim",receiver_teamfile:t,receiver_alias:n,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 kd=ro(bs(),1);function lE(r){return r===null?null:Ee(r)?"live":"dead"}function Hi(r){let e=r.nowMs??Date.now(),t=Date.parse(r.since);return{holder_pid:r.holderPid,holder_liveness:lE(r.holderPid),since:r.since,idle_ms:Number.isFinite(t)?Math.max(0,e-t):null}}function cE(r){return(0,kd.formatDuration)(r)}function Xi(r){let e=[];return r.idle_ms!==null&&e.push(`active ${cE(r.idle_ms)}`),e.push(`since ${r.since}`),e.push(r.holder_pid===null?"holder_pid=unavailable":`holder_pid=${r.holder_pid}, ${r.holder_liveness}`),`(${e.join("; ")})`}import{hostname as dE,networkInterfaces as ub}from"node:os";var uE=12e4;function mE(r=process.env){return fE(r.LMCTL_TERMINAL_LOCK_STALE_MS,uE)}function qi(r,e={}){let t=e.now??new Date,n=e.localHost??dE(),s=e.staleMs??mE();if(r.holder_host===n)return(e.isProcessAlive??pE)(r.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(r.last_heartbeat);return Number.isFinite(i)?t.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function Tr(r){return`${r.alias} is held by a terminal on ${r.holder_host} since ${r.started_at}; retry later`}function fE(r,e){if(r===void 0||r.trim()==="")return e;let t=r.trim(),n=Number.parseInt(t,10);return!Number.isFinite(n)||n<=0||String(n)!==t?e:n}function pE(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function Gn(r){return`lmctl ${r}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
1996
1996
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
1997
1997
|
Consulted ${Va(Pe())}
|
|
1998
|
-
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Jn(r,e){let t=hE(r,e);return t.ok?{ok:!0,identity:t.identity,source:"session"}:t}function hE(r,e){let t=r[ks];if(t===void 0||t.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=St(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===t&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];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]}}function Vn(r){let e=cs(r);if(e===null)throw new Error(`invalid agent identity: ${r}`);return{teamfile:e.teamfile,alias:e.alias,value:r}}var xb=60*60*1e3,gE=2e3,_E=5e3;function Gi(r,e,t){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>r.dal!==void 0?r.dal:(s===null&&(s=
|
|
1999
|
-
`)}function yE(r){return`${r.teamfile}:${r.alias}`}var Cd=256*1024,Md=3e4;async function Vi(r){let e=r.onEvent??(()=>{}),t=TE(r.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,u=null,d=r.prompt;try{let
|
|
2000
|
-
`});let E=r.env??process.env,y=await U(t,C=>C.getRootTeam(T)?.name??null);y!==null&&(E.LMBEE_TEAM_NAME=y),i=await IE(t,{receiverTeamfile:m,receiverAlias:p.alias,sender:g,rootTeamfile:T,provider:p.provider,model:p.model,sessionId:p.sessionid,cwd:p.sessiondir,prompt:r.prompt,origin:h.origin,parentInvocationId:en(E.LMCTL_INVOCATION_ID)}),o=RE(t,i),i!==null&&(E.LMCTL_INVOCATION_ID=String(i));try{Oo(t,Gt(m),m)}catch{}n={root_teamfile:T,sender_teamfile:g?.teamfile??null,sender_alias:g?.alias??null,receiver_teamfile:m,receiver_alias:p.alias,receiver_provider:p.provider,receiver_session_id:p.sessionid,origin:h.origin,message_type:r.messageType??null,policy:f};let I=await Pd(t,m,p.alias);if(I!==null){let C=Tr(I);return gt(i,n,r.prompt,C,"unavailable"),u=Ji(C,null),{status:"busy",message:C,teamChatLogId:null}}let w=!1;if(r.heldLease!==void 0){let C=r.heldLease;if(!await U(t,V=>{let ee=V.getAgentInflight(m,p.alias);return ee===null||ee.sender_teamfile!==C.row.sender_teamfile||ee.sender_alias!==C.row.sender_alias||ee.started_at!==C.row.started_at||ee.holder_pid!==process.pid?!1:V.heartbeatAgentInflight(C.row,C.leaseId,new Date().toISOString())})){let V=`bundle lease lost for ${p.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return gt(i,n,r.prompt,V,"unavailable"),u=Sr(V,null),{status:"error",errorKind:"provider",message:V,teamChatLogId:null,messageId:null}}}else{let C=await SE(t,m,p.alias);if(C.busy){let B=await vE(t,m,p.alias);return B+=await wE(t,m,p.alias),gt(i,n,r.prompt,B,"unavailable"),u=Ji(B,null),{status:"busy",message:B,teamChatLogId:null}}w=C.idleReclaim}if(g!==null&&g.teamfile!==m){let C=await U(t,B=>Yo(B,{root:T,sender:g,receiverTeamfile:m,receiverAlias:p.alias,now:new Date}));if(C.stop){let B=Qo(C.chain);return gt(i,n,r.prompt,B,"cycle"),u=Sr(B,null),{status:"error",errorKind:"cycle",message:B,teamChatLogId:null,messageId:null}}}if(r.heldLease===void 0){let C=await FE(t,{receiver_teamfile:m,receiver_alias:p.alias,sender_teamfile:g?.teamfile??m,sender_alias:g?.alias??"operator",...w?{force:!0,reclaimReason:"session-idle"}:{}});if(!C.acquired){let B=Ud(m,p.alias,C.current);return B+=` ${Xi(Hi({holderPid:C.current.holder_pid,since:C.current.started_at}))}`,gt(i,n,r.prompt,B,"unavailable"),u=Ji(B,null),{status:"busy",message:B,teamChatLogId:null}}s={row:C.lease,leaseId:C.leaseId},a=Xr(B=>U(t,V=>V.heartbeatAgentInflight(s.row,s.leaseId,B)),{intervalMs:Md,onError:B=>{z()&&ge(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:B instanceof Error?B.message:String(B)}))}})}let _=await Ld({sender:g??{teamfile:m,alias:"operator"},receiver:{teamfile:m,alias:p.alias,provider:p.provider,sessionId:p.sessionid,cwd:p.sessiondir,...p.model!==void 0?{model:p.model}:{},...p.effort!==void 0?{effort:p.effort}:{},...p.isLead!==void 0?{isLead:p.isLead}:{}},newMessage:r.prompt,newMessageFrom:g===null?"operator":`${g.teamfile}:${g.alias}`,io:t,permissionMode:r.permissionMode,...r.expectedSession!==void 0?{requireResume:!0}:{},...r.bundleSession!==void 0?{bundleSession:r.bundleSession}:{},env:r.env??process.env,...r.idleTimeoutMs!==void 0?{idleTimeoutMs:r.idleTimeoutMs}:{},onDelta:C=>e({kind:"delta",chunk:C}),onProgress:C=>e({kind:"progress",alias:p.alias,event:C}),onPromptBuilt:async C=>{d=C,l===null&&(l=await UE(t,{...n,message:C}),l!==null&&(r.onAccepted?.(Fe(l)),i!==null&&await bE(t,i,l))),i!==null&&await AE(t,i,C)}});d=_.prompt;let v=_.status==="stalled",S=_.status==="empty",x=null,A=v?`provider stalled${_.stalledAfterMs!==void 0?` after ${_.stalledAfterMs}ms`:""}`:S?"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":_.status==="error"?_.error??_.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=v||S||_.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await Dd(t,l,{...n,message:d,response:_.receipt,status:R,error_detail:A}),c=!0,x=l):x=await jE(t,{...n,message:d,response:_.receipt,status:R,error_detail:A});let $=_.status!=="error"?_.warnings:void 0;if(v||S){let C=A;gt(i,n,d,C,"error"),u=Sr(C,x,_.receipt,$)}else u=NE(_.receipt,x,$);return{status:v?"stalled":S?"empty":"ok",replyText:_.receipt,wroteDelta:_.wroteDelta,teamChatLogId:x,messageId:x===null?null:Fe(x),durationMs:_.durationMs}}catch(p){let m=p instanceof Error?p.message:String(p);return l!==null&&!c&&n!==null&&(await Dd(t,l,{...n,message:d,response:null,status:"error",error_detail:m}),c=!0),gt(i,n,d,m,"error"),u=Sr(m,l),{status:"error",errorKind:p instanceof Te?"target":"provider",message:m,teamChatLogId:l,messageId:l===null?null:Fe(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await $E(t,n,Fe(l)),s!==null&&await PE(t,s.row,s.leaseId),i!==null&&await xE(t,i,u??Sr("chat turn exited without a terminal outcome",null))}}function TE(r,e){return{...r,stdout:{write:()=>{}},stderr:{write:t=>{e({kind:"warning",message:t})}}}}async function SE(r,e,t){let n=await U(r,i=>(tn(i,e,t),Gr(i,e,t)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await U(r,i=>Nd(i,n,e,t));return{busy:!s,idleReclaim:s}}async function vE(r,e,t){let n=await Pd(r,e,t);if(n!==null)return Tr(n);let s=await U(r,i=>i.getAgentInflight(e,t));return s!==null?Ud(e,t,s):`${t} is busy; wait and retry`}async function wE(r,e,t){let n=await U(r,s=>s.getAgentInflight(e,t));return n===null?"":` ${Xi(Hi({holderPid:n.holder_pid,since:n.started_at}))}`}async function IE(r,e){try{return(await U(r,n=>n.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:kE(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(t){return z()&&ge(JSON.stringify({event:"tracked_invocation_start_error",error:t instanceof Error?t.message:String(t)})),null}}async function xE(r,e,t){try{await U(r,n=>{n.finishTrackedInvocation(e,t)})}catch(n){z()&&ge(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function AE(r,e,t){try{await U(r,n=>{n.updateTrackedInvocationRequestPayload(e,t)})}catch(n){z()&&ge(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function bE(r,e,t){try{await U(r,n=>{n.linkTrackedInvocationMessage(e,t)})}catch(n){z()&&ge(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:t,error:n instanceof Error?n.message:String(n)}))}}function RE(r,e){if(e===null)return;let t=setInterval(()=>{U(r,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{z()&&ge(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Md);return t.unref?.(),t}function Fd(r){return r!==void 0&&r.length>0?{config_warnings:JSON.stringify(r)}:{}}function NE(r,e,t){return{status:"done",result_summary:vr(r),error:null,team_chat_log_id:e,...Fd(t)}}function Ji(r,e){return{status:"busy",result_summary:vr(r),error:r,team_chat_log_id:e}}function Sr(r,e,t,n){return{status:"error",result_summary:vr(t===void 0?r:t),error:r,team_chat_log_id:e,...Fd(n)}}function vr(r){let e=r.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function kE(r,e,t){return`lmctl prompt ${JSON.stringify(r)} ${e} ${JSON.stringify(t)}`}function LE(r,e){let t=Jn(e,r);if(t.ok)return{sender:Vn(t.identity),origin:"agent"};if(t.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Gn("chat"))}async function CE(r,e){if(e.explicitRoot!==void 0)return await U(r,n=>nt(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let t=e.sender;return await U(r,n=>zo(n,{sender:t,now:new Date})??e.receiverTeamfile)}async function OE(r,e){return await U(r,t=>Jo({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:DE(t,e.sender.teamfile,e.receiverTeamfile)}))}function DE(r,e,t){return{teams:[e,t].map(s=>ME(s,r))}}function ME(r,e){let t=St(r,e),n=Jt(t);return{teamfile:r,aliases:t.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function FE(r,e){return await U(r,t=>{let n=z(),s=qr(t,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:It(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&ge(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:Od(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&ge(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:Od(s.current)})),{acquired:!1,current:s.current})})}async function Pd(r,e,t){return await U(r,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,t);if(o===null)return null;if(qi(o).live)return o;let l=n.getAgentInflight(e,t);if(n.clearTerminalLock(e,t,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&n.clearObservedTerminalAgentInflight(e,t,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=n.getTerminalLock(e,t);return s===null?null:qi(s).live?s:null})}function Od(r){return r===null?null:{sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,holder_pid:r.holder_pid,started_at:r.started_at}}async function PE(r,e,t){try{await U(r,n=>{n.releaseAgentInflight(e,t)})}catch(n){r.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
2001
|
-
`)}}function Ud(r,e,t){return`${e} is servicing ${t.sender_alias} (${t.sender_teamfile}) since ${t.started_at} \u2014 wait and retry, or inspect without waking it: lmctl tail "${r}" ${e}`}async function UE(r,e){let t=wr(e.message);try{return await
|
|
2002
|
-
`),null}}async function Dd(r,e,t){let n=wr(t.message),s=t.response===null?null:wr(t.response);try{await
|
|
2003
|
-
`)}}async function $E(r,e,t){if(e!==null)try{await
|
|
2004
|
-
`)}}async function jE(r,e){let t=wr(e.message),n=e.response===null?null:wr(e.response);try{return await
|
|
2005
|
-
`),null}}function
|
|
2006
|
-
`)}}function ty(r,e){let t=Jn(r,e);if(t.ok)return Vn(t.identity);if(t.reason==="unset")return null;throw new Error(Gn("batch"))}async function ry(r,e){try{let{member:t}=e;return await
|
|
2007
|
-
`),null}}function ny(r,e,t,n){try{if(r.dal!==void 0){r.dal.finishTrackedInvocation(e,t);return}let s=
|
|
2008
|
-
`)}}t==="done"&&e.stderr.write(`batch ${
|
|
2009
|
-
`)}}var Zi=[{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",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:"map",description:"Batch handle object or null on error"},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:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'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 session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{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 the reply.",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_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:"string[]",description:"List of prompt strings"},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:"string[]",description:"List of paragraph strings"},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:"List of member records { 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|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"args",type:"any[]",description:"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(...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"args",type:"any[]",description:"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);"}].map(r=>({...r,module:"lmctl"}));function sy(r){for(let e of Zi)r.registerFunctionDoc(e)}function Xd(r={}){let e=new Me;e.isAsyncMode=!0;let t=r.scriptArgs??[];if(e.setGlobal("args",[...t]),e.setGlobal("ARGV",[...t]),r.io){let n=r.io;e.registerFunction("print",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
1998
|
+
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Jn(r,e){let t=hE(r,e);return t.ok?{ok:!0,identity:t.identity,source:"session"}:t}function hE(r,e){let t=r[ks];if(t===void 0||t.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=St(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===t&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];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]}}function Vn(r){let e=cs(r);if(e===null)throw new Error(`invalid agent identity: ${r}`);return{teamfile:e.teamfile,alias:e.alias,value:r}}var xb=60*60*1e3,gE=2e3,_E=5e3;function Gi(r,e,t){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>r.dal!==void 0?r.dal:(s===null&&(s=ct({path:Pe()})),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&&Ee(a.holder_pid)),pollMs:gE,settleMs:_E,maxHoldMs:At(t),onHold:()=>b({event:"delivery_hold_open_started",receiver:n}),onRelease:a=>{o(),!(!a.held&&a.reason==="cleared")&&b({event:"delivery_hold_open_released",receiver:n,elapsed_ms:a.elapsedMs,held:a.held,reason:a.reason})}}}async function Ld(r){let e=EE(r.newMessage,{newMessageFrom:r.newMessageFrom??yE(r.sender)});if(e.length===0)throw new Error(`no message to deliver for ${r.sender.teamfile}:${r.sender.alias} -> ${r.receiver.teamfile}:${r.receiver.alias}`);let t=!1,n=z(),s=0,i=0,o=0,a={provider:r.receiver.provider,sessionId:r.receiver.sessionId,cwd:r.receiver.cwd,prompt:e,permissionMode:r.permissionMode,env:r.env,onDelta:c=>{t=!0,n&&(s+=1,o=Buffer.byteLength(c,"utf8"),i+=o),r.onDelta?.(c)},onProgress:c=>r.onProgress?.(c)};r.receiver.model!==void 0&&(a.model=r.receiver.model),r.receiver.effort!==void 0&&(a.effort=r.receiver.effort),a.alias=r.receiver.alias,a.isLead=r.receiver.isLead,r.idleTimeoutMs!==void 0&&(a.timeoutMs=r.idleTimeoutMs),r.requireResume!==void 0&&(a.requireResume=r.requireResume),r.bundleSession!==void 0&&(a.bundleSession=r.bundleSession),a.holdOpen=Gi(r.io,r.receiver,r.env),await r.onPromptBuilt?.(e);let l=await qn(a);if(r.requireResume&&l.sessionId!==r.receiver.sessionId)throw new Error(`provider session changed: expected ${r.receiver.sessionId}, received ${l.sessionId??"(missing)"}`);return n&&_e(JSON.stringify({event:"chat_return",alias:r.receiver.alias,provider:r.receiver.provider,streamed:t,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,prompt:e,wroteDelta:t,durationMs:l.durationMs,stalledAfterMs:l.stalledAfterMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:l.status==="empty"?{status:"empty",receipt:l.text,prompt:e,wroteDelta:t,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:{status:"ok",receipt:l.text,prompt:e,wroteDelta:t,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}}function EE(r,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,r].join(`
|
|
1999
|
+
`)}function yE(r){return`${r.teamfile}:${r.alias}`}var Cd=256*1024,Md=3e4;async function Vi(r){let e=r.onEvent??(()=>{}),t=TE(r.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,u=null,d=r.prompt;try{let m=await $(t,k=>it(r.teamfile,r.alias,k));if(r.expectedSession!==void 0&&(m.provider!==r.expectedSession.provider||m.sessionid!==r.expectedSession.sessionid))throw new Se(`session changed for ${m.alias}; expected ${r.expectedSession.provider}:${r.expectedSession.sessionid}, found ${m.provider}:${m.sessionid}`);let h=m.teamfile,f=await $(t,k=>LE(k,r.env??process.env)),T=f.sender,_=await CE(t,{explicitRoot:r.rootFlag,sender:T,receiverTeamfile:h,operatorOrigin:f.origin==="operator"}),p=T===null?null:await OE(t,{rootTeamfile:_,sender:T,receiverTeamfile:h,receiverAlias:m.alias});p!==null&&!p.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${p.reason}
|
|
2000
|
+
`});let g=r.env??process.env,E=await $(t,k=>k.getRootTeam(_)?.name??null);E!==null&&(g.LMBEE_TEAM_NAME=E),i=await IE(t,{receiverTeamfile:h,receiverAlias:m.alias,sender:T,rootTeamfile:_,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:r.prompt,origin:f.origin,parentInvocationId:en(g.LMCTL_INVOCATION_ID)}),o=RE(t,i),i!==null&&(g.LMCTL_INVOCATION_ID=String(i));try{Oo(t,Gt(h),h)}catch{}n={root_teamfile:_,sender_teamfile:T?.teamfile??null,sender_alias:T?.alias??null,receiver_teamfile:h,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:f.origin,message_type:r.messageType??null,policy:p};let w=await Pd(t,h,m.alias);if(w!==null){let k=Tr(w);return _t(i,n,r.prompt,k,"unavailable"),u=Ji(k,null),{status:"busy",message:k,teamChatLogId:null}}let I=!1;if(r.heldLease!==void 0){let k=r.heldLease;if(!await $(t,ee=>{let G=ee.getAgentInflight(h,m.alias);return G===null||G.sender_teamfile!==k.row.sender_teamfile||G.sender_alias!==k.row.sender_alias||G.started_at!==k.row.started_at||G.holder_pid!==process.pid?!1:ee.heartbeatAgentInflight(k.row,k.leaseId,new Date().toISOString())})){let ee=`bundle lease lost for ${m.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return _t(i,n,r.prompt,ee,"unavailable"),u=Sr(ee,null),{status:"error",errorKind:"provider",message:ee,teamChatLogId:null,messageId:null}}}else{let k=await SE(t,h,m.alias);if(k.busy){let j=await vE(t,h,m.alias);return j+=await wE(t,h,m.alias),_t(i,n,r.prompt,j,"unavailable"),u=Ji(j,null),{status:"busy",message:j,teamChatLogId:null}}I=k.idleReclaim}if(T!==null&&T.teamfile!==h){let k=await $(t,j=>Yo(j,{root:_,sender:T,receiverTeamfile:h,receiverAlias:m.alias,now:new Date}));if(k.stop){let j=Qo(k.chain);return _t(i,n,r.prompt,j,"cycle"),u=Sr(j,null),{status:"error",errorKind:"cycle",message:j,teamChatLogId:null,messageId:null}}}if(r.heldLease===void 0){let k=await FE(t,{receiver_teamfile:h,receiver_alias:m.alias,sender_teamfile:T?.teamfile??h,sender_alias:T?.alias??"operator",...I?{force:!0,reclaimReason:"session-idle"}:{}});if(!k.acquired){let j=Ud(h,m.alias,k.current);return j+=` ${Xi(Hi({holderPid:k.current.holder_pid,since:k.current.started_at}))}`,_t(i,n,r.prompt,j,"unavailable"),u=Ji(j,null),{status:"busy",message:j,teamChatLogId:null}}s={row:k.lease,leaseId:k.leaseId},a=Xr(j=>$(t,ee=>ee.heartbeatAgentInflight(s.row,s.leaseId,j)),{intervalMs:Md,onError:j=>{z()&&_e(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:j instanceof Error?j.message:String(j)}))}})}let y=await Ld({sender:T??{teamfile:h,alias:"operator"},receiver:{teamfile:h,alias:m.alias,provider:m.provider,sessionId:m.sessionid,cwd:m.sessiondir,...m.model!==void 0?{model:m.model}:{},...m.effort!==void 0?{effort:m.effort}:{},...m.isLead!==void 0?{isLead:m.isLead}:{}},newMessage:r.prompt,newMessageFrom:T===null?"operator":`${T.teamfile}:${T.alias}`,io:t,permissionMode:r.permissionMode,...r.expectedSession!==void 0?{requireResume:!0}:{},...r.bundleSession!==void 0?{bundleSession:r.bundleSession}:{},env:r.env??process.env,...r.idleTimeoutMs!==void 0?{idleTimeoutMs:r.idleTimeoutMs}:{},onDelta:k=>e({kind:"delta",chunk:k}),onProgress:k=>e({kind:"progress",alias:m.alias,event:k}),onPromptBuilt:async k=>{d=k,l===null&&(l=await UE(t,{...n,message:k}),l!==null&&(r.onAccepted?.(Fe(l)),i!==null&&await bE(t,i,l))),i!==null&&await AE(t,i,k)}});d=y.prompt;let v=y.status==="stalled",S=y.status==="empty",x=null,A=v?`provider stalled${y.stalledAfterMs!==void 0?` after ${y.stalledAfterMs}ms`:""}`:S?"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":y.status==="error"?y.error??y.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,N=v||S||y.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await Dd(t,l,{...n,message:d,response:y.receipt,status:N,error_detail:A}),c=!0,x=l):x=await jE(t,{...n,message:d,response:y.receipt,status:N,error_detail:A});let P=y.status!=="error"?y.warnings:void 0;if(v||S){let k=A;_t(i,n,d,k,"error"),u=Sr(k,x,y.receipt,P)}else u=NE(y.receipt,x,P);return{status:v?"stalled":S?"empty":"ok",replyText:y.receipt,wroteDelta:y.wroteDelta,teamChatLogId:x,messageId:x===null?null:Fe(x),durationMs:y.durationMs}}catch(m){let h=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await Dd(t,l,{...n,message:d,response:null,status:"error",error_detail:h}),c=!0),_t(i,n,d,h,"error"),u=Sr(h,l),{status:"error",errorKind:m instanceof Se?"target":"provider",message:h,teamChatLogId:l,messageId:l===null?null:Fe(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await $E(t,n,Fe(l)),s!==null&&await PE(t,s.row,s.leaseId),i!==null&&await xE(t,i,u??Sr("chat turn exited without a terminal outcome",null))}}function TE(r,e){return{...r,stdout:{write:()=>{}},stderr:{write:t=>{e({kind:"warning",message:t})}}}}async function SE(r,e,t){let n=await $(r,i=>(tn(i,e,t),Gr(i,e,t)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await $(r,i=>Nd(i,n,e,t));return{busy:!s,idleReclaim:s}}async function vE(r,e,t){let n=await Pd(r,e,t);if(n!==null)return Tr(n);let s=await $(r,i=>i.getAgentInflight(e,t));return s!==null?Ud(e,t,s):`${t} is busy; wait and retry`}async function wE(r,e,t){let n=await $(r,s=>s.getAgentInflight(e,t));return n===null?"":` ${Xi(Hi({holderPid:n.holder_pid,since:n.started_at}))}`}async function IE(r,e){try{return(await $(r,n=>n.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:kE(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(t){return z()&&_e(JSON.stringify({event:"tracked_invocation_start_error",error:t instanceof Error?t.message:String(t)})),null}}async function xE(r,e,t){try{await $(r,n=>{n.finishTrackedInvocation(e,t)})}catch(n){z()&&_e(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function AE(r,e,t){try{await $(r,n=>{n.updateTrackedInvocationRequestPayload(e,t)})}catch(n){z()&&_e(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function bE(r,e,t){try{await $(r,n=>{n.linkTrackedInvocationMessage(e,t)})}catch(n){z()&&_e(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:t,error:n instanceof Error?n.message:String(n)}))}}function RE(r,e){if(e===null)return;let t=setInterval(()=>{$(r,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{z()&&_e(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Md);return t.unref?.(),t}function Fd(r){return r!==void 0&&r.length>0?{config_warnings:JSON.stringify(r)}:{}}function NE(r,e,t){return{status:"done",result_summary:vr(r),error:null,team_chat_log_id:e,...Fd(t)}}function Ji(r,e){return{status:"busy",result_summary:vr(r),error:r,team_chat_log_id:e}}function Sr(r,e,t,n){return{status:"error",result_summary:vr(t===void 0?r:t),error:r,team_chat_log_id:e,...Fd(n)}}function vr(r){let e=r.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function kE(r,e,t){return`lmctl prompt ${JSON.stringify(r)} ${e} ${JSON.stringify(t)}`}function LE(r,e){let t=Jn(e,r);if(t.ok)return{sender:Vn(t.identity),origin:"agent"};if(t.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Gn("chat"))}async function CE(r,e){if(e.explicitRoot!==void 0)return await $(r,n=>st(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let t=e.sender;return await $(r,n=>zo(n,{sender:t,now:new Date})??e.receiverTeamfile)}async function OE(r,e){return await $(r,t=>Jo({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:DE(t,e.sender.teamfile,e.receiverTeamfile)}))}function DE(r,e,t){return{teams:[e,t].map(s=>ME(s,r))}}function ME(r,e){let t=St(r,e),n=Jt(t);return{teamfile:r,aliases:t.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function FE(r,e){return await $(r,t=>{let n=z(),s=qr(t,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:It(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&_e(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:Od(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&_e(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:Od(s.current)})),{acquired:!1,current:s.current})})}async function Pd(r,e,t){return await $(r,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,t);if(o===null)return null;if(qi(o).live)return o;let l=n.getAgentInflight(e,t);if(n.clearTerminalLock(e,t,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&n.clearObservedTerminalAgentInflight(e,t,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=n.getTerminalLock(e,t);return s===null?null:qi(s).live?s:null})}function Od(r){return r===null?null:{sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,holder_pid:r.holder_pid,started_at:r.started_at}}async function PE(r,e,t){try{await $(r,n=>{n.releaseAgentInflight(e,t)})}catch(n){r.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
2001
|
+
`)}}function Ud(r,e,t){return`${e} is servicing ${t.sender_alias} (${t.sender_teamfile}) since ${t.started_at} \u2014 wait and retry, or inspect without waking it: lmctl tail "${r}" ${e}`}async function UE(r,e){let t=wr(e.message);try{return await $(r,n=>n.beginTeamChatLog({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:t.text,response:null,origin:e.origin,status:"running",error_detail:null,truncated:t.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(n){return r.stderr.write(`warning: failed to begin chat log: ${n instanceof Error?n.message:String(n)}
|
|
2002
|
+
`),null}}async function Dd(r,e,t){let n=wr(t.message),s=t.response===null?null:wr(t.response);try{await $(r,i=>i.finishTeamChatLog(e,{root_teamfile:t.root_teamfile,sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,receiver_teamfile:t.receiver_teamfile,receiver_alias:t.receiver_alias,receiver_provider:t.receiver_provider,receiver_session_id:t.receiver_session_id,provider_prompt:t.message,message:n.text,response:s?.text??null,origin:t.origin,status:t.status,error_detail:t.error_detail,truncated:n.truncated||s?.truncated?1:0,created_at:new Date().toISOString()}))}catch(i){r.stderr.write(`warning: failed to finish chat log ${e}: ${i instanceof Error?i.message:String(i)}
|
|
2003
|
+
`)}}async function $E(r,e,t){if(e!==null)try{await $(r,n=>{n.clearCurrentlyHandlingMessage(e.receiver_teamfile,e.receiver_alias,t)})}catch(n){r.stderr.write(`warning: failed to clear chat causal pointer: ${n instanceof Error?n.message:String(n)}
|
|
2004
|
+
`)}}async function jE(r,e){let t=wr(e.message),n=e.response===null?null:wr(e.response);try{return await $(r,s=>s.insertTeamChatLog({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:t.text,response:n?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:t.truncated||n?.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(s){return r.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
2005
|
+
`),null}}function _t(r,e,t,n,s){r!==null||e===null||b({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:n,message_preview:vr(t)})}function wr(r){return r.length<=Cd?{text:r,truncated:!1}:{text:r.slice(0,Cd),truncated:!0}}import{spawnSync as BE}from"node:child_process";import{existsSync as WE}from"node:fs";import{homedir as Yi}from"node:os";import{delimiter as HE,join as zi}from"node:path";var $d=["all","codex","agy","claude","kimi"],XE=15,qE=4;function GE(r,e,t){let n=BE(r,e,{encoding:"utf8",timeout:t,maxBuffer:16777216});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",...n.signal!==null?{signal:n.signal}:{},...n.error!==void 0?{error:n.error}:{}}}var JE={exists:WE},VE=GE,Ki=JE;function KE(r){return r==="~"?Yi():r.startsWith("~/")?zi(Yi(),r.slice(2)):r}function YE(r){let e=r.LMCTL_RATELIMIT_BIN;if(e!==void 0&&e!==""){let n=KE(e);if(Ki.exists(n))return n}let t=zi(Yi(),"repos","tools","lmratelimit","bin","lmratelimit");if(Ki.exists(t))return t;for(let n of(r.PATH??"").split(HE)){if(n==="")continue;let s=zi(n,"lmratelimit");if(Ki.exists(s))return s}return null}function jd(r){return typeof r=="object"&&r!==null}function zE(r){let e;try{e=JSON.parse(r)}catch{return null}return jd(e)?Array.isArray(e.readings)?e.readings.filter(jd):typeof e.provider=="string"&&typeof e.status=="string"?[e]:null:null}function Bd(r,e){let t=r.trim();return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Wd(r={}){let e=r.targets??r.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(c=>typeof c!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let c of e)if(!$d.includes(c))return{status:"error",error:`unknown provider: ${c} (valid targets: ${$d.join(", ")})`,readings:[]};let t=r.timeoutSeconds??XE;if(!Number.isFinite(t)||t<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=r.env??process.env,s=YE(n);if(s===null)return{status:"error",error:"lmratelimit binary not found (looked at LMCTL_RATELIMIT_BIN, ~/repos/tools/lmratelimit/bin/lmratelimit, and PATH).",readings:[]};let i=e.includes("all")?qE:e.length,o=Math.ceil(2*t*i*1e3);r.progress?.(`querying ${e.join(" ")} live (timeout ${t}s per provider) ...`);let a=VE(s,[...e,"--pretty","--timeout",String(t)],o);if(a.error!==void 0){let c=a.error.code==="ETIMEDOUT"?`timed out after ${Math.round(o/1e3)}s (--timeout ${t}s x ${i} provider(s))`:a.error.message;return{status:"error",error:`failed to run lmratelimit (${s}): ${c}`,readings:[]}}if(a.status!==0){let c=a.signal!==null&&a.signal!==void 0?`signal ${a.signal}`:`status ${a.status}`,u=Bd(a.stderr,500);return{status:"error",error:`lmratelimit exited with ${c}${u!==""?`: ${u}`:""}`,readings:[]}}let l=zE(a.stdout);return l===null?{status:"error",error:`could not parse lmratelimit output as JSON: ${Bd(a.stdout,300)}`,readings:[]}:{status:"ok",readings:l}}var $t=class{batchHandles=new Map;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}async forceCloseAll(e){for(let t of this.getOpenBatches())await Hd(t,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}};async function ey(r){let e=r.provider.trim().toLowerCase();return Ui.includes(e)||sl().tools[e]?.agent!==void 0||!Pi.includes(e)?!1:Bi().includes(e)}async function Qi(r,e){try{await $(r,t=>{t.releaseAgentInflight(e.row,e.leaseId)})}catch(t){r.stderr.write(`warning: failed to release batch bundle lease: ${t instanceof Error?t.message:String(t)}
|
|
2006
|
+
`)}}function ty(r,e){let t=Jn(r,e);if(t.ok)return Vn(t.identity);if(t.reason==="unset")return null;throw new Error(Gn("batch"))}async function ry(r,e){try{let{member:t}=e;return await $(r,n=>n.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:t.teamfile,from_identity:`${t.teamfile}:batch`,target_teamfile:t.teamfile,target_alias:t.alias,root_teamfile:t.teamfile,cwd:t.sessiondir,command:`lmctl batch ${t.teamfile} ${t.alias} ${e.batchfile}`,holder_pid:process.pid,launch_source:"exec",parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({batchfile:e.batchfile,prompt_count:e.promptCount,provider:t.provider,sessionid:t.sessionid,...t.model!==void 0?{model:t.model}:{}})}).id)}catch(t){return r.stderr.write(`warning: failed to start batch root invocation: ${t instanceof Error?t.message:String(t)}
|
|
2007
|
+
`),null}}function ny(r,e,t,n){try{if(r.dal!==void 0){r.dal.finishTrackedInvocation(e,t);return}let s=ct({path:Pe(n?.LMCTL_DB)});try{s.finishTrackedInvocation(e,t)}finally{s.close()}}catch{}}async function Hd(r,e,t,n){if(!r.closed&&(r.closed=!0,r.kind!=="agent")){if(r.bundleSession)try{await r.bundleSession.close()}catch{}if(r.heartbeatTimer&&r.heartbeatTimer.stop(),r.heldLease&&await Qi(e,r.heldLease),r.rootId!==null){let s=t==="done"?{status:"done",exit_code:0,result_summary:`batch completed ${r.promptCount}/${r.promptCount} prompts`}:{status:r.rootFinish.status??(t==="cancelled"?"cancelled":"error"),exit_code:1,error:n??r.rootFinish.error,result_summary:r.rootFinish.result_summary};try{await $(e,i=>{i.finishTrackedInvocation(r.rootId,s)})}catch(i){e.stderr.write(`warning: failed to finish batch root invocation: ${i instanceof Error?i.message:String(i)}
|
|
2008
|
+
`)}}t==="done"&&e.stderr.write(`batch ${Ve()}: completed ${r.promptCount}/${r.promptCount} prompts
|
|
2009
|
+
`)}}var Zi=[{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",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:"map",description:"Batch handle object or null on error"},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:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'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 session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{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 the reply.",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_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_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:"string[]",description:"List of prompt strings"},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:"string[]",description:"List of paragraph strings"},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:"List of member records { 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|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"args",type:"any[]",description:"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(...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"args",type:"any[]",description:"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);"}].map(r=>({...r,module:"lmctl"}));function sy(r){for(let e of Zi)r.registerFunctionDoc(e)}function Xd(r={}){let e=new Me;e.isAsyncMode=!0;let t=r.scriptArgs??[];if(e.setGlobal("args",[...t]),e.setGlobal("ARGV",[...t]),r.io){let n=r.io;e.registerFunction("print",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
2010
2010
|
`),i},void 0,{description:"Prints formatted values to stdout",allowOverwrite:!0}),e.registerFunction("println",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
2011
2011
|
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=Ht(s,i);return n.stdout.write(o+`
|
|
2012
|
-
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return qt(s,i,o)}return Xt(s)},{min:0,max:1},{description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",allowOverwrite:!0})}return e}function qd(r,e,t,n=process.env){r.registerFunction("lm_exit",(
|
|
2012
|
+
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return qt(s,i,o)}return Xt(s)},{min:0,max:1},{description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",allowOverwrite:!0})}return e}function qd(r,e,t,n=process.env){r.registerFunction("lm_exit",(f=0)=>{let T=Math.floor(Number(f)),_=Number.isFinite(T)&&T>=0&&T<=255?T:1;throw new he(_)},{min:0,max:1},"Exits the LMScript execution with an exit code"),r.registerFunction("lm_log",(...f)=>{let T=f.map(_=>typeof _=="object"?JSON.stringify(_):String(_)).join(" ");return e.stderr.write(T+(T.endsWith(`
|
|
2013
2013
|
`)?"":`
|
|
2014
|
-
`)),
|
|
2015
|
-
`),t.recordError(
|
|
2016
|
-
`);return!!
|
|
2017
|
-
`);try{if(I){let
|
|
2018
|
-
`);try{let
|
|
2019
|
-
`);let I=Zr(e,
|
|
2020
|
-
`);try{let
|
|
2021
|
-
`)}})}catch(
|
|
2022
|
-
`),I=Zr(e,
|
|
2023
|
-
`);let x
|
|
2024
|
-
`);if(!
|
|
2025
|
-
`);return
|
|
2026
|
-
`);let
|
|
2027
|
-
`);else{let
|
|
2014
|
+
`)),T},void 0,"Writes formatted log message to stderr"),r.registerFunction("lm_error",(...f)=>{let T=f.map(_=>typeof _=="object"?JSON.stringify(_):String(_)).join(" ");return e.stderr.write(`error: ${T}
|
|
2015
|
+
`),t.recordError(T),T},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(f,T=!1)=>{try{let _=QE(String(f),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2016
|
+
`);return!!T?[_.trim()].filter(g=>g.length>0):_.split(/\n\s*\n/u).map(g=>g.trim()).filter(Boolean)}catch(_){throw dt(e,`batch: ${_ instanceof Error?_.message:String(_)}`),new he(1)}};r.registerFunction("lm_read_prompts",(f,T=!1)=>s(f,T),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),r.registerFunction("lm_read_paragraphs",f=>s(f,!1),1,"Reads file and splits into blank-line-separated paragraphs"),r.registerFunction("lm_members",f=>{try{return Gt(String(f)).members.map(_=>({alias:_.alias,provider:_.provider,model:_.model,sessionid:_.session,sessiondir:_.sessiondir}))}catch(T){throw new Error(`Failed to read teamfile '${f}': ${T?.message||String(T)}`)}},1,"Resolves all members declared in a teamfile"),r.registerFunction("lm_member",(f,T)=>{try{let _=it(String(f),String(T),e.dal);return{alias:_.alias,provider:_.provider,model:_.model,sessionid:_.sessionid,sessiondir:_.sessiondir,isLead:_.isLead,teamfile:_.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),r.registerFunction("lm_batch_open",async(f,T,_,p={})=>{if(typeof f!="string"){if(!f||Array.isArray(f)||typeof f!="object"||typeof f.provider!="string"||!f.provider.trim())throw new Error("lm_batch_open: member map requires provider");let P=T??{};if(typeof P!="object"||Array.isArray(P)||_!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let k={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...f},sourceMember:f,options:{...P},closed:!1,failed:!1,inFlight:!1};return t.registerBatch(k),k}if(typeof T!="string"||typeof _!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let g;try{g=it(String(f),String(T),e.dal)}catch(P){return dt(e,`batch: ${P?.message||String(P)}`),null}let E=Number(p?.promptCount??1),I=!!!p?.legacy&&E>1&&await ey(g),y={...e.env??n},v=await ry(e,{member:g,batchfile:String(_),promptCount:E,parentInvocationId:en(y.LMCTL_INVOCATION_ID)});v!==null&&(y.LMCTL_INVOCATION_ID=String(v));let S,x,A,N=!1;e.stderr.write(`batch ${Ve()}: starting ${E} prompt${E===1?"":"s"} -> ${g.alias} (teamfile=${f} input=${_})
|
|
2017
|
+
`);try{if(I){let j=await $(e,J=>(tn(J,g.teamfile,g.alias),Gr(J,g.teamfile,g.alias)));if(j.busy){let J=j.reason==="in-flight"?`${g.alias} is servicing ${j.inFlight.sender_alias} (${j.inFlight.sender_teamfile}) since ${j.inFlight.started_at} \u2014 wait and retry`:j.source==="terminal-lock"?Tr(j.terminalLock):`${g.alias} is busy (interactive terminal); wait and retry`;return v!==null&&await $(e,le=>{le.finishTrackedInvocation(v,{status:"busy",exit_code:1,error:J,result_summary:"0 prompts completed"})}),dt(e,`batch: cannot start bundle: ${J}`),null}let ee=await $(e,J=>ty(y,J)),G=await $(e,J=>qr(J,{receiver_teamfile:g.teamfile,receiver_alias:g.alias,sender_teamfile:ee?.teamfile??g.teamfile,sender_alias:ee?.alias??"operator",ttlMs:It(y)}));if(!G.acquired){let J=`${g.alias} is servicing ${G.current.sender_alias} (${G.current.sender_teamfile}) since ${G.current.started_at} \u2014 wait and retry`;return v!==null&&await $(e,le=>{le.finishTrackedInvocation(v,{status:"busy",exit_code:1,error:J,result_summary:"0 prompts completed"})}),dt(e,`batch: cannot start bundle: ${J}`),null}S={row:G.lease,leaseId:G.leaseId};let ae=Xr(J=>$(e,le=>le.heartbeatAgentInflight(S.row,S.leaseId,J)));A={stop:()=>clearInterval(ae)};let pe=Zr(e,J=>`batch ${Ve()}: opening provider session (${J}s elapsed)
|
|
2018
|
+
`);try{let J={...y};try{let le=await $(e,Ue=>Ue.getRootTeam(g.teamfile)?.name??null);le!==null&&(J.LMBEE_TEAM_NAME=le)}catch{}x=await wd({provider:g.provider,sessionId:g.sessionid,cwd:g.sessiondir,env:J,...g.model!==void 0?{model:g.model}:{},...g.effort!==void 0?{effort:g.effort}:{},alias:g.alias,isLead:g.isLead,permissionMode:"yolo",holdOpen:Gi(e,{teamfile:g.teamfile,alias:g.alias},J)}),N=!0}catch{A&&A.stop(),A=void 0,await Qi(e,S),S=void 0,N=!1}finally{pe.stop()}}let k={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(f),alias:String(T),batchfile:String(_),member:g,promptCount:E,useBundle:N,rootId:v,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:S,bundleSession:x,heartbeatTimer:A,closed:!1,env:y};return t.registerBatch(k),k}catch(P){if(A){try{A.stop()}catch{}A=void 0}if(S){try{await Qi(e,S)}catch{}S=void 0}if(x){try{await x.close()}catch{}x=void 0}if(v!==null)try{await $(e,k=>{k.finishTrackedInvocation(v,{status:"error",exit_code:1,error:P?.message||String(P),result_summary:"0 prompts completed"})})}catch{}throw P}},{min:1,max:4},"Opens a batch from a member map or a teamfile with lifecycle management"),r.registerFunction("lm_batch_turn",async(f,T,_,p)=>{let g=typeof f=="string"?t.getBatch(f):f?.id?t.getBatch(f.id)??f:void 0;if(!g)throw new Error("Invalid or unmanaged batch handle");if(g.kind==="agent"){if(t.getBatch(g.id)!==g)throw new Error("Invalid or unmanaged batch handle");if(g.closed||g.failed)return{status:"error",reply:"",error:"Batch is closed or stopped after a failed turn"};if(g.inFlight)return{status:"busy",reply:"",error:"Batch already has an active turn"};g.inFlight=!0;try{let y=g.member.sessionid,v=await u(g.member,String(T),g.options);return g.member.sessionid&&g.sourceMember.provider===g.member.provider&&g.sourceMember.sessionid===y&&(g.sourceMember.sessionid=g.member.sessionid),v.status!=="ok"&&(g.failed=!0),{status:v.status,reply:v.reply.replace(/\n+$/u,""),error:v.error}}finally{g.inFlight=!1}}let E=Number(_),w=Number(p);e.stderr.write(`batch ${Ve()}: prompt ${E}/${w} -> ${g.member.alias}
|
|
2019
|
+
`);let I=Zr(e,y=>`batch ${Ve()}: prompt ${E}/${w} still running (${y}s elapsed)
|
|
2020
|
+
`);try{let y=await Vi({teamfile:g.member.teamfile,alias:g.member.alias,prompt:String(T),expectedSession:{provider:g.member.provider,sessionid:g.member.sessionid},permissionMode:"yolo",env:{...g.env},messageType:"batch",...g.heldLease!==void 0?{heldLease:g.heldLease}:{},...g.bundleSession!==void 0?{bundleSession:g.bundleSession}:{},io:e,onEvent:S=>{I.poke(),S.kind==="warning"&&e.stderr.write(S.message)}}),v=y.replyText?String(y.replyText).replace(/\n+$/u,""):"";if(y.status!=="ok"){let S=y.status==="stalled"?"provider stalled":y.status==="empty"?"provider returned no content and no observed activity for this turn":y.message,x=`batch: stopped at prompt ${E}/${w} (${E-1} completed): ${S}; later prompts were not sent`;return g.rootFinish={status:y.status==="busy"?"busy":"error",exit_code:1,error:x,result_summary:`${E-1}/${w} prompts completed`},dt(e,x),{status:y.status,reply:v,error:x}}return{status:"ok",reply:v,error:null}}catch(y){let v=`batch: stopped at prompt ${E}/${w} (${E-1} completed): ${y instanceof Error?y.message:String(y)}; later prompts were not sent`;return g.rootFinish={status:"error",exit_code:1,error:v,result_summary:`${E-1}/${w} prompts completed`},dt(e,v),{status:"error",reply:"",error:v}}finally{I.stop()}},4,"Executes a prompt turn within a batch session"),r.registerFunction("lm_batch_close",async(f,T="done",_)=>{let p=typeof f=="string"?t.getBatch(f):f?.id?t.getBatch(f.id)??f:void 0;return p?(await Hd(p,e,T==="done"?"done":T==="cancelled"?"cancelled":"error",_),!0):!1},{min:1,max:3},"Closes a batch session and cleans up resources"),r.registerFunction("lm_ratelimit_readings",async(f={})=>{try{if(!f||typeof f!="object"||Array.isArray(f))throw new Error("lm_ratelimit_readings: options must be a map");let T=f.providers??(f.provider===void 0?["all"]:[f.provider]);if(!Array.isArray(T)||T.some(p=>typeof p!="string"||!p||p.startsWith("-")))throw new Error("lm_ratelimit_readings: providers must be a list of provider names");let _=f.timeoutSeconds??15;if(typeof _!="number"||!Number.isFinite(_)||_<=0)throw new Error("lm_ratelimit_readings: timeoutSeconds must be a positive finite number");return Wd({providers:T.length?T:["all"],timeoutSeconds:_,env:e.env??n,progress:p=>{e.stderr.write(`${p}
|
|
2021
|
+
`)}})}catch(T){return{status:"error",error:T instanceof Error?T.message:String(T),readings:[]}}},{min:0,max:1},"Reads live provider quota values without analytics or aggregation");let i=new WeakSet,o=new Set,a=new Set,l=new Map,c=async(f,T,_={},p=!1)=>{let g=(y,v="",S=null)=>({status:y,reply:v,error:S,message_id:null,team_chat_log_id:null}),E,w=!1,I;try{if(!f||typeof f!="object"||Array.isArray(f))throw new Error("lm_agent: member must be a map");for(let P of["provider","alias","model","effort","sessiondir","sessionid"]){let k=f[P];if(k!=null&&(typeof k!="string"||!k.trim()))throw new Error(`lm_agent: ${P} must be a nonempty string when supplied`)}if(!f.provider)throw new Error("lm_agent: provider is required");if(typeof T!="string")throw new Error("lm_agent: prompt must be a string");if(!_||typeof _!="object"||Array.isArray(_))throw new Error("lm_agent: options must be a map");let y=_.permissionMode??"yolo";if(y!=="yolo"&&y!=="plan")throw new Error("lm_agent: permissionMode must be yolo or plan");if(_.idleTimeoutMs!=null&&(typeof _.idleTimeoutMs!="number"||!Number.isFinite(_.idleTimeoutMs)||_.idleTimeoutMs<0))throw new Error("lm_agent: idleTimeoutMs must be a finite nonnegative number");let v=f.provider,S=f.sessiondir??process.cwd(),x=f.sessionid??"";if(E=x?JSON.stringify([v,x]):void 0,i.has(f)||E!==void 0&&(o.has(E)||!p&&a.has(E)))return g("busy","","lm_agent: session already has an active turn in this engine");i.add(f),E!==void 0&&o.add(E),w=!0,e.stderr.write(`agent ${Ve()}: prompting ${f.alias??v}
|
|
2022
|
+
`),I=Zr(e,P=>`agent ${Ve()}: still running (${P}s elapsed)
|
|
2023
|
+
`);let A=x;if(!A&&["agy","pi","dsh"].includes(v)){if(y!=="yolo")throw new Error(`lm_agent: fresh ${v} sessions require yolo seed; supply sessionid for resume`);let P=await Id({provider:v,cwd:S,model:f.model,effort:f.effort});for(let k of P.warnings??[])e.stderr.write(`warning: ${k}
|
|
2024
|
+
`);if(!P.success||!P.sessionId)throw new Error(P.error??"lm_agent: provider did not identify the seeded session");A=P.sessionId,f.sessionid=A,E=JSON.stringify([v,A]),o.add(E)}let N=await qn({provider:v,cwd:S,sessionId:A,prompt:T,model:f.model,effort:f.effort,alias:f.alias,isLead:!1,permissionMode:y,timeoutMs:_.idleTimeoutMs,requireResume:!!A,env:{...e.env??n},onDelta:()=>I?.poke(),onProgress:()=>I?.poke()});for(let P of N.warnings??[])e.stderr.write(`warning: ${P}
|
|
2025
|
+
`);return A&&N.sessionId!==A?g("error","","lm_agent: provider changed session identity during resume"):(N.sessionId&&(f.sessionid=N.sessionId),N.status==="stalled"?g("stalled",N.text,"provider stalled"):N.status==="empty"?g("empty","","lm_agent: 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"):N.sessionId?g("ok",N.text):g("error",N.text,"lm_agent: provider did not return a session ID"))}catch(y){return g("error","",y instanceof Error?y.message:String(y))}finally{I?.stop(),w&&(i.delete(f),E!==void 0&&o.delete(E))}},u=async(f,T,_={},p=!1)=>{let g=await c(f,T,_,p);if(f?.sessionid&&g.status!=="busy"){let E=JSON.stringify([f.provider,f.sessionid]),w=l.get(E)??{lines:[],options:{}};w.lines.push(`You: ${T}`),g.reply&&w.lines.push(`Agent: ${g.reply}`),g.error&&w.lines.push(`${g.status}: ${g.error}`),w.options={..._},l.set(E,w)}return g};r.registerFunction("lm_agent",u,{min:2,max:3},"Prompts an agent described by a map without a teamfile");let d=async(f,T,_={})=>{if(!Array.isArray(f))throw new Error("lm_fanout: participants must be an array of member maps");if(f.length===0)return[];let p;if(typeof T=="string")p=f.map(()=>T);else if(Array.isArray(T)){if(T.length!==f.length)throw new Error(`lm_fanout: prompts array length (${T.length}) must match participants length (${f.length})`);for(let g of T)if(typeof g!="string")throw new Error("lm_fanout: every prompts[] entry must be a string");p=T}else throw new Error("lm_fanout: prompts must be a string (broadcast to every participant) or an array of strings (one per participant)");if(!_||typeof _!="object"||Array.isArray(_))throw new Error("lm_fanout: options must be a map");return Promise.all(f.map((g,E)=>u(g,p[E],_)))};r.registerFunction("lm_fanout",d,{min:2,max:3},"Dispatches a prompt to every participant in an array concurrently (runtime-sized, unlike parallel()); returns an array of lm_agent-shaped results in the same order as participants. prompts is a single string broadcast to all, or an array of strings (one per participant, same length).");let m=!1,h=async f=>{let T=f!==null&&typeof f=="object";if(m)throw new Error("prompt_human: another operator prompt is active");m=!0;let _,p;try{let g=e.stdin??process.stdin;if(!T)return await qt(f,g,e.stdout);let E={...f};if(Array.isArray(f)||typeof E.provider!="string"||!E.provider.trim()||typeof E.sessionid!="string"||!E.sessionid.trim())return{command:"error",args:["prompt_human: session map requires provider and sessionid; call lm_agent first"]};let w=JSON.stringify([E.provider,E.sessionid]);if(o.has(w))return{command:"busy",args:["Agent turn is still running"]};a.add(w),p=w;let I=g;if(I.destroyed||I.readableEnded)return{command:"eof",args:[]};_=ZE({input:I,output:e.stdout,terminal:!!I.isTTY,crlfDelay:1/0});let y=_[Symbol.asyncIterator](),v=!1;_.on("SIGINT",()=>{v=!0,_?.close()}),e.stdout.write(`Session ${E.alias??E.provider} (${E.sessionid})
|
|
2026
|
+
`);let S=l.get(w);if(S)for(let x of S.lines)e.stdout.write(`${x}
|
|
2027
|
+
`);else{let x=await ut(gt()).getSession(E.sessionid,E.provider);if(!x)return{command:"error",args:["Could not load session history"]};for(let A of x.messages)(A.role==="user"||A.role==="assistant")&&e.stdout.write(`${A.role==="user"?"You":"Agent"}: ${A.content}
|
|
2028
2028
|
`)}for(e.stdout.write(`Talk to the agent. Return to the script with /exit [command] [args...].
|
|
2029
|
-
`);;){e.stdout.write("You> ");let
|
|
2030
|
-
`),
|
|
2031
|
-
`),{command:
|
|
2032
|
-
=== LMScript Error Summary (${
|
|
2033
|
-
`);for(let
|
|
2029
|
+
`);;){e.stdout.write("You> ");let x=await y.next();if(v)return{command:"cancelled",args:[]};if(x.done)return{command:"eof",args:[]};let A=x.value.trim();if(!A)continue;if(/^\/exit(?:\s|$)/u.test(A)){let P=A.split(/\s+/u).slice(1);return{command:P.shift()??"exit",args:P}}let N=await u(E,x.value,S?.options??{},!0);if(N.reply&&e.stdout.write(`Agent: ${N.reply}
|
|
2030
|
+
`),N.status!=="ok")return e.stdout.write(`${N.status}: ${N.error}
|
|
2031
|
+
`),{command:N.status,args:[N.error??"Agent turn failed"]}}}catch(g){if(!T)throw g;return{command:"error",args:[g instanceof Error?g.message:String(g)]}}finally{_?.close(),p!==void 0&&a.delete(p),m=!1}};r.registerFunction("prompt_human",f=>{if(!r.isAsyncMode&&(f===null||typeof f!="object")){if(m)throw new Error("prompt_human: another operator prompt is active");return Xt(f)}return h(f)},{min:0,max:1},{description:"Prompts for a string, or hands an agent session to the operator and returns a decision map",allowOverwrite:!0}),r.registerFunctionDoc({name:"prompt_human",module:"core",category:"System & Process",signature:"prompt_human([question: string]): string|null; prompt_human(session: map): map",description:'Question form reads one line. In the lmctl engine, a session map opens an agent conversation showing script history. /exit retry a b returns {command: "retry", args: ["a", "b"]}; arguments are whitespace-separated. Bare /exit returns command "exit"; closed input returns "eof". Errors, stalls, busy sessions and Ctrl-C return "error", "stalled", "busy" and "cancelled" maps. All map results have args: string[].',example:'agent = { provider: "codex" }; lm_agent(agent, "Review this change"); decision = prompt_human(agent); if (decision.command == "retry") { lm_agent(agent, join(decision.args, " ")); }'}),r.registerFunction("lm_prompt",async(f,T,_,p={})=>{try{let g=await Vi({teamfile:String(f),alias:String(T),prompt:String(_),permissionMode:p?.permissionMode??"yolo",idleTimeoutMs:p?.idleTimeoutMs,env:{...e.env??n},messageType:p?.messageType,io:e});return{status:g.status,reply:g.replyText??"",error:g.message??null,message_id:g.messageId??null,team_chat_log_id:g.teamChatLogId??null}}catch(g){return{status:"error",reply:"",error:g?.message||String(g),message_id:null,team_chat_log_id:null}}},{min:3,max:4},"Sends a prompt directly to a team member and returns the reply")}var Gd={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:Zi,register(r,e){qd(r,e.io,e.registry,e.env)}};function Jd(r,e,t=new $t,n=process.env){return r.registerModule(Gd,{io:e,registry:t,env:n})}function Vd(r,e=[],t=new $t,n=process.env){let s=Xd({scriptArgs:e,io:r,env:n});return Jd(s,r,t,n),s}async function iy(r,e,t={stdout:process.stdout,stderr:process.stderr},n=process.env,s){let i=new $t,o=u=>{for(let d of i.getOpenBatches()){if(d.kind==="agent"){d.closed=!0;continue}if(d.heartbeatTimer){try{d.heartbeatTimer.stop()}catch{}d.heartbeatTimer=void 0}if(d.heldLease){try{if(t.dal)t.dal.releaseAgentInflight(d.heldLease.row,d.heldLease.leaseId);else{let m=ct({path:Pe(n?.LMCTL_DB)});try{m.releaseAgentInflight(d.heldLease.row,d.heldLease.leaseId)}finally{m.close()}}}catch{}d.heldLease=void 0}d.rootId!==null&&ny(t,d.rootId,{status:"cancelled",signal:u,error:`batch interrupted by ${u}`},n)}process.exit(u==="SIGINT"?130:143)};process.once("SIGINT",o),process.once("SIGTERM",o);let a=!1,l,c=()=>{if(a)return;a=!0;let u=i.getErrors(),d=l?l.getRecordedErrors():[],m=[...u];for(let h of d)m.includes(h)||m.push(h);if(m.length>0){t.stderr.write(`
|
|
2032
|
+
=== LMScript Error Summary (${m.length} error${m.length===1?"":"s"}) ===
|
|
2033
|
+
`);for(let h=0;h<m.length;h++)t.stderr.write(` ${h+1}. ${m[h]}
|
|
2034
2034
|
`);t.stderr.write(`==========================================
|
|
2035
|
-
`)}};try{let u=Vd(t,e,i,n);l=u;let d=await u.runAsync(r,{file:s,stderr:
|
|
2036
|
-
`)?
|
|
2037
|
-
`)}});if(c(),d.exitCode!==void 0)return d.exitCode;if(!d.success){for(let
|
|
2038
|
-
`)}return 1}return i.hasErrors()||d.errors&&d.errors.length>0?1:0}catch(u){return c(),u instanceof
|
|
2035
|
+
`)}};try{let u=Vd(t,e,i,n);l=u;let d=await u.runAsync(r,{file:s,stderr:m=>{t.stderr.write(m.endsWith(`
|
|
2036
|
+
`)?m:`${m}
|
|
2037
|
+
`)}});if(c(),d.exitCode!==void 0)return d.exitCode;if(!d.success){for(let m of d.diagnostics){let h=m.file?`${m.file}:${m.line}:${m.column}`:`${m.line}:${m.column}`;t.stderr.write(`error:${h}: ${m.message}
|
|
2038
|
+
`)}return 1}return i.hasErrors()||d.errors&&d.errors.length>0?1:0}catch(u){return c(),u instanceof he||u?.name==="LMScriptExit"?u.exitCode:(t.stderr.write(`error: ${u instanceof Error?u.message:String(u)}
|
|
2039
2039
|
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(t)}}var oy=`# batchscript.lms - Test-only comparison with procedural lmctl batch
|
|
2040
2040
|
# Arguments: [teamfile, alias, batchfile, flags...]
|
|
2041
2041
|
|
|
@@ -2103,4 +2103,4 @@ for (i = 0; i < len(prompts); i = i + 1) {
|
|
|
2103
2103
|
|
|
2104
2104
|
lm_batch_close(handle, "done");
|
|
2105
2105
|
lm_exit(0);
|
|
2106
|
-
`;export{oy as BATCH_LMS,Zi as LMCTL_FUNCTION_DOCS,Me as LMScript,
|
|
2106
|
+
`;export{oy as BATCH_LMS,Zi as LMCTL_FUNCTION_DOCS,Me as LMScript,he as LMScriptExit,$t as ResourceRegistry,Xd as createBaseScriptEngine,Vd as createLmScriptEngine,Gd as lmctlModule,sy as registerLmctlDocs,qd as registerLmctlHostFunctions,Jd as registerLmctlModule,iy as runScriptEngine};
|