@lmctl-ai/lmctl 0.2.15 → 0.2.16
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 +32 -31
- package/dist/cli/script.js +37 -36
- package/package.json +1 -1
package/dist/cli/script.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
var Mf=Object.create;var $s=Object.defineProperty;var Ff=Object.getOwnPropertyDescriptor;var Pf=Object.getOwnPropertyNames;var $f=Object.getPrototypeOf,Uf=Object.prototype.hasOwnProperty;var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var jf=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wf=(t,e)=>{for(var r in e)$s(t,r,{get:e[r],enumerable:!0})},Bf=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pf(e))!Uf.call(t,s)&&s!==r&&$s(t,s,{get:()=>e[s],enumerable:!(n=Ff(e,s))||n.enumerable});return t};var Fa=(t,e,r)=>(r=t!=null?Mf($f(t)):{},Bf(e||!t||!t.__esModule?$s(r,"default",{value:t,enumerable:!0}):r,t));import{readFileSync as cl,appendFileSync as Tp,mkdirSync as Sp,existsSync as Fv,readdirSync as Pv,unlinkSync as $v}from"node:fs";import{join as mn,dirname as wp}from"node:path";import{homedir as vp}from"node:os";function ei(){return mn(vp(),".lmctl")}function Z(){if(dl||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-ll>=Ip&&(al=Ap(),ll=t),al}function xp(){let t=new Date,e=t.getTimezoneOffset(),r=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(t.getTime()-e*6e4).toISOString().replace("Z",`${r}${n}:${s}`)}function Te(t,e){if(e?.verbose){if(!dl)return}else if(!e?.always&&!Z())return;try{bp();let r={ts:new Date().toISOString(),pid:process.pid,vti:process.env.LMCTL_VTI??null,autocode_run_id:process.env.LMCTL_AUTOCODE_RUN_ID??void 0,...t};Tp(un,JSON.stringify(r)+`
|
|
2
2
|
`)}catch{}}function bp(){if(!un){let e=xp().slice(0,13).replace("T","-");un=mn(ei(),`debug-${e}.log`)}Sp(wp(un),{recursive:!0})}function Se(...t){Te({event:"legacy",msg:t.join(" ")})}function le(...t){Te({event:"legacy",msg:t.join(" ")},{verbose:!0})}function R(t){Te(t,{always:!0})}function Ap(){return Rp()||kp()}function Rp(){try{let t=cl(mn(ei(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
3
|
-
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function kp(){try{let t=cl(mn(ei(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var dl,al,ll,Ip,un,z=O(()=>{"use strict";dl=!1,al=!1,ll=0,Ip=5e3;un=null});var _i=jf(
|
|
3
|
+
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function kp(){try{let t=cl(mn(ei(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var dl,al,ll,Ip,un,z=O(()=>{"use strict";dl=!1,al=!1,ll=0,Ip=5e3;un=null});var _i=jf(ge=>{"use strict";function kn(t){if(!Array.isArray(t))throw new TypeError("Each row and headers must be an array of cells");return Array.from(t,e=>{let r=e==null?"":String(e);if(/[\x00-\x1f\x7f-\x9f]/u.test(r))throw new TypeError("Cells must be single-line text without terminal control characters");return r})}function _g(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left" or "right" per column');return t.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function rt(t){let e=0;for(let r of t){let n=r.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 Ec(t,e,r){let n=" ".repeat(Math.max(0,e-rt(t)));return r?n+t:t+n}function yg(t){if(Array.isArray(t))return{rows:t};if(t!==null&&typeof t=="object"&&Array.isArray(t.rows))return t;throw new TypeError("each grid must be a rows array or { rows, headers }")}function Eg(t){if(t===void 0)return"\u2026";if(typeof t!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(t))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return t}function Tg(t,e,r="\u2026"){if(rt(t)<=e)return t;let n=rt(r)>e?"\u2026":r,s=rt(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=rt(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function Sg(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError("max must be an array of per-column width caps");return t.map(e=>{if(e!=null){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new TypeError("max entries must be positive integers, null, or undefined");return e}})}function Sc(t,{max:e}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let r=Sg(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of t){let o=yg(i);o.headers!==void 0&&kn(o.headers).forEach((a,l)=>{s(l,rt(a))});for(let a of o.rows.map(kn))a.forEach((l,c)=>{s(c,rt(l))})}return n.map((i,o)=>{let a=r[o];return a===void 0?i:Math.min(i,a)})}ge.measureColumns=Sc;function wg(t){if(t===void 0)return"";if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return" ".repeat(t);if(typeof t=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(t))return t;throw new TypeError("margin must be a number of spaces or a single-line string")}function wc(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let c=wg(o),d=_g(n),u=Eg(l),f=e??Sc([{rows:t,headers:r}],{max:a}),p=t.map(kn);r!==void 0&&p.unshift(kn(r));let y=p.map(h=>{let _=h.length-1;for(;_>=0&&h[_]==="";)_--;return h.slice(0,_+1).map((m,E)=>{let g=f[E]||0,v=s&&g>0&&(E!==_||i)?Tg(m,g,u):m;return d[E]==="right"?Ec(v,g,!0):E===_?v:Ec(v,g,!1)}).join(" ")}).join(`
|
|
4
4
|
`);return y===""||c===""?y:`${c}${y.split(`
|
|
5
5
|
`).join(`
|
|
6
|
-
${c}`)}`}
|
|
7
|
-
`)}
|
|
8
|
-
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}
|
|
6
|
+
${c}`)}`}ge.renderGrid=wc;function vc(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a}={}){return wc(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a})}function vg(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,stream:l=process.stdout}={}){let c=vc(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a});c&&l.write(`${c}
|
|
7
|
+
`)}ge.formatTable=vc;ge.printTable=vg;function Tc(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function Ig(t,{now:e=Date.now()}={}){let r=Tc(e);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=Tc(t);if(!Number.isFinite(n))return"unknown";let s=n-r,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":""}`}ge.formatRelativeTime=Ig;function xg(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=t<0?"-":"",r=Math.abs(t);if(r<1e3)return String(t);let n=Math.round(r/1e3);return n<1e3?`${e}${n}K`:`${e}${(r/1e6).toFixed(1)}M`}ge.formatCount=xg;var gi=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function bg(t,{maxUnit:e="w",style:r="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let n=gi.findIndex(([a])=>a===e);if(n===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(r!=="spaced"&&r!=="compact")throw new TypeError('style must be "spaced" or "compact"');let s=Math.floor(Math.max(0,t)/1e3);if(r==="compact"){let a=gi.slice(n).filter(([u])=>u!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,d=!1;for(let[u,f]of a){let p=Math.floor(c/f);if(c-=p*f,p>0&&!d){let y=u==="d"||u==="w"?`${p}${u}`:`${Fe(p)}${u}`;l.push({text:y,zero:!1}),d=!0}else d&&l.push({text:`${Fe(p)}${u}`,zero:p===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(u=>u.text).join("")}let i=s,o=[];for(let[a,l]of gi.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(" ")}ge.formatDuration=bg;function Ic(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function Fe(t){return String(t).padStart(2,"0")}function xc(t){let e=Ic(t);return Number.isNaN(e.getTime())?"unknown":`${Fe(e.getHours())}:${Fe(e.getMinutes())}:${Fe(e.getSeconds())}`}ge.formatClock=xc;function Ag(t){let e=Ic(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${Fe(e.getMonth()+1)}-${Fe(e.getDate())}`} ${xc(e)}`}ge.formatLocalTimestamp=Ag;function Rg(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}ge.formatPercent=Rg;function kg(t,{width:e=10,fill:r="#",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",r],["empty",n],["unknown",s]])if(typeof a!="string"||[...a].length!==1||/[\x00-\x1f\x7f-\x9f]/u.test(a)||rt(a)!==1)throw new TypeError(`${o} must be a single character with terminal display width 1`);if(typeof t!="number"||!Number.isFinite(t))return s.repeat(e);let i=Math.min(e,Math.max(0,Math.round(t*e)));return`${r.repeat(i)}${n.repeat(e-i)}`}ge.formatBar=kg;function Ng(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=Math.floor(Math.max(0,t)/1e3),r=Math.floor(e/86400);e-=r*86400;let n=Math.floor(e/3600);e-=n*3600;let s=Math.floor(e/60);e-=s*60;let i=`${Fe(n)}:${Fe(s)}:${Fe(e)}`;return r>0?`${r}d ${i}`:i}ge.formatTimer=Ng;function Lg(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
|
|
8
|
+
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}ge.escapeCell=Lg});import{realpathSync as $g}from"node:fs";import{resolve as Ug}from"node:path";function yi(t){let e=Ug(t);try{return $g(e)}catch{return e}}var kc=O(()=>{"use strict"});import{platform as Nc}from"node:os";function st(t){let e=new Tr;for(let r of t)e.registerAdapter(r);return e}var Tr,Ei=O(()=>{"use strict";kc();Tr=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],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)r.push(...o);let i=r;if(e?.workspace){let o=yi(e.workspace);i=i.filter(a=>yi(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,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,r){let n=await this.resolveSessions(e,r);return n.length===1?n[0]:null}async resolveSessions(e,r){let n=r?this.providers.filter(i=>i.name===r):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=Nc()==="darwin"||Nc()==="win32",r=[];for(let n of this.providers)if(typeof n.getWatchPaths=="function")for(let s of n.getWatchPaths())r.push({provider:n.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return r}async deleteSession(e,r){let n=await this.resolveSession(e,r);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:r=>e.load(r),resolveSessionPath:r=>e.resolvePath(r),deleteSession:r=>e.delete(r),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});import{createReadStream as Lc}from"node:fs";import{createInterface as Cc}from"node:readline";import{stat as jg}from"node:fs/promises";import{homedir as Wg}from"node:os";function Oc(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*re(t){let e=Lc(t,{encoding:"utf-8"}),r=Cc({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(!s)continue;let i=Oc(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function ve(t,e){let r=[],n=Lc(t,{encoding:"utf-8"}),s=Cc({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=Oc(o);if(a!==void 0&&r.push(a),r.length>=e)break}}finally{s.close(),n.destroy()}return r}async function se(t){let e=await jg(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function J(t){return t.replace(/\\n/g,`
|
|
9
9
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function ke(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var W,ce=O(()=>{"use strict";W=Wg()});import{readdir as Cn,stat as Dc,unlink as Bg}from"node:fs/promises";import{join as Gt,basename as Mc}from"node:path";function Hg(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function Xg(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return J(e.trim());if(e!==void 0)return JSON.stringify(e,null,2)}return t.type==="progress"&&t.data!==void 0?JSON.stringify(t.data,null,2):JSON.stringify(t,null,2)}async function Fc(t){let e=0,r=0,n=0,s=0,i=0,o=0,a,l;for await(let c of re(t))if(!c.isSidechain){if(c.type==="user"&&!c.isMeta&&c.message){let d=c.message.content;if(typeof d=="string"){if(d.includes("<command-name>")||d.includes("<local-command-"))continue;e++,l=F(d.trim(),80)}}else if(c.type==="assistant"&&c.message){let d=c.message.content;if(Array.isArray(d))for(let f of d)f.type==="text"&&e++;let u=c.message.usage;if(u){let f=u.input_tokens||0,p=u.cache_creation_input_tokens||0,y=u.cache_read_input_tokens||0,h=u.output_tokens||0;r+=f+p+y,n+=y,s+=p,i+=h;let _=f+p+y;_&&(o=_),a={inputTokens:f,cacheWriteInputTokens:p,cachedInputTokens:y,outputTokens:h}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function qg(t){let e=Gg(t),r=new Set;for(let n of t){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&&(r.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of t){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"||!r.has(s))continue;n.backgroundTaskId=s;let i=e.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function Gg(t){let e=new Map;for(let r of t)r.role==="tool_result"&&r.toolCallId!==void 0&&e.set(r.toolCallId,r);return e}var On,Pc=O(()=>{"use strict";ce();On=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Gt(W,".claude"),this.projectsDir=Gt(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Cn(this.projectsDir)}catch{return e}for(let n of r){let s=Gt(this.projectsDir,n);if(!(await Dc(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Cn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Mc(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Gt(s,a);try{let d=await this.extractSummary(c,l);d&&e.push(d)}catch{}}}return e}async extractSummary(e,r){let n=await ve(e,50),s=await se(e),i="",o,a,l,c,d,u;for(let p of n)if(!Hg(p.type)&&(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!u&&p.timestamp&&(u=new Date(p.timestamp)),p.type==="assistant"&&p.message?.model&&(l=p.message.model),p.type==="user"&&!p.isMeta&&p.message)){let y=p.message.content;if(typeof y=="string"){if(y.includes("<command-name>")||y.includes("<local-command-"))continue;c||(c=F(y.trim(),80)),d=F(y.trim(),80)}}if(!i)return null;let f=await Fc(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:u||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:f.lastUserMessage??d,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await se(r),s=[],i="",o,a,l,c,d,u,f,p=e,y,h=[];for await(let m of re(r))if(m.type!=="file-history-snapshot"&&!m.isSidechain){if(!i&&m.cwd&&(i=m.cwd),!o&&m.slug&&(o=m.slug),!a&&m.version&&(a=m.version),!c&&m.gitBranch&&(c=m.gitBranch),!f&&m.timestamp&&(f=new Date(m.timestamp)),m.sessionId&&(p=m.sessionId),m.type==="system"||m.type==="progress"||m.type==="queue-operation"){s.push({role:"system",timestamp:new Date(m.timestamp||0),content:Xg(m)});continue}if(m.type==="user"&&m.message){if(m.isMeta)continue;let E=new Date(m.timestamp||0),g=m.message.content;if(m.isCompactSummary!==!0&&m.isVisibleInTranscriptOnly!==!0&&m.promptSource!=="system"&&m.toolUseResult===void 0&&m.origin?.kind!=="task-notification"&&m.interruptedMessageId===void 0&&m.interruptedByShutdown!==!0&&m.scheduledTaskId===void 0&&m.scheduledFireId===void 0&&!(Array.isArray(g)&&g.some(v=>v.type==="tool_result"))){let v=typeof g=="string"?g:Array.isArray(g)?g.filter(I=>I.type==="text"&&typeof I.text=="string").map(I=>I.text).join(`
|
|
10
10
|
`):"";v&&!/^<(?:command-name>|local-command-)/u.test(v.trimStart())&&h.push(v)}if(typeof g=="string"){if(g.includes("<command-name>")||g.includes("<local-command-"))continue;d||(d=F(g.trim(),80)),u=F(g.trim(),80),y=void 0,s.push({role:"user",timestamp:E,content:J(g.trim())})}else if(Array.isArray(g)){for(let v of g)if(v.type==="tool_result"){let I=typeof v.content=="string"?J(v.content):JSON.stringify(v.content);s.push({role:"tool_result",timestamp:E,content:I,toolCallId:v.tool_use_id})}}}if(m.type==="assistant"&&m.message){m.message.stop_reason===null||m.message.stop_reason==="tool_use"?y="in_progress":typeof m.message.stop_reason=="string"&&(y="complete"),m.message.model&&(l=m.message.model);let E=new Date(m.timestamp||0),g=m.message.content;if(Array.isArray(g))for(let v of g)v.type==="text"&&v.text?s.push({role:"assistant",timestamp:E,content:J(v.text),model:m.message.model,...typeof m.message.stop_reason=="string"?{stopReason:m.message.stop_reason}:{}}):v.type==="tool_use"?s.push({role:"tool_use",timestamp:E,content:v.name||"unknown tool",toolName:v.name,toolInput:JSON.stringify(v.input,null,2),toolInputData:v.input,toolCallId:v.id,model:m.message.model,...typeof m.message.stop_reason=="string"?{stopReason:m.message.stop_reason}:{}}):v.type==="thinking"&&v.thinking&&s.push({role:"thinking",timestamp:E,content:v.thinking})}}if(!i)return null;qg(s);let _=await Fc(r);return{provider:"claude",sessionId:p,slug:o,cwd:i,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:y,firstUserMessage:d,lastUserMessage:u,messageCount:_.messageCount,filePath:r,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:h}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await Bg(r),!0):!1}async resolveSessionFile(e){let r;try{r=await Cn(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Gt(this.projectsDir,o);if(!(await Dc(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await Cn(a)}catch{continue}for(let d of c){if(!d.endsWith(".jsonl"))continue;let u=Mc(d,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Gt(a,d),fileSessionId:u})}}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 ve(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as Jg,writeFileSync as gx,mkdirSync as _x}from"node:fs";import{join as Vg,dirname as Ex}from"node:path";import{homedir as Kg}from"node:os";function zg(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Qg(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=zg(t.slice(e+1).trim());return r?{key:r,value:n}:null}function Zg(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Dn(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function e_(){return Vg(Kg(),".lmctl","config.toml")}function Uc(t){let e=t??e_(),r;try{r=Jg(e,"utf-8")}catch{return{tools:{}}}return t_(r)}function $c(t){if(typeof t=="number")return Number.isFinite(t)?t:null;let e=String(t).trim();if(!e)return null;let r=e.match(/^(\d+(?:\.\d+)?)\s*([KkMm]?)$/);if(!r)return null;let n=parseFloat(r[1]);if(!Number.isFinite(n))return null;switch(r[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 t_(t){let e={},r={},n=t.split(`
|
|
11
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let u=e[s.tool]??{};if(s.profile){let f=u.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),u.profiles||(u.profiles={}),u.profiles[s.profile]=f}else i.start&&(u.start=i.start),i.resume&&(u.resume=i.resume),i.agent&&(u.agent=i.agent),i.profile_flag!==void 0&&(u.profile_flag=i.profile_flag);e[s.tool]=u}else if(s.kind==="compact"){let u=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let f=$c(i.min);f!==null&&(u.min=f)}if(i.max!==void 0){let f=$c(i.max);f!==null&&(u.max=f)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let f=u.trim();if(!f||f.startsWith("#"))continue;let p=Zg(f);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let h=".profile.",_=p.indexOf(h);_!==-1?s={kind:"tool",tool:p.slice(5,_),profile:p.slice(_+h.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let y=Qg(f);y&&s.kind!=="none"?i[y.key]=y.value:y&&!o&&(a[y.key]=y.value)}l();let c={tools:e};(r.global||r.providers)&&(c.compact=r);let d=a.site_name;return d!==void 0&&d.length>0&&(c.site_name=d),c}function r_(t,e,r){if(!r)return"";let n=t.tools[e]??Ti[e],s=n?.profiles?.[r]?.flags??Ti[e]?.profiles?.[r]?.flags;if(s!==void 0)return s.trim();if(n?.profile_flag)return n.profile_flag.replace(/\{\{profile\}\}/g,r).trim();throw new Error(`Profile "${r}" is not configured for tool "${e}"`)}function jc(t,e){return!!t.tools[e]}function Wc(t,e,r,n,s){let i=t.tools[e]??Ti[e],o;if(i?.agent){let l=Dn(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=Yg[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(d=>d.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let d=c.map(Dn).join(" ");o=`printf '%s\\n' ${Dn(n)} | ${d}`}else o=c.map(Dn).join(" ")}let a=r_(t,e,s);return a&&(o+=" "+a),o}var Ti,Yg,Si=O(()=>{"use strict";Ti={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:""}}}},Yg={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 Bc(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let r=Number(e);return!Number.isFinite(r)||r<=0?6e5:r}var Hc=O(()=>{"use strict"});var n_,H,Mn,
|
|
11
|
+
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let u=e[s.tool]??{};if(s.profile){let f=u.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),u.profiles||(u.profiles={}),u.profiles[s.profile]=f}else i.start&&(u.start=i.start),i.resume&&(u.resume=i.resume),i.agent&&(u.agent=i.agent),i.profile_flag!==void 0&&(u.profile_flag=i.profile_flag);e[s.tool]=u}else if(s.kind==="compact"){let u=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let f=$c(i.min);f!==null&&(u.min=f)}if(i.max!==void 0){let f=$c(i.max);f!==null&&(u.max=f)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let f=u.trim();if(!f||f.startsWith("#"))continue;let p=Zg(f);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let h=".profile.",_=p.indexOf(h);_!==-1?s={kind:"tool",tool:p.slice(5,_),profile:p.slice(_+h.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let y=Qg(f);y&&s.kind!=="none"?i[y.key]=y.value:y&&!o&&(a[y.key]=y.value)}l();let c={tools:e};(r.global||r.providers)&&(c.compact=r);let d=a.site_name;return d!==void 0&&d.length>0&&(c.site_name=d),c}function r_(t,e,r){if(!r)return"";let n=t.tools[e]??Ti[e],s=n?.profiles?.[r]?.flags??Ti[e]?.profiles?.[r]?.flags;if(s!==void 0)return s.trim();if(n?.profile_flag)return n.profile_flag.replace(/\{\{profile\}\}/g,r).trim();throw new Error(`Profile "${r}" is not configured for tool "${e}"`)}function jc(t,e){return!!t.tools[e]}function Wc(t,e,r,n,s){let i=t.tools[e]??Ti[e],o;if(i?.agent){let l=Dn(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=Yg[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(d=>d.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let d=c.map(Dn).join(" ");o=`printf '%s\\n' ${Dn(n)} | ${d}`}else o=c.map(Dn).join(" ")}let a=r_(t,e,s);return a&&(o+=" "+a),o}var Ti,Yg,Si=O(()=>{"use strict";Ti={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:""}}}},Yg={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 Bc(t=process.env){let e=t.LMCTL_ONE_SHOT_TIMEOUT_MS;if(!e)return 6e5;let r=Number(e);return!Number.isFinite(r)||r<=0?6e5:r}var Hc=O(()=>{"use strict"});var n_,H,Mn,_e=O(()=>{"use strict";n_="ACK: waiting for explicit lmctl task.",H=`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: ${n_}`,Mn=`send this exact lmctl seed instruction: "${H}"`});import{existsSync as s_}from"node:fs";function Xc(t){let e=t.CLAUDE_CODE_EXECPATH;if(e===void 0||e.length===0)return t;let r=process.platform!=="win32"&&e.toLowerCase().endsWith(".exe"),n=!r&&!s_(e);if(!r&&!n)return t;R({event:"claude_execpath_sanitized",reason:r?"wrong_platform_exe":"missing_file",value:e,platform:process.platform});let s={...t};return delete s.CLAUDE_CODE_EXECPATH,s}function Jt(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function o_(t,e){return e===void 0||e.length===0?t:{...t??process.env,[wi]:e}}function ue(t,e,r,n="chat"){return{...o_(Jt(t,e),r),[i_]:n}}var wi,i_,Xe=O(()=>{"use strict";z();wi="LMCTL_SELF_SESSIONID",i_="LMCTL_LAUNCH_SOURCE"});function Sr(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var vi=O(()=>{"use strict"});import{spawn as qc}from"node:child_process";import{mkdirSync as a_}from"node:fs";var Ii,K,Ie=O(()=>{"use strict";Si();Hc();_e();Xe();vi();Ii=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},K=class t{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 r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===H?r:n)}turnOptsFor(e){return e}seed(e,r){return a_(e,{recursive:!0}),new Promise(n=>{let s;try{s=qc(this.binary,this.seedArgsFor(r),{cwd:e,env:Jt(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=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
12
12
|
`: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=Sr(o).trim(),d=Sr(i).trim();n({success:!1,error:(c||d).slice(0,500)||`exit code ${l}`})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:Mn,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){let n=this.turnOptsFor(r);if(n.userConfig&&jc(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??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,r,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),d(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},d=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let u={...n,binary:this.binary,signal:s.signal,onDelta:y=>{a+=y,c(),n.onDelta?.(y)},onProgress:y=>{y.kind!=="api_retry"&&c(),n.onProgress?.(y)}},f=this.transportFn(r,u).then(y=>(d(),{...y,status:y.status??"ok"})).catch(y=>{throw d(),o==="external"?new Ii("Turn cancelled","external"):y}),p=new Promise(y=>{l=y});return Promise.race([f,p])}runOneShotAgent(e,r,n){let s=Wc(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=Bc(r.env),c=qc(s,{shell:!0,cwd:r.cwd,env:ue(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),d=!1,u=!1,f=setTimeout(()=>{u=!0,c.kill()},l),p="",y="";if(c.stdout?.on("data",h=>{let _=h.toString();p+=_,r.onDelta?.(_)}),c.stderr?.on("data",h=>{y+=h.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",h=>{if(d)return;d=!0,clearTimeout(f);let _=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?o({text:p.trim(),sessionId:r.sessionId,durationMs:_}):a(new Error(y.trim().slice(0,200)||`Agent command exited with code ${h}`))}),c.on("error",h=>{d||(d=!0,clearTimeout(f),a(h))})})}}});function Ir(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new vr(t,r,e)}var it,Y,wr,Fn,vr,vt=O(()=>{"use strict";it=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},Y=class extends it{},wr=class extends it{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},Fn=class extends it{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},vr=class extends it{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as bi from"node:child_process";function c_(t){if(typeof bi.spawnSync=="function")try{bi.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function Gc(t){return t.exitCode!==null||t.signalCode!==null}function xi(t,e){return Gc(t)?Promise.resolve(!0):new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(i),r(!0))},i=setTimeout(()=>{n||(n=!0,t.removeListener("exit",s),r(!1))},e);t.once("exit",s)})}async function Q(t,e={}){let r=Date.now(),n=e.stdinEnd!==!1,s=e.softDelayMs??5e3,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??c_;if(Gc(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await xi(t,s))return{signal:"stdin",elapsedMs:Date.now()-r};if(o==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await xi(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await xi(t,l_)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var l_,xr=O(()=>{"use strict";l_=1e3});function Jc(t){Z()&&Te({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function ot(t,e){let r=u_[t];if(r)return r[e]??r.yolo}function f_(t,e){if(e.length===0)return!0;for(let r=0;r+e.length<=t.length;r++){let n=!0;for(let s=0;s<e.length;s++)if(t[r+s]!==e[s]){n=!1;break}if(n)return!0}return!1}function de(t,e,r="yolo"){if(m_.has(t)){Jc(`YOLO ${t} [mode=${r}]: ${t==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${r==="plan"?"read-only":"danger-full-access"})`:t==="opencode"?".opencode/opencode.json (permission=allow)":t==="kimi"?`ACP session/set_config_option (configId=mode, value=${r==="plan"?"plan":"auto"})`:t==="dsh"?"DSH_PERMISSION_MODE=danger-full-access env var on the sidecar spawn \u2014 no argv flag":t==="hermes"?"HERMES_YOLO_MODE=1 shell gate + ACP session/set_mode (modeId=dont_ask) edit gate":t==="pi"?"no tool-permission prompts exist in pi by design \u2014 nothing to bypass":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=r==="plan"?ot(t,"plan"):d_[t];if(!n){let s=`unknown provider "${t}" \u2014 YOLO contract not configured. Add an entry to YOLO_FLAGS in src/providers/yolo-contract.ts before spawning this provider.`;throw R({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new Y(s)}if(!f_(e,n)){let s=n.join(" "),i=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(o=>JSON.stringify(o)).join(", ")}]`;throw R({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new Y(i)}Jc(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var d_,u_,m_,qe=O(()=>{"use strict";vt();z();d_={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},u_={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"]}};m_=new Set(["codex","opencode","kimi","dsh","hermes","pi"])});async function $n(t,e,r){if(typeof t=="boolean")return t;let n,s;try{return await Promise.race([t,new Promise(i=>{n=setTimeout(()=>i(Ai),e),n.unref?.(),r!==void 0&&(s=()=>i(Ai),r.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&r?.removeEventListener("abort",s)}}function at(t,e){if(t===void 0){e.closeStdin();return}let r=!1,n=i=>{if(!r){r=!0;try{t.onRelease?.({elapsedMs:Date.now()-i.startedMs,held:i.held,reason:i.reason})}catch{}}e.closeStdin()},s=Date.now();y_(t,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function y_(t,e,r,n){let s=t.pollMs??p_,i=t.maxHoldMs??Pn,o=t.settleMs??h_,a=t.backgroundGraceMs??g_,l=!1,c=null,d=u=>n({startedMs:r,held:l,reason:u});for(;;){if(e.isAborted())return d("aborted");if(e.hasChildExited())return d("child-exited");let u=i-(Date.now()-r);if(u<=0)return d("max-hold");let f;try{f=await $n(t.hasOutstandingWork(),u,e.signal)}catch{return d("check-error")}if(f===Ai)return d(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(f)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-r<a){let h=a-(Date.now()-r);await new Promise(_=>setTimeout(_,Math.max(0,Math.min(s,__,h))).unref?.());continue}if(!l||o<=0)return d("cleared");c===null&&(c=Date.now(),le(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let y=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-y>=o)return d("cleared")}if(l||(l=!0,t.onHold?.(),le(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-r>=i)return R({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-r}),d("max-hold");let p=Math.max(0,Math.min(s,i-(Date.now()-r)));await new Promise(y=>setTimeout(y,p).unref?.())}}var p_,Pn,h_,g_,__,Ai,Un=O(()=>{"use strict";z();p_=2e3,Pn=8*60*60*1e3,h_=5e3,g_=1e3,__=50,Ai=Symbol("check-timed-out")});function Vc(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=[];for(let r=0;r<t.length;r++)r===0?e.push(t[r]):e.push(`
|
|
13
13
|
|
|
14
14
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
@@ -17,9 +17,9 @@ ${c}`)}`}he.renderGrid=wc;function vc(t,{headers:e,align:r,truncate:n,truncateTr
|
|
|
17
17
|
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:
|
|
18
18
|
${e}
|
|
19
19
|
|
|
20
|
-
${r}`:r}function rd(t){let e=t.tool||"claude",r=t.binaryPath||T_[e]||"claude",n=["-p","","--output-format","stream-json","--input-format","stream-json"];e==="claude"&&n.push("--verbose"),t.sessionId&&n.push("--resume",t.sessionId),t.model&&n.push("--model",t.model);let s=t.permissionMode??"yolo",i=ot(e,s)??w_[e]??["--dangerously-skip-permissions"];if(n.push(...i),de(e,n,s),t.cwd&&!Qc(t.cwd))throw R({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new Y(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=ue(t.env,t.cwd,t.sessionId);return{tool:e,binary:r,args:n,spawnEnv:e==="claude"?Xc(o):o}}function nd(t,e){return new Promise((r,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=rd(e))}catch(M){return n(M instanceof Error?M:new Error(String(M)))}let c=zc(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",M=>{le(`stream-json: stdin pipe error, ignored (exit handler reports): ${M.message}`)});let d=!1;if(e.signal){if(e.signal.aborted)return d=!0,R({event:"transport_abort",provider:i,phase:"pre_spawn"}),Q(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,R({event:"transport_abort",provider:i}),Q(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let u="",f=!1,p=!1,y=0,h=!1,_="",m="",E,g,v=null,I=null,T=!1,w=!1,S=Zc(),x=ed();function b(){E!==void 0&&(clearTimeout(E),E=void 0)}function k(){g!==void 0&&(clearTimeout(g),g=void 0)}let $=null;function A(){return f||d||ne.sawResult()}function U(M){return M==="text_done"?S:x}async function V(M){if(M==="text_done"?E=void 0:g=void 0,A()||v!==null)return;$??=Date.now();let G=U(M);if(e.holdOpen){let ar=(e.holdOpen.maxHoldMs??Pn)-(Date.now()-$),Fs=ar>0?await $n(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),ar,e.signal):!1;if(A()||(M==="text_done"?E!==void 0:g!==void 0))return;if(Fs===!0){R({event:"transport_stall_grace_deferred",provider:i,grace_kind:M,grace_ms:G,reason:"outstanding_dispatched_work"}),te(M);return}}I=M,v=M==="text_done"?`${i} finished responding but never emitted its closing result event (${G}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${G}ms of silence)`,R({event:"transport_stall_grace_fired",provider:i,grace_kind:M,grace_ms:G}),Q(c).catch(()=>{})}function te(M){let G=setTimeout(()=>{V(M)},U(M));G.unref?.(),M==="text_done"?(b(),E=G):(k(),g=G)}let ne=jn({onEvent:M=>{y=Date.now(),h=M.type!=="result",M.type==="system"&&M.subtype==="init"&&(m=M.session_id||m),M.type==="assistant"?(T=!td(M),w=T&&M.message?.stop_reason==="pause_turn"):(M.type==="result"||M.type==="user")&&(T=!1,w=!1),b(),i==="claude"&&T&&!w&&!ne.sawResult()&&te("text_done"),k(),i==="claude"&&!ne.sawResult()&&te("tool_use_silence"),e.onEvent?.(M)},onText:M=>{_+=M,e.onText?.(M)}});function
|
|
20
|
+
${r}`:r}function rd(t){let e=t.tool||"claude",r=t.binaryPath||T_[e]||"claude",n=["-p","","--output-format","stream-json","--input-format","stream-json"];e==="claude"&&n.push("--verbose"),t.sessionId&&n.push("--resume",t.sessionId),t.model&&n.push("--model",t.model);let s=t.permissionMode??"yolo",i=ot(e,s)??w_[e]??["--dangerously-skip-permissions"];if(n.push(...i),de(e,n,s),t.cwd&&!Qc(t.cwd))throw R({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new Y(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=ue(t.env,t.cwd,t.sessionId);return{tool:e,binary:r,args:n,spawnEnv:e==="claude"?Xc(o):o}}function nd(t,e){return new Promise((r,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=rd(e))}catch(M){return n(M instanceof Error?M:new Error(String(M)))}let c=zc(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",M=>{le(`stream-json: stdin pipe error, ignored (exit handler reports): ${M.message}`)});let d=!1;if(e.signal){if(e.signal.aborted)return d=!0,R({event:"transport_abort",provider:i,phase:"pre_spawn"}),Q(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,R({event:"transport_abort",provider:i}),Q(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let u="",f=!1,p=!1,y=0,h=!1,_="",m="",E,g,v=null,I=null,T=!1,w=!1,S=Zc(),x=ed();function b(){E!==void 0&&(clearTimeout(E),E=void 0)}function k(){g!==void 0&&(clearTimeout(g),g=void 0)}let $=null;function A(){return f||d||ne.sawResult()}function U(M){return M==="text_done"?S:x}async function V(M){if(M==="text_done"?E=void 0:g=void 0,A()||v!==null)return;$??=Date.now();let G=U(M);if(e.holdOpen){let ar=(e.holdOpen.maxHoldMs??Pn)-(Date.now()-$),Fs=ar>0?await $n(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),ar,e.signal):!1;if(A()||(M==="text_done"?E!==void 0:g!==void 0))return;if(Fs===!0){R({event:"transport_stall_grace_deferred",provider:i,grace_kind:M,grace_ms:G,reason:"outstanding_dispatched_work"}),te(M);return}}I=M,v=M==="text_done"?`${i} finished responding but never emitted its closing result event (${G}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${G}ms of silence)`,R({event:"transport_stall_grace_fired",provider:i,grace_kind:M,grace_ms:G}),Q(c).catch(()=>{})}function te(M){let G=setTimeout(()=>{V(M)},U(M));G.unref?.(),M==="text_done"?(b(),E=G):(k(),g=G)}let ne=jn({onEvent:M=>{y=Date.now(),h=M.type!=="result",M.type==="system"&&M.subtype==="init"&&(m=M.session_id||m),M.type==="assistant"?(T=!td(M),w=T&&M.message?.stop_reason==="pause_turn"):(M.type==="result"||M.type==="user")&&(T=!1,w=!1),b(),i==="claude"&&T&&!w&&!ne.sawResult()&&te("text_done"),k(),i==="claude"&&!ne.sawResult()&&te("tool_use_silence"),e.onEvent?.(M)},onText:M=>{_+=M,e.onText?.(M)}});function Ee(){p||(p=!0,at(e.holdOpen,{isAborted:()=>d,hasChildExited:()=>f,isTurnInFlight:()=>h,lastEventAtMs:()=>y,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function ht(M){let G=ne.sawResult();ne.processLine(M),!G&&ne.sawResult()&&Ee()}c.stdout?.on("data",M=>{u+=M.toString();let G=u.split(`
|
|
21
21
|
`);u=G.pop()||"";for(let Zr of G)ht(Zr)});let q="";c.stderr?.on("data",M=>{q+=M.toString()}),c.on("error",M=>{R({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:M.message}),n(new Y(`Failed to spawn ${o}: ${M.message}`,{cause:M}))}),c.on("exit",M=>{if(f=!0,b(),k(),d)return;u.trim()&&ht(u);let G=ne.finalize();G?.isError?(R({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:G.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${G.errorMessage??"unknown error"}`))):G?(le(`stream-json: result ${G.result.slice(0,80)}${G.result.length>80?"...":""} (${G.durationMs}ms)`),r({result:G.result,sessionId:G.sessionId,durationMs:G.durationMs,numTurns:G.numTurns,exitCode:M})):v!==null&&I==="text_done"&&_.trim().length>0?(R({event:"transport_stall_finalized",provider:i,reason:v,text_len:_.length}),r({result:_,sessionId:m||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:M,warnings:[v]})):v!==null&&I==="tool_use_silence"?(R({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:M,stderr_tail:q.slice(0,500)}),n(new Error(`${v} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(e.sessionId?` (session=${e.sessionId})`:"")))):(R({event:"transport_error",provider:i,error_class:"Error",reason:v!==null?"provider_stalled_no_content":"provider_no_result",exit_code:M,stderr_tail:q.slice(0,500)}),n(new Error(v!==null?`${v} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):S_({tool:i,exitCode:M,stderr:q}))))});let me=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(me+`
|
|
22
|
-
`),le(`stream-json: prompt sent (${t.length} chars)`)})}function v_(t){return t==="qwen"?[Wn(W,".qwen","projects")]:[Wn(W,".claude","projects")]}async function Yc(t,e,r){let n=r??v_(t),s=null;for(let a of n){let l;try{l=await E_(a)}catch{continue}for(let c of l){for(let d of[Wn(a,c,`${e}.jsonl`),Wn(a,c,"chats",`${e}.jsonl`)])if(Qc(d)){s=d;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 ve(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 sd(t){let{tool:e,binary:r,args:n,spawnEnv:s}=rd(t),i=zc(r,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",N=>{le(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${N.message}`)});let a={exited:!1,exitCode:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=null,d="";i.stderr?.on("data",N=>{d+=N.toString()});let u="",f="",p=!1,y=!1,h=null,_=null,m=null,E,g,v=Zc(),I=ed(),T=null,w=[],S=()=>a.exited?Promise.resolve():new Promise(N=>{w.push(N)}),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 b(){E!==void 0&&(clearTimeout(E),E=void 0)}function k(){g!==void 0&&(clearTimeout(g),g=void 0)}function $(){return a.exited||T===null||T.aborted||T.processor.sawResult()}function A(N){return N==="text_done"?v:I}async function U(N){if(N==="text_done"?E=void 0:g=void 0,$()||h!==null)return;m??=Date.now();let P=A(N);if(t.holdOpen){let Ct=(t.holdOpen.maxHoldMs??Pn)-(Date.now()-m),en=Ct>0?await $n(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),Ct,void 0):!1;if($()||(N==="text_done"?E!==void 0:g!==void 0))return;if(en===!0){R({event:"transport_stall_grace_deferred",provider:e,grace_kind:N,grace_ms:P,reason:"outstanding_dispatched_work"}),V(N);return}}_=N,h=N==="text_done"?`${e} finished responding but never emitted its closing result event (${P}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${P}ms of silence)`,R({event:"transport_stall_grace_fired",provider:e,grace_kind:N,grace_ms:P}),Q(i).catch(()=>{})}function V(N){let P=setTimeout(()=>{U(N)},A(N));P.unref?.(),N==="text_done"?(b(),E=P):(k(),g=P)}let te=!1,ne,
|
|
22
|
+
`),le(`stream-json: prompt sent (${t.length} chars)`)})}function v_(t){return t==="qwen"?[Wn(W,".qwen","projects")]:[Wn(W,".claude","projects")]}async function Yc(t,e,r){let n=r??v_(t),s=null;for(let a of n){let l;try{l=await E_(a)}catch{continue}for(let c of l){for(let d of[Wn(a,c,`${e}.jsonl`),Wn(a,c,"chats",`${e}.jsonl`)])if(Qc(d)){s=d;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 ve(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 sd(t){let{tool:e,binary:r,args:n,spawnEnv:s}=rd(t),i=zc(r,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",N=>{le(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${N.message}`)});let a={exited:!1,exitCode:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=null,d="";i.stderr?.on("data",N=>{d+=N.toString()});let u="",f="",p=!1,y=!1,h=null,_=null,m=null,E,g,v=Zc(),I=ed(),T=null,w=[],S=()=>a.exited?Promise.resolve():new Promise(N=>{w.push(N)}),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 b(){E!==void 0&&(clearTimeout(E),E=void 0)}function k(){g!==void 0&&(clearTimeout(g),g=void 0)}function $(){return a.exited||T===null||T.aborted||T.processor.sawResult()}function A(N){return N==="text_done"?v:I}async function U(N){if(N==="text_done"?E=void 0:g=void 0,$()||h!==null)return;m??=Date.now();let P=A(N);if(t.holdOpen){let Ct=(t.holdOpen.maxHoldMs??Pn)-(Date.now()-m),en=Ct>0?await $n(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),Ct,void 0):!1;if($()||(N==="text_done"?E!==void 0:g!==void 0))return;if(en===!0){R({event:"transport_stall_grace_deferred",provider:e,grace_kind:N,grace_ms:P,reason:"outstanding_dispatched_work"}),V(N);return}}_=N,h=N==="text_done"?`${e} finished responding but never emitted its closing result event (${P}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${P}ms of silence)`,R({event:"transport_stall_grace_fired",provider:e,grace_kind:N,grace_ms:P}),Q(i).catch(()=>{})}function V(N){let P=setTimeout(()=>{U(N)},A(N));P.unref?.(),N==="text_done"?(b(),E=P):(k(),g=P)}let te=!1,ne,Ee,ht=new Promise((N,P)=>{ne=N,Ee=P});ht.catch(()=>{});let q=setTimeout(()=>{te||(te=!0,Ee(new Error(`stream-json bundle: ${e} emitted no init event within the open timeout \u2014 cannot verify the resumed session identity`)))},t.closeTimeoutMs!==void 0?Math.max(t.closeTimeoutMs,5e3):3e4);q.unref?.();function me(N){te||(te=!0,clearTimeout(q),N?Ee(N):ne())}let M="";function G(N){if(a.lastEventAtMs=Date.now(),N.type==="system"&&N.subtype==="init"){if(f=N.session_id||f,t.sessionId&&typeof N.session_id=="string"&&N.session_id.length>0&&N.session_id!==t.sessionId){let oe=new Error(`stream-json bundle: provider resumed a different session (init reported "${N.session_id}", expected "${t.sessionId}")`);me(oe),Q(i).catch(()=>{});return}me()}let P=T?.processor.sawResult()??!0;N.type==="assistant"?(p=!td(N),y=p&&N.message?.stop_reason==="pause_turn"):(N.type==="result"||N.type==="user")&&(p=!1,y=!1),b(),e==="claude"&&a.turnActive&&p&&!y&&!P&&V("text_done"),k(),e==="claude"&&a.turnActive&&!P&&V("tool_use_silence")}function Zr(){let N=T;if(N===null)return;let P=N.processor.finalize();if(P!==null){if(T=null,a.turnActive=!1,b(),k(),P.isError){R({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:P.errorMessage}),N.reject(new Error(`${e} reported an error for this turn (no assistant output)`+(t.sessionId?` \u2014 session=${t.sessionId}`:"")+`: ${P.errorMessage??"unknown error"}`));return}a.completedTurns+=1,l=P.sessionId||l,le(`stream-json bundle: result ${P.result.slice(0,80)}${P.result.length>80?"...":""} (${P.durationMs}ms)`),N.resolve({result:P.result,sessionId:P.sessionId||l,durationMs:P.durationMs,numTurns:P.numTurns})}}function ar(N){if(!N.trim())return;let P;try{P=JSON.parse(N)}catch{return}G(P);let oe=T;if(oe!==null){let Ct=oe.processor.sawResult();oe.processor.processLine(N),oe.onEventForward?.(P),!Ct&&oe.processor.sawResult()&&Zr()}}i.stdout?.on("data",N=>{M+=N.toString();let P=M.split(`
|
|
23
23
|
`);M=P.pop()||"";for(let oe of P)ar(oe)}),i.on("error",N=>{if(c=new Y(`Failed to spawn ${r}: ${N.message}`,{cause:N}),R({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:N.message}),me(c),T!==null){let P=T;T=null,a.turnActive=!1,P.reject(c)}}),i.on("exit",N=>{a.exited=!0,a.exitCode=N,b(),k(),M.trim()&&ar(M),me(a.exited&&!te?new Error(`stream-json bundle: ${e} exited (code ${String(N)}) before its init event`):void 0);let P=T;P!==null&&(T=null,a.turnActive=!1,P.aborted||(h!==null&&_==="text_done"&&u.trim().length>0?(R({event:"transport_stall_finalized",provider:e,reason:h,text_len:u.length}),P.resolve({result:u,sessionId:f||t.sessionId||"",durationMs:Date.now()-P.startMs,numTurns:1,warnings:[h]})):h!==null&&_==="tool_use_silence"?(R({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:N,stderr_tail:d.slice(0,500)}),P.reject(new Error(`${h} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(t.sessionId?` (session=${t.sessionId})`:"")))):(R({event:"transport_error",provider:e,error_class:"Error",reason:h!==null?"provider_stalled_no_content":"provider_no_result",exit_code:N,stderr_tail:d.slice(0,500)}),P.reject(x()))));for(let oe of w.splice(0))oe()});try{t.sessionId&&await Yc(e,t.sessionId,t.sessionFileRoots),await ht}catch(N){let P=c??(N instanceof Error?N:new Error(String(N))),oe=t.closeTimeoutMs??2e3;throw await Q(i,{softDelayMs:Math.min(1e3,oe),killDelayMs:Math.min(1e3,oe)}).catch(()=>{}),P}let Fs=N=>new Promise(P=>{setTimeout(P,N).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(N,P={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw x();if(T!==null)throw new Error(`stream-json bundle session (${e}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);let oe=()=>(a.closed=!0,Q(i).catch(()=>{}),new Error("Aborted"));if(P.signal?.aborted)throw oe();if(t.sessionId&&(await Yc(e,t.sessionId,t.sessionFileRoots),a.exited))throw x();if(P.signal?.aborted)throw oe();return u="",p=!1,y=!1,h=null,_=null,m=null,new Promise((Ct,en)=>{let Ps={processor:jn({onText:Ma=>{u+=Ma,P.onText?.(Ma)}}),resolve:Ct,reject:en,startMs:Date.now(),aborted:!1,onEventForward:P.onEvent};T=Ps,a.turnActive=!0;let Of=()=>{Ps.aborted=!0,R({event:"transport_abort",provider:e}),a.closed=!0,Q(i).catch(()=>{}),T===Ps&&(T=null,a.turnActive=!1),en(new Error("Aborted"))};P.signal?.addEventListener("abort",Of,{once:!0});let Df=JSON.stringify({type:"user",message:{role:"user",content:N}});i.stdin?.write(`${Df}
|
|
24
24
|
`),le(`stream-json bundle: prompt sent (${N.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(N=>{at(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),N()},label:e})}):i.stdin?.end(),!a.exited)){let N=t.closeTimeoutMs??2e3;await Promise.race([S(),Fs(N)]),a.exited||await Q(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,N),killDelayMs:Math.min(1e3,N)}).catch(()=>{})}})()),a.closing}}}var T_,w_,ki=O(()=>{"use strict";vt();xr();qe();z();Un();Xe();Ri();ce();Ri();T_={claude:"claude",qwen:"qwen"};w_={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function Ni(t={}){return[]}var Li=O(()=>{"use strict"});function Ci(t){return t==="plan"?"read-only":"danger-full-access"}function id(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function Bn(){return{agentItems:new Map,resultText:""}}function Vt(t,e,r,n){let s=t.method;if(!s)return!1;let i=t.params;if(s==="turn/started")return e.agentItems.clear(),e.resultText="",!1;if(s==="item/started"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=typeof o.phase=="string"?o.phase:void 0,l=a==="commentary"||a==="final_answer"?a:void 0;return e.agentItems.set(o.id,{phase:l,buffer:""}),!0}return!1}if(s==="item/agentMessage/delta"){let o=i?.delta||"",a=typeof i?.itemId=="string"?i.itemId:void 0;if(!o)return!0;let l=a?e.agentItems.get(a):void 0;return l?(l.phase==="commentary"||(l.buffer+=o),r?.(o),l.phase&&i&&(i._lmctlItemPhase=l.phase)):(e.resultText+=o,r?.(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,d=typeof i?.turnId=="string"?i.turnId:void 0;n({itemId:o.id,threadId:c,turnId:d,expectedFromItemText:o.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(o.id)}return!0}return!1}return!1}function Hn(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function od(t){let e=t.params,r=e?.error,n=typeof r?.message=="string"?r.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 Xn(){return{pendingCodexError:null}}function qn(t,e){let r=od(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function Gn(t,e){if(e.pendingCodexError){let i=e.pendingCodexError;return e.pendingCodexError=null,{shouldReject:!0,turnError:i}}let n=t.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 Oi=O(()=>{"use strict"});import{spawn as ad}from"node:child_process";import{createInterface as ld}from"node:readline";import{existsSync as I_,readFileSync as x_}from"node:fs";import{fileURLToPath as b_}from"node:url";function cd(){return id(A_)}function lt(t,e){le(`[codex:${t}] ${JSON.stringify(e)}`)}function R_(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
25
25
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
@@ -60,38 +60,38 @@ One possible cause: the provider process failed before a complete ACP response w
|
|
|
60
60
|
${e}
|
|
61
61
|
|
|
62
62
|
${r}`:r}function oy(t,e){return Dr(t)?.filterExpectedStderr?.(e)??e}function Wd(t){if(t.method!=="session/update")return!1;let r=t.params?.update;if(r===void 0)return!1;let n=r.sessionUpdate;if(n!=="tool_call"&&n!=="tool_call_update")return!1;let s=r.status;return s!==void 0&&s!=="pending"&&s!=="in_progress"?!1:r.rawInput?.background===!0}async function Bd(t,e,r,n){for(let s of t.sessionSetup??[]){let i={...e,sessionId:r.sessionId,response:r.response,sendRpc:n};if(s.applies(i))try{await s.run(i),s.successLog&&le(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(R({event:a.event,provider:t.name,...a.fields}),a.stderrLine&&process.stderr.write(a.stderrLine),a.warning&&e.warnings.push(a.warning),s.onFailure==="fail-closed")throw new Error(a.message)}}}function Hd(t,e,r){let n=ue(e.env,e.cwd,e.sessionId);t.preSpawn?.({...r,cwd:e.cwd,env:n});let s=e.binaryPath||t.binary,i=t.argv(r),o=t.yoloAssertion==="always-yolo"?"yolo":r.permissionMode;if(de(e.tool,i,o),e.cwd&&!sy(e.cwd))throw R({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new Y(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:n}}async function Xd(t){let{sendRpc:e,sendNotification:r,opts:n,outputProcessor:s}=t,i=t.strictSessionIdentity===!0;await e("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r("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
|
|
63
|
-
`),R({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let d=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=ct(d),s.setSessionId(o),{sessionId:o,sessionResponse:d}}if(i){let c=ct(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(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await t.verifyLoadResponse(l)}o=n.sessionId}else o=ct(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=ct(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function qd(t,e){let r=Dr(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{jd(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,d;try{({binary:l,spawnArgs:c,spawnEnv:d}=Hd(r,e,a))}catch(S){return s(S instanceof Error?S:new Error(String(S)))}let u=Ud(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:d}),f=Date.now(),p=!1,y=!1,h=0,_=!1,m=!1;if(e.signal){if(e.signal.aborted)return p=!0,R({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),Q(u).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,R({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-f}),Q(u).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let E=e.sessionId||"",g=Vn({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});g.setSessionId(E);let v=Ar(u,{provider:e.tool,onEvent:S=>{h=Date.now(),Wd(S)&&(m=!0),e.onEvent?.(S)},onNotification:S=>{h=Date.now(),g.processMessage(S)}}),{sendRpc:I,sendNotification:T}=v,w="";u.stderr?.on("data",S=>{w+=S.toString()}),u.on("error",S=>{v.close(S),R({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-f}),s(new Y(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${S.message}`,{cause:S}))}),u.on("exit",S=>{if(y=!0,v.close(new Y(`ACP process exited with code ${String(S)}`)),p)return;let x=g.finalize();if(x!==null)r.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-f,stopReason:x.stopReason,exitCode:S,sawActivity:x.sawActivity,...o.length>0?{warnings:o}:{}});else{let b=oy(e.tool,w);R({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:b.slice(0,500),elapsed_ms:Date.now()-f}),s(new Error(iy({tool:e.tool,exitCode:S,stderr:b})))}}),(async()=>{try{let S=await Xd({sendRpc:I,sendNotification:T,opts:e,outputProcessor:g});E=S.sessionId;let x=S.sessionResponse;await Bd(r,a,{sessionId:E,response:x},I),g.beginTurn(),_=!0,le(`acp: prompt sent (${t.length} chars)`);let b=await I("session/prompt",{sessionId:E,prompt:[{type:"text",text:t}]}),k=g.completeTurn(b);_=!1,le(`acp: result received (${k.result.length} chars, stopReason=${k.stopReason})`),at(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>y,isTurnInFlight:()=>_,lastEventAtMs:()=>h,closeStdin:()=>{u.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>m})}catch(S){Q(u).catch(()=>{}),s(S instanceof Error?S:new Error(String(S)))}})()})}async function Gd(t){let e=Dr(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&jd(t.tool,t.acpMode);let r=t.permissionMode??"yolo",n=[],s=!0,i={permissionMode:r,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:S=>{n.push(S)}}},{binary:o,spawnArgs:a,spawnEnv:l}=Hd(e,t,i),c=Ud(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),d=Date.now(),u={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},f=t.sessionId||"",p=null,y="";c.stderr?.on("data",S=>{y+=S.toString()});let h,_,m=Vn({tool:t.tool,onDelta:S=>h?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});m.setSessionId(f);let E=Ar(c,{provider:t.tool,onEvent:S=>{u.lastEventAtMs=Date.now(),Wd(S)&&(u.backgroundJobLaunched=!0),_?.(S)},onNotification:S=>{u.lastEventAtMs=Date.now(),m.processMessage(S)}}),g=()=>new Error(`ACP bundle process (${t.tool}) exited${u.exitCode!==null?` with code ${u.exitCode}`:""} after ${u.completedTurns} completed prompt(s); the bundle cannot continue`),v=[],I=()=>u.exited?Promise.resolve():new Promise(S=>{v.push(S)}),T=null;c.on("error",S=>{p=new Y(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),R({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-d}),E.close(S)}),c.on("exit",S=>{if(u.exited=!0,u.exitCode=S,E.close(new Y(`ACP process exited with code ${String(S)}`)),!u.telemetryFired){u.telemetryFired=!0;let x=m.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S})}if(T!==null){let x=T;T=null,x(g())}for(let x of v.splice(0))x()});try{let S=await Xd({sendRpc:E.sendRpc,sendNotification:E.sendNotification,opts:t,outputProcessor:m,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:x,cwd:t.cwd,env:l})});f=S.sessionId,await Bd(e,i,{sessionId:S.sessionId,response:S.sessionResponse},E.sendRpc)}catch(S){let x=p??(S instanceof Error?S:new Error(String(S)));throw Q(c).catch(()=>{}),x}let w=S=>new Promise(x=>{setTimeout(x,S).unref?.()});return{tool:t.tool,get sessionId(){return f},get completedTurns(){return u.completedTurns},async sendTurn(S,x={}){if(u.closed||u.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(u.exited)throw g();if(u.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:f,cwd:t.cwd,env:l}),u.exited)throw g();if(x.signal?.aborted)throw new Error("Aborted")}u.turnInFlight=!0,h=x.onDelta,_=x.onEvent;let b=Date.now();try{m.beginTurn(),le(`acp: bundle prompt sent (${S.length} chars)`);let k=await new Promise((U,V)=>{T=V;let te=()=>{m.cancelTurn(),E.sendNotification("session/cancel",{sessionId:f}),V(new Error("Aborted"))},ne=x.signal;ne?.addEventListener("abort",te,{once:!0}),E.sendRpc("session/prompt",{sessionId:f,prompt:[{type:"text",text:S}]}).then(ye=>{ne?.removeEventListener("abort",te),U(ye)},ye=>{ne?.removeEventListener("abort",te),V(ye instanceof Error?ye:new Error(String(ye)))})});T=null;let $=m.completeTurn(k);u.turnInFlight=!1,u.completedTurns+=1,le(`acp: bundle result received (${$.result.length} chars, stopReason=${$.stopReason})`);let A=s&&n.length>0?[...n]:void 0;return s=!1,{result:$.result,sessionId:$.sessionId,stopReason:$.stopReason,durationMs:Date.now()-b,sawActivity:$.sawActivity,...A!==void 0?{warnings:A}:{}}}catch(k){throw T=null,m.cancelTurn(),u.turnInFlight=!1,u.exited?g():k}finally{h=void 0,_=void 0}},close(){return u.closing!==null||(u.closing=(async()=>{if(u.closed=!0,u.exited||(t.holdOpen!==void 0?await new Promise(x=>{at(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>u.exited,isTurnInFlight:()=>u.turnInFlight,lastEventAtMs:()=>u.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:t.tool,wasBackgroundJobLaunched:()=>u.backgroundJobLaunched})}):c.stdin?.end(),u.exited))return;let S=t.closeTimeoutMs??2e3;await Promise.race([I(),w(S)]),u.exited||await Q(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),u.closing}}}var Ji=O(()=>{"use strict";z();vt();xr();Un();qe();z();Xe();br();Di();$d();Gi();Hi();br()});function ee(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function Kd(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=ay){let n=t.keys().next().value;n!==void 0&&t.delete(n)}t.set(r.id,Date.now()),e(r);return}if(r.kind==="tool_result"&&typeof r.id=="string"&&r.elapsedMs===void 0){let n=t.get(r.id);if(n!==void 0){e({...r,elapsedMs:Date.now()-n}),t.delete(r.id);return}}e(r)}}function ly(){let t=new Map;return(e,r)=>{cy(e,Kd(t,r))}}function cy(t,e){let r=t.type;if(r==="system"){let n=t.subtype;if(n==="api_retry"){let s=typeof t.attempt=="number"?t.attempt:void 0,i=typeof t.max_retries=="number"?t.max_retries:void 0,o=typeof t.error_status=="number"?t.error_status:void 0,a=typeof t.error=="string"?t.error:void 0,l=typeof t.retry_delay_ms=="number"?t.retry_delay_ms:void 0,c=[];s!==void 0&&c.push(i!==void 0?`attempt ${s}/${i}`:`attempt ${s}`),o!==void 0&&c.push(`HTTP ${o}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(ee(a,60));let d=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:d});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(ee(i,80)),e({kind:"other",summary:o.join(": "),raw:t});return}e({kind:"system",summary:n||"system",raw:t});return}if(r==="assistant"||r==="user"){let s=t.message?.content;if(!Array.isArray(s))return;for(let i of s){let o=i.type;if(o==="text"){let a=i.text||"";a&&e({kind:"text",summary:ee(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,d="";c&&(typeof c.command=="string"?d=c.command:typeof c.file_path=="string"?d=c.file_path:typeof c.path=="string"?d=c.path:typeof c.pattern=="string"?d=c.pattern:typeof c.url=="string"?d=c.url:d=ee(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:ee(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:ee(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,d,u=i.content;if(typeof u=="string")d=`${u.split(`
|
|
63
|
+
`),R({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let d=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=ct(d),s.setSessionId(o),{sessionId:o,sessionResponse:d}}if(i){let c=ct(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(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await t.verifyLoadResponse(l)}o=n.sessionId}else o=ct(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=ct(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function qd(t,e){let r=Dr(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{jd(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,d;try{({binary:l,spawnArgs:c,spawnEnv:d}=Hd(r,e,a))}catch(S){return s(S instanceof Error?S:new Error(String(S)))}let u=Ud(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:d}),f=Date.now(),p=!1,y=!1,h=0,_=!1,m=!1;if(e.signal){if(e.signal.aborted)return p=!0,R({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),Q(u).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,R({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-f}),Q(u).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let E=e.sessionId||"",g=Vn({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});g.setSessionId(E);let v=Ar(u,{provider:e.tool,onEvent:S=>{h=Date.now(),Wd(S)&&(m=!0),e.onEvent?.(S)},onNotification:S=>{h=Date.now(),g.processMessage(S)}}),{sendRpc:I,sendNotification:T}=v,w="";u.stderr?.on("data",S=>{w+=S.toString()}),u.on("error",S=>{v.close(S),R({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-f}),s(new Y(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${S.message}`,{cause:S}))}),u.on("exit",S=>{if(y=!0,v.close(new Y(`ACP process exited with code ${String(S)}`)),p)return;let x=g.finalize();if(x!==null)r.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-f,stopReason:x.stopReason,exitCode:S,sawActivity:x.sawActivity,...o.length>0?{warnings:o}:{}});else{let b=oy(e.tool,w);R({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:b.slice(0,500),elapsed_ms:Date.now()-f}),s(new Error(iy({tool:e.tool,exitCode:S,stderr:b})))}}),(async()=>{try{let S=await Xd({sendRpc:I,sendNotification:T,opts:e,outputProcessor:g});E=S.sessionId;let x=S.sessionResponse;await Bd(r,a,{sessionId:E,response:x},I),g.beginTurn(),_=!0,le(`acp: prompt sent (${t.length} chars)`);let b=await I("session/prompt",{sessionId:E,prompt:[{type:"text",text:t}]}),k=g.completeTurn(b);_=!1,le(`acp: result received (${k.result.length} chars, stopReason=${k.stopReason})`),at(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>y,isTurnInFlight:()=>_,lastEventAtMs:()=>h,closeStdin:()=>{u.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>m})}catch(S){Q(u).catch(()=>{}),s(S instanceof Error?S:new Error(String(S)))}})()})}async function Gd(t){let e=Dr(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&jd(t.tool,t.acpMode);let r=t.permissionMode??"yolo",n=[],s=!0,i={permissionMode:r,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:S=>{n.push(S)}}},{binary:o,spawnArgs:a,spawnEnv:l}=Hd(e,t,i),c=Ud(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),d=Date.now(),u={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},f=t.sessionId||"",p=null,y="";c.stderr?.on("data",S=>{y+=S.toString()});let h,_,m=Vn({tool:t.tool,onDelta:S=>h?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});m.setSessionId(f);let E=Ar(c,{provider:t.tool,onEvent:S=>{u.lastEventAtMs=Date.now(),Wd(S)&&(u.backgroundJobLaunched=!0),_?.(S)},onNotification:S=>{u.lastEventAtMs=Date.now(),m.processMessage(S)}}),g=()=>new Error(`ACP bundle process (${t.tool}) exited${u.exitCode!==null?` with code ${u.exitCode}`:""} after ${u.completedTurns} completed prompt(s); the bundle cannot continue`),v=[],I=()=>u.exited?Promise.resolve():new Promise(S=>{v.push(S)}),T=null;c.on("error",S=>{p=new Y(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),R({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-d}),E.close(S)}),c.on("exit",S=>{if(u.exited=!0,u.exitCode=S,E.close(new Y(`ACP process exited with code ${String(S)}`)),!u.telemetryFired){u.telemetryFired=!0;let x=m.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:S})}if(T!==null){let x=T;T=null,x(g())}for(let x of v.splice(0))x()});try{let S=await Xd({sendRpc:E.sendRpc,sendNotification:E.sendNotification,opts:t,outputProcessor:m,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:x,cwd:t.cwd,env:l})});f=S.sessionId,await Bd(e,i,{sessionId:S.sessionId,response:S.sessionResponse},E.sendRpc)}catch(S){let x=p??(S instanceof Error?S:new Error(String(S)));throw Q(c).catch(()=>{}),x}let w=S=>new Promise(x=>{setTimeout(x,S).unref?.()});return{tool:t.tool,get sessionId(){return f},get completedTurns(){return u.completedTurns},async sendTurn(S,x={}){if(u.closed||u.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(u.exited)throw g();if(u.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:f,cwd:t.cwd,env:l}),u.exited)throw g();if(x.signal?.aborted)throw new Error("Aborted")}u.turnInFlight=!0,h=x.onDelta,_=x.onEvent;let b=Date.now();try{m.beginTurn(),le(`acp: bundle prompt sent (${S.length} chars)`);let k=await new Promise((U,V)=>{T=V;let te=()=>{m.cancelTurn(),E.sendNotification("session/cancel",{sessionId:f}),V(new Error("Aborted"))},ne=x.signal;ne?.addEventListener("abort",te,{once:!0}),E.sendRpc("session/prompt",{sessionId:f,prompt:[{type:"text",text:S}]}).then(Ee=>{ne?.removeEventListener("abort",te),U(Ee)},Ee=>{ne?.removeEventListener("abort",te),V(Ee instanceof Error?Ee:new Error(String(Ee)))})});T=null;let $=m.completeTurn(k);u.turnInFlight=!1,u.completedTurns+=1,le(`acp: bundle result received (${$.result.length} chars, stopReason=${$.stopReason})`);let A=s&&n.length>0?[...n]:void 0;return s=!1,{result:$.result,sessionId:$.sessionId,stopReason:$.stopReason,durationMs:Date.now()-b,sawActivity:$.sawActivity,...A!==void 0?{warnings:A}:{}}}catch(k){throw T=null,m.cancelTurn(),u.turnInFlight=!1,u.exited?g():k}finally{h=void 0,_=void 0}},close(){return u.closing!==null||(u.closing=(async()=>{if(u.closed=!0,u.exited||(t.holdOpen!==void 0?await new Promise(x=>{at(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>u.exited,isTurnInFlight:()=>u.turnInFlight,lastEventAtMs:()=>u.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:t.tool,wasBackgroundJobLaunched:()=>u.backgroundJobLaunched})}):c.stdin?.end(),u.exited))return;let S=t.closeTimeoutMs??2e3;await Promise.race([I(),w(S)]),u.exited||await Q(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),u.closing}}}var Ji=O(()=>{"use strict";z();vt();xr();Un();qe();z();Xe();br();Di();$d();Gi();Hi();br()});function ee(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function Kd(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=ay){let n=t.keys().next().value;n!==void 0&&t.delete(n)}t.set(r.id,Date.now()),e(r);return}if(r.kind==="tool_result"&&typeof r.id=="string"&&r.elapsedMs===void 0){let n=t.get(r.id);if(n!==void 0){e({...r,elapsedMs:Date.now()-n}),t.delete(r.id);return}}e(r)}}function ly(){let t=new Map;return(e,r)=>{cy(e,Kd(t,r))}}function cy(t,e){let r=t.type;if(r==="system"){let n=t.subtype;if(n==="api_retry"){let s=typeof t.attempt=="number"?t.attempt:void 0,i=typeof t.max_retries=="number"?t.max_retries:void 0,o=typeof t.error_status=="number"?t.error_status:void 0,a=typeof t.error=="string"?t.error:void 0,l=typeof t.retry_delay_ms=="number"?t.retry_delay_ms:void 0,c=[];s!==void 0&&c.push(i!==void 0?`attempt ${s}/${i}`:`attempt ${s}`),o!==void 0&&c.push(`HTTP ${o}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(ee(a,60));let d=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:d});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(ee(i,80)),e({kind:"other",summary:o.join(": "),raw:t});return}e({kind:"system",summary:n||"system",raw:t});return}if(r==="assistant"||r==="user"){let s=t.message?.content;if(!Array.isArray(s))return;for(let i of s){let o=i.type;if(o==="text"){let a=i.text||"";a&&e({kind:"text",summary:ee(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,d="";c&&(typeof c.command=="string"?d=c.command:typeof c.file_path=="string"?d=c.file_path:typeof c.path=="string"?d=c.path:typeof c.pattern=="string"?d=c.pattern:typeof c.url=="string"?d=c.url:d=ee(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:ee(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:ee(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,d,u=i.content;if(typeof u=="string")d=`${u.split(`
|
|
64
64
|
`).length} lines, ${u.length} chars`;else if(Array.isArray(u)){let f=u.map(p=>typeof p=="object"&&p&&"text"in p?p.text:"").filter(Boolean).join("");f&&(d=`${f.split(`
|
|
65
65
|
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:d,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function zn(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?ly():void 0;if(e.bundleSession!==void 0){let i=e.bundleSession;if(i.provider!==r)throw new Error(`bundle session provider mismatch: session serves "${i.provider}", turn targets "${r}"`);let o=await i.sendTurn(t,{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 nd(t,{sessionId:e.sessionId,cwd:e.cwd,env:e.env,tool:r,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 Qn(t){let e=t.binary==="qwen"?"qwen":"claude",r=await sd({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs,sessionFileRoots:t.sessionFileRoots});return{provider:e,get sessionId(){return r.sessionId},get completedTurns(){return r.completedTurns},async sendTurn(n,s={}){let i=await r.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:()=>r.close()}}function dy(){let t=new Map;return(e,r)=>{uy(e,Kd(t,r))}}function uy(t,e){if(t.method!=="session/update")return;let s=t.params?.update;if(!s)return;let i=s.sessionUpdate;if(i){if(i==="agent_message_chunk"){let a=s.content?.text||"";a&&e({kind:"text",summary:ee(a)});return}if(i==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:ee(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=ee(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:ee(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:"",d=c?`running\u2026 ${ee(c,80)}`:"running\u2026";e({kind:"other",summary:d,id:a})}return}e({kind:"other",summary:i})}}function Jd(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function Pe(t,e){let r=e.acpTool||e.binary,n=e.onProgress?dy():void 0;if(e.bundleSession!==void 0){let a=e.bundleSession;if(a.provider!==r)throw new Error(`bundle session provider mismatch: session serves "${a.provider}", turn targets "${r}"`);let l=await a.sendTurn(t,{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,...Jd(l.text,l.sawActivity)!==void 0?{status:"empty"}:{},...l.warnings!==void 0?{warnings:l.warnings}:{}}}let s=[];if(e.model&&r==="copilot"){let a="copilot --acp does not implement per-session model selection";Te({event:"model_ignored",provider:r,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await qd(t,{tool:r,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,...Jd(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function $e(t){let e=t.acpTool||t.binary,r=await Gd({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,effort:t.effort,alias:t.alias,permissionMode:t.permissionMode,acpMode:t.acpMode,requireResume:!0,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:e,get sessionId(){return r.sessionId},get completedTurns(){return r.completedTurns},async sendTurn(n,s){let i=await r.sendTurn(n,s);return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>r.close()}}function Vd(t,e){let r=t.method;if(!r)return;let n=t.params;if(r==="turn/started"){e({kind:"system",summary:"turn started"});return}if(r==="turn/completed"){e({kind:"system",summary:"turn completed"});return}if(r==="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: ${ee(o,120)}`}:{kind:"other",summary:`codex error: ${ee(o,120)}`});return}if(r==="item/started"||r==="item/completed"){let s=n?.item;if(!s)return;let i=s.type,o=r==="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:ee(c||"(command)"),id:a});else{let d=s.exitCode,u=s.status||"",f=typeof s.durationMs=="number"?s.durationMs:void 0,p=typeof d=="number"?`exit ${d}`:u||"done",y=[];typeof d=="number"?y.push(`exit ${d}`):u&&y.push(u),typeof f=="number"&&y.push(`${Math.round(f/1e3)}s`),e({kind:"tool_result",summary:y.join(", ")||"done",status:p,elapsedMs:f,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(d=>d.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:ee(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 d=s.status||"done";e({kind:"tool_result",summary:d,status:d,id:a})}return}case"webSearch":{let a=typeof s.id=="string"?s.id:void 0;e(o?{kind:"tool_use",tool:"WebSearch",summary:ee(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(r==="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:ee(s)}:{kind:"text",summary:ee(s)})}return}if(r==="item/reasoning/summaryTextDelta"||r==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:ee(s)});return}if(r==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let i=s.split(`
|
|
66
66
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${ee(o,60)}`:ee(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r==="item/commandExecution/terminalInteraction"||r==="item/commandExecution/outputChunk"||r==="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(`
|
|
67
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${ee(o,60)}`:ee(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r.startsWith("item/")){e({kind:"other",summary:r.slice(5)});return}}async function Yd(t,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(t,{onDelta:e.onDelta,onEvent:e.onProgress?i=>Vd(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await ud(t,{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=>Vd(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function zd(t){let e=await md({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(r,n){let s=await e.sendTurn(r,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var ay,Ge=O(()=>{"use strict";ki();ki();fd();Ji();z();ay=256});import{join as Qd}from"node:path";function Ki(t){return new Vi(t)}var Vi,Yi=O(()=>{"use strict";Pc();Ie();ce();Ge();
|
|
67
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${ee(o,60)}`:ee(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r.startsWith("item/")){e({kind:"other",summary:r.slice(5)});return}}async function Yd(t,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(t,{onDelta:e.onDelta,onEvent:e.onProgress?i=>Vd(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await ud(t,{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=>Vd(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function zd(t){let e=await md({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(r,n){let s=await e.sendTurn(r,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var ay,Ge=O(()=>{"use strict";ki();ki();fd();Ji();z();ay=256});import{join as Qd}from"node:path";function Ki(t){return new Vi(t)}var Vi,Yi=O(()=>{"use strict";Pc();Ie();ce();Ge();_e();Vi=class extends K{claudeDir;constructor(e){super({provider:new On(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",H,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:zn}),this.claudeDir=e?.claudeDir??Qd(W,".claude")}openSession(e){return Qn({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[Qd(this.claudeDir,"projects")]})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as my,stat as Zd,unlink as fy}from"node:fs/promises";import{join as Mr,basename as py}from"node:path";function hy(t,e,r){return`${t}|${e.toISOString()}|${r}`}function Fr(t,e,r){let n=hy(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function eu(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function gy(t){if(!t)return;let e=t.cached_input_tokens??t.cache_read_input_tokens;return{inputTokens:t.input_tokens,cachedInputTokens:e,outputTokens:t.output_tokens,reasoningOutputTokens:t.reasoning_output_tokens,totalTokens:t.total_tokens}}function Yt(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.map(r=>{if(typeof r=="string")return r;if(r&&typeof r=="object"){let n=r;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 Yt(r)}).filter(r=>r.length>0).join(`
|
|
68
68
|
`);try{return JSON.stringify(t)}catch{return String(t)}}function _y(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function yy(t,e){if(e===void 0)return;let r={input:e};if(t!=="apply_patch"||typeof e!="string")return r;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&&(r.path=n[0].path,r.paths=n.map(s=>s.path),r.kinds=n.map(s=>s.kind)),r}async function tu(t){let e=0,r=0,n=0,s=0,i=0,o,a,l;for await(let c of re(t)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let d=c.payload.message||c.payload.text;d&&(l=F(d.trim(),80))}if(c.type==="response_item"&&c.payload){let d=c.payload;if(d.type==="message"&&d.role==="user"&&d.content)for(let u of d.content)u.type==="input_text"&&typeof u.text=="string"&&u.text&&(e++,l=F(u.text.trim(),80));else if(d.type==="message"&&d.role==="assistant"&&d.content)for(let u of d.content)u.type==="output_text"&&typeof u.text=="string"&&u.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 d=c.payload.info.total_token_usage;r=d.input_tokens??r,n=d.cached_input_tokens??d.cache_read_input_tokens??n,s=d.output_tokens??s,i=d.reasoning_output_tokens??i;let u=gy(c.payload.info.last_token_usage);u&&(o=u),typeof c.payload.info.model_context_window=="number"&&(a=c.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:r,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:a,lastUserMessage:l}}var Zn,ru=O(()=>{"use strict";ce();Zn=class{name="codex";codexDirs;constructor(e={}){let r=[Mr(W,".codex"),Mr(W,".code")];if(e.codexDirs&&e.codexDirs.length>0){this.codexDirs=[...new Set(e.codexDirs)];return}let n=[e.codexDir||r[0],e.codeDir||r[1]];this.codexDirs=[...new Set(n)]}getWatchPaths(){return this.codexDirs.map(e=>({directory:Mr(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=Mr(r,"sessions");try{await Zd(n),e.push(n)}catch{}}return e}async discoverSessions(){let e=[],r=await this.getSessionsDirs();for(let n of r){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 r=[],n;try{n=await my(e)}catch{return r}for(let s of n){let i=Mr(e,s),o=await Zd(i).catch(()=>null);if(o)if(o.isDirectory()){let a=await this.findSessionFiles(i);r.push(...a)}else s.endsWith(".jsonl")&&r.push(i)}return r}extractSessionIdFromFilename(e){let r=py(e,".jsonl"),n=r.match(/rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(.+)$/);return n?n[1]:r}async extractSummary(e){let r=await ve(e,30),n=await se(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,d,u,f;for(let y of r){if(y.type==="session_meta"&&y.payload&&(y.payload.id&&(s=y.payload.id),y.payload.cwd&&(i=y.payload.cwd),y.payload.cli_version&&(o=y.payload.cli_version),y.payload.timestamp&&(l=new Date(y.payload.timestamp)),y.payload.originator&&(u=y.payload.originator),y.payload.source&&(f=y.payload.source)),y.type==="turn_context"&&y.payload&&(y.payload.model&&(a=y.payload.model),!i&&y.payload.cwd&&(i=y.payload.cwd)),y.type==="event_msg"&&y.payload?.type==="user_message"){let h=y.payload.message||y.payload.text;h&&(c||(c=F(h.trim(),80)),d=F(h.trim(),80))}if(y.type==="response_item"&&y.payload?.type==="message"&&y.payload.role==="user"&&y.payload.content){let h=y.payload.content.find(_=>_.type==="input_text"&&typeof _.text=="string"&&_.text);typeof h?.text=="string"&&(c||(c=F(h.text.trim(),80)),d=F(h.text.trim(),80))}}if(!i)return null;let p=await tu(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:eu(u,f),firstUserMessage:c,lastUserMessage:p.lastUserMessage??d,messageCount:p.messageCount,filePath:e,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCachedInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,totalReasoningOutputTokens:p.totalReasoningOutputTokens||void 0,lastInputTokens:p.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:p.lastTokenUsage,modelContextWindow:p.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await se(r),s=[],i="",o,a,l,c,d,u=e,f,p,y=new Set,h=[],_=new Set,m=[],E=(I,T)=>{let w=m.find(S=>!S.mirrored&&S.source!==T&&S.text===I);w?w.mirrored=!0:m.push({text:I,source:T,mirrored:!1})},g=()=>{h.push(...m.map(I=>I.text)),m=[]};for await(let I of re(r)){let T=I.timestamp?new Date(I.timestamp):new Date;if(I.type==="session_meta"&&I.payload){I.payload.id&&(u=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)),f=eu(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 w=I.payload;if(w.type==="message"){if(w.role==="user"&&w.content){let S=w.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(S)){let x=w.content.filter((b,k)=>S[k]==="user.text"&&typeof b.text=="string").map(b=>b.text).join(`
|
|
69
69
|
`);S.includes("user.text")&&x&&(!w.id||!_.has(w.id))&&(E(x,"metadata"),w.id&&_.add(w.id))}for(let x of w.content)if(x.type==="input_text"&&typeof x.text=="string"&&x.text){let b=x.text.trim();c||(c=F(b,80)),d=F(b,80),Fr(s,y,{role:"user",timestamp:T,content:J(b)})}continue}if(w.role==="assistant"&&w.content){for(let S of w.content)S.type==="output_text"&&typeof S.text=="string"&&S.text&&Fr(s,y,{role:"assistant",timestamp:T,content:J(S.text),model:a});continue}if(w.role!=="user"&&w.role!=="assistant"&&w.content){for(let S of w.content)(S.type==="input_text"||S.type==="output_text")&&typeof S.text=="string"&&S.text&&Fr(s,y,{role:"system",timestamp:T,content:J(S.text.trim())});continue}}if(w.type==="function_call"){s.push({role:"tool_use",timestamp:T,content:w.name||"unknown tool",toolName:w.name,toolInput:w.arguments!==void 0?J(Yt(w.arguments)):void 0,toolInputData:_y(w.arguments),toolCallId:w.call_id});continue}if(w.type==="function_call_output"){s.push({role:"tool_result",timestamp:T,content:J(Yt(w.output)),toolCallId:w.call_id});continue}if(w.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:T,content:w.name||"unknown tool",toolName:w.name,toolInput:w.input!==void 0?J(Yt(w.input)):void 0,toolInputData:yy(w.name,w.input),toolCallId:w.call_id});continue}if(w.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:T,content:J(Yt(w.output)),toolCallId:w.call_id});continue}if(w.type==="reasoning"&&w.summary){let S=w.summary.map(x=>Yt(x.text)).join(`
|
|
70
|
-
`);S.trim()&&Fr(s,y,{role:"thinking",timestamp:T,content:J(S)});continue}}if(I.type==="event_msg"&&I.payload&&(I.payload.type==="task_started"?(g(),p="in_progress"):I.payload.type==="task_complete"?p="complete":I.payload.type==="turn_aborted"&&(p="aborted"),I.payload.type==="user_message"&&typeof I.payload.message=="string"&&E(I.payload.message,"event"),I.payload.type==="agent_reasoning")){let w=I.payload.message||I.payload.text;w&&Fr(s,y,{role:"thinking",timestamp:T,content:J(w)})}}if(!i)return null;g();let v=await tu(r);return{provider:"codex",sessionId:u,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:f,turnStatus:p,firstUserMessage:c,lastUserMessage:d,messageCount:v.messageCount,filePath:r,totalInputTokens:v.totalInputTokens||void 0,totalCachedInputTokens:v.totalCachedInputTokens||void 0,totalOutputTokens:v.totalOutputTokens||void 0,totalReasoningOutputTokens:v.totalReasoningOutputTokens||void 0,lastInputTokens:v.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:v.lastTokenUsage,modelContextWindow:v.modelContextWindow,messages:s,userPrompts:h}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await fy(r),!0):!1}async resolveSessionFile(e){let r=await this.getSessionsDirs(),n=[];for(let i of r){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 ve(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 Zi(t){return new Qi(t)}var zi,Qi,eo=O(()=>{"use strict";ru();Ie();Ge();
|
|
70
|
+
`);S.trim()&&Fr(s,y,{role:"thinking",timestamp:T,content:J(S)});continue}}if(I.type==="event_msg"&&I.payload&&(I.payload.type==="task_started"?(g(),p="in_progress"):I.payload.type==="task_complete"?p="complete":I.payload.type==="turn_aborted"&&(p="aborted"),I.payload.type==="user_message"&&typeof I.payload.message=="string"&&E(I.payload.message,"event"),I.payload.type==="agent_reasoning")){let w=I.payload.message||I.payload.text;w&&Fr(s,y,{role:"thinking",timestamp:T,content:J(w)})}}if(!i)return null;g();let v=await tu(r);return{provider:"codex",sessionId:u,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:f,turnStatus:p,firstUserMessage:c,lastUserMessage:d,messageCount:v.messageCount,filePath:r,totalInputTokens:v.totalInputTokens||void 0,totalCachedInputTokens:v.totalCachedInputTokens||void 0,totalOutputTokens:v.totalOutputTokens||void 0,totalReasoningOutputTokens:v.totalReasoningOutputTokens||void 0,lastInputTokens:v.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:v.lastTokenUsage,modelContextWindow:v.modelContextWindow,messages:s,userPrompts:h}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await fy(r),!0):!1}async resolveSessionFile(e){let r=await this.getSessionsDirs(),n=[];for(let i of r){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 ve(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 Zi(t){return new Qi(t)}var zi,Qi,eo=O(()=>{"use strict";ru();Ie();Ge();_e();zi="gpt-5.6-sol",Qi=class extends K{constructor(e){super({provider:new Zn(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:`${H}
|
|
71
71
|
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Yd})}openSession(e){return zd({...e,model:e.model??zi})}seedArgsFor(e){let r=super.seedArgsFor(e),n=e?.model??zi;return[...r.slice(0,-1),"--model",n,r[r.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:zi}}}});function Pr(t){if(!t.trim())return"unknown";let e=t.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 r;try{r=JSON.parse(t)}catch{return"unknown"}if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let n=r;if(Array.isArray(n.messages))return"json";if("kind"in n)return"jsonl"}return"unknown"}function es(t){let e=Pr(t);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(t);return{sessionId:a.sessionId,projectHash:a.projectHash,startTime:a.startTime,lastUpdated:a.lastUpdated,kind:a.kind,messages:Array.isArray(a.messages)?a.messages:[]}}let r=t.split(`
|
|
72
72
|
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[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<r.length;a++){let l;try{l=JSON.parse(r[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 d=c;if(typeof d.id=="string"){let u=o.get(d.id);u?Ey(u,d):(i.push(d),o.set(d.id,d))}else i.push(d)}}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 Ey(t,e){for(let[r,n]of Object.entries(e))if(n!==void 0){if(r==="tokens"&&nu(t.tokens)&&nu(n)){t.tokens={...t.tokens,...n};continue}t[r]=n}}function nu(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function su(t,e){if(e==="json")return JSON.stringify(t,null,2);let{messages:r,...n}=t,s=[JSON.stringify(n)];for(let i of r)s.push(JSON.stringify(i));return s.join(`
|
|
73
73
|
`)+`
|
|
74
74
|
`}var to=O(()=>{"use strict"});import{createHash as Ty}from"node:crypto";import{readdir as $r,readFile as iu,stat as ts,unlink as Sy}from"node:fs/promises";import{join as xe,basename as wy,dirname as vy}from"node:path";import{cwd as Iy}from"node:process";function ro(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function ou(t){return t==="user"}function no(t){return t==="gemini"||t==="assistant"}function xt(t,e=new Date(0)){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function xy(t){return`${t.sessionId}\0${t.cwd}`}function by(t,e){let r=t.filePaths??[t.filePath],n=e.filePaths??[e.filePath],s=[...new Set([...r,...n])],i=e.modifiedAt.getTime()>=t.modifiedAt.getTime()?e:t;return{...i,createdAt:t.createdAt.getTime()<=e.createdAt.getTime()?t.createdAt:e.createdAt,modifiedAt:i.modifiedAt,filePath:i.filePath,filePaths:s}}function rs(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function au(t){let e=0,r=0,n=0,s=0,i=0,o;for(let a of t){if(!no(a.type)||!a.tokens)continue;let l=rs(a.tokens.input),c=rs(a.tokens.cached),d=Math.max(l-c,0),u=rs(a.tokens.output),f=rs(a.tokens.thoughts);e+=l,r+=c,n+=u,s+=f,i=l,o={inputTokens:d,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:u,reasoningOutputTokens:f,totalTokens:l+u+f}}return{totalInputTokens:e,totalCachedInputTokens:r,totalOutputTokens:n,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function Ay(t){return Ty("sha256").update(t).digest("hex")}function Ur(t,e){let r=e;for(;r&&!t.has(r);){t.add(r);let n=vy(r);if(n===r)break;r=n}}var ns,lu=O(()=>{"use strict";ce();to();z();ns=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let r=e.geminiDir||xe(W,".gemini");this.geminiProjectsFile=xe(r,"projects.json"),this.geminiTmpDir=xe(r,"tmp");let n=e.claudeDir||xe(W,".claude");this.claudeProjectsDir=xe(n,"projects");let s=[xe(W,".codex"),xe(W,".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=>xe(o,"sessions")),this.extraWorkspacePaths=e.extraWorkspacePaths||[]}getWatchPaths(){return[{directory:this.geminiTmpDir,filePattern:/\.jsonl?$/}]}async discoverSessions(){let e=await this.findSessionFiles(),r=new Map;for(let n of e)try{let s=await this.extractSummary(n);if(!s)continue;let i=xy(s),o=r.get(i);r.set(i,o?by(o,s):s)}catch{}return[...r.values()]}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n;try{n=await this.readSessionFile(r)}catch{return null}if(!n)return null;let s=await se(r),i=[],o=[],a=n.messages||[],l=n.sessionId||this.extractSessionIdFromFilename(r),c=n.projectHash||"",d=await this.resolveWorkspace(c),u,f,p;for(let m of a){let E=xt(m.timestamp),g=m.type,v=J(ro(m.content));if(ou(g)){let T=ro(m.content);T&&o.push(T);let w=v.trim();w&&(u||(u=F(w,80)),f=F(w,80)),i.push({role:"user",timestamp:E,content:w||v});continue}if(no(g)){m.model&&(p=m.model);for(let T of m.thoughts||[]){let w=[T.subject,T.description].filter(Boolean).join(`
|
|
75
|
-
`).trim();w&&i.push({role:"thinking",timestamp:xt(T.timestamp,E),content:J(w)})}i.push({role:"assistant",timestamp:E,content:v,model:m.model});continue}let I=g?`[${g}] `:"";i.push({role:"system",timestamp:E,content:`${I}${v}`.trim()})}let y=xt(n.startTime,s.createdAt),h=xt(n.lastUpdated,s.modifiedAt),_=au(a);return{provider:"gemini",sessionId:l,cwd:d,createdAt:y,modifiedAt:h,model:p,startCommand:"gemini",firstUserMessage:u,lastUserMessage:f,messageCount:i.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:r,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 r=await this.readSessionFile(e);if(!r)return null;let n=await se(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,d,u=0;for(let p of s)if(ou(p.type)){u++;let y=ro(p.content).trim();y&&(l||(l=F(J(y),80)),c=F(J(y),80))}else no(p.type)&&(u++,p.model&&(d=p.model));let f=au(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:xt(r.startTime,n.createdAt),modifiedAt:xt(r.lastUpdated,n.modifiedAt),model:d,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCachedInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,totalReasoningOutputTokens:f.totalReasoningOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async readSessionFile(e){let r=await iu(e,"utf-8");if(Pr(r)==="unknown")return R({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:r.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 es(r)}catch{return null}}extractSessionIdFromFilename(e){let r=wy(e).replace(/\.jsonl?$/,""),n=r.match(/session-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-(.+)$/);return n?n[1]:r}async findSessionFiles(){let e=[],r;try{r=await $r(this.geminiTmpDir)}catch{return e}for(let n of r){let s=xe(this.geminiTmpDir,n,"chats");if(!(await ts(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await $r(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(xe(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await Sy(r),!0):!1}async resolveSessionFile(e){let r=await this.findSessionFiles(),n=[];for(let s of r){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 d=await se(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:xt(i?.lastUpdated,d.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;Ur(e,Iy());for(let n of this.extraWorkspacePaths)Ur(e,n);for(let n of await this.collectGeminiProjectPaths())Ur(e,n);for(let n of await this.collectCodexCwds())Ur(e,n);for(let n of await this.collectClaudeCwds())Ur(e,n);let r=new Map;for(let n of e)r.set(Ay(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await iu(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 r of this.codexSessionDirs){let n=await this.findJsonlFiles(r);for(let s of n){let o=(await ve(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await $r(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=xe(this.claudeProjectsDir,n);if(!(await ts(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await $r(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=xe(s,a),d=(await ve(l,1).catch(()=>[]))[0]?.cwd;d&&e.add(d)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await ts(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await $r(e)}catch{return r}for(let i of s){let o=xe(e,i),a=await ts(o).catch(()=>null);if(a)if(a.isDirectory()){let l=await this.findJsonlFiles(o);r.push(...l)}else i.endsWith(".jsonl")&&r.push(o)}return r}}});import{readFileSync as Ry,writeFileSync as ky,mkdirSync as Ny}from"node:fs";import{join as Ly,dirname as Cy}from"node:path";import{randomUUID as Oy}from"node:crypto";function io(t){return new so(t)}var so,oo=O(()=>{"use strict";lu();Ie();Ge();
|
|
75
|
+
`).trim();w&&i.push({role:"thinking",timestamp:xt(T.timestamp,E),content:J(w)})}i.push({role:"assistant",timestamp:E,content:v,model:m.model});continue}let I=g?`[${g}] `:"";i.push({role:"system",timestamp:E,content:`${I}${v}`.trim()})}let y=xt(n.startTime,s.createdAt),h=xt(n.lastUpdated,s.modifiedAt),_=au(a);return{provider:"gemini",sessionId:l,cwd:d,createdAt:y,modifiedAt:h,model:p,startCommand:"gemini",firstUserMessage:u,lastUserMessage:f,messageCount:i.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:r,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 r=await this.readSessionFile(e);if(!r)return null;let n=await se(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,d,u=0;for(let p of s)if(ou(p.type)){u++;let y=ro(p.content).trim();y&&(l||(l=F(J(y),80)),c=F(J(y),80))}else no(p.type)&&(u++,p.model&&(d=p.model));let f=au(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:xt(r.startTime,n.createdAt),modifiedAt:xt(r.lastUpdated,n.modifiedAt),model:d,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCachedInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,totalReasoningOutputTokens:f.totalReasoningOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async readSessionFile(e){let r=await iu(e,"utf-8");if(Pr(r)==="unknown")return R({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:r.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 es(r)}catch{return null}}extractSessionIdFromFilename(e){let r=wy(e).replace(/\.jsonl?$/,""),n=r.match(/session-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-(.+)$/);return n?n[1]:r}async findSessionFiles(){let e=[],r;try{r=await $r(this.geminiTmpDir)}catch{return e}for(let n of r){let s=xe(this.geminiTmpDir,n,"chats");if(!(await ts(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await $r(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(xe(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await Sy(r),!0):!1}async resolveSessionFile(e){let r=await this.findSessionFiles(),n=[];for(let s of r){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 d=await se(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:xt(i?.lastUpdated,d.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;Ur(e,Iy());for(let n of this.extraWorkspacePaths)Ur(e,n);for(let n of await this.collectGeminiProjectPaths())Ur(e,n);for(let n of await this.collectCodexCwds())Ur(e,n);for(let n of await this.collectClaudeCwds())Ur(e,n);let r=new Map;for(let n of e)r.set(Ay(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await iu(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 r of this.codexSessionDirs){let n=await this.findJsonlFiles(r);for(let s of n){let o=(await ve(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await $r(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=xe(this.claudeProjectsDir,n);if(!(await ts(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await $r(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=xe(s,a),d=(await ve(l,1).catch(()=>[]))[0]?.cwd;d&&e.add(d)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await ts(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await $r(e)}catch{return r}for(let i of s){let o=xe(e,i),a=await ts(o).catch(()=>null);if(a)if(a.isDirectory()){let l=await this.findJsonlFiles(o);r.push(...l)}else i.endsWith(".jsonl")&&r.push(o)}return r}}});import{readFileSync as Ry,writeFileSync as ky,mkdirSync as Ny}from"node:fs";import{join as Ly,dirname as Cy}from"node:path";import{randomUUID as Oy}from"node:crypto";function io(t){return new so(t)}var so,oo=O(()=>{"use strict";lu();Ie();Ge();_e();to();so=class extends K{geminiDir;constructor(e){super({provider:new ns(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",H,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(r,n)=>Pe(r,{...n,acpTool:"gemini"})}),this.geminiDir=e?.geminiDir}openSession(e){return $e({...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(`
|
|
76
76
|
`)}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:Mn,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,r){let n=await this.resolvePath(e);if(!n)return{success:!1,error:`Session file not found for ${e}`};try{let s=Ry(n,"utf-8"),i=Pr(s),o=es(s),a=Oy();o.sessionId=a,o.kind="main";let l=Cy(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=i==="jsonl"?".jsonl":".json",u=`session-${c}-${a.slice(0,8)}${d}`,f=Ly(l,u);return Ny(l,{recursive:!0}),ky(f,su(o,i),"utf-8"),{success:!0,sessionId:a,filePath:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}});import{readdir as cu,readFile as Dy,rm as My,stat as zt}from"node:fs/promises";import{basename as Fy,join as Ce}from"node:path";function Py(t){if(!t)return null;let e={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,reasoningTokens:0},r=!1;for(let n of Object.values(t))n?.usage&&(r=!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 r?e:null}function ao(){return{shutdownTotals:null,assistantOutputSum:0}}function uu(t,e){if(e.type==="assistant.message"){let r=e.data?.outputTokens;typeof r=="number"&&(t.assistantOutputSum+=r,t.lastAssistantOutputTokens=r)}else if(e.type==="session.shutdown"){let r=Py(e.data?.modelMetrics);r&&(t.shutdownTotals=r)}}function du(t){let e=t.shutdownTotals,r=t.lastAssistantOutputTokens!==void 0?{outputTokens:t.lastAssistantOutputTokens}:void 0;return{totalInputTokens:e?.inputTokens,totalCachedInputTokens:e?.cacheReadTokens,totalCacheWriteInputTokens:e?.cacheWriteTokens,totalOutputTokens:e?.outputTokens??(t.lastAssistantOutputTokens===void 0?void 0:t.assistantOutputSum),totalReasoningOutputTokens:e?.reasoningTokens,lastTokenUsage:r}}function $y(t){let e={};for(let r of t.split(`
|
|
77
77
|
`)){let n=r.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 bt(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function Uy(t){let e=0,r=ao(),n;for await(let s of re(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=F(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;uu(r,s)}return{messageCount:e,tokens:r,lastUserMessage:n}}function jy(t){let e=Wy(t),r=new Map;for(let n of t){if(n.role!=="tool_use"||n.toolCallId===void 0)continue;if(n.toolName==="bash"){let l=e.get(n.toolCallId),d=[l?.content,l?.toolDetailedContent].filter(f=>typeof f=="string").join(`
|
|
78
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(d===void 0)continue;let u=`copilot-shell:${d}:${n.toolCallId}`;r.set(d,u),n.backgroundTaskId=u,l!==void 0&&(l.backgroundTaskId=u);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=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function Wy(t){let e=new Map;for(let r of t)r.role==="tool_result"&&r.toolCallId!==void 0&&e.set(r.toolCallId,r);return e}var ss,mu=O(()=>{"use strict";ce();ss=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||Ce(W,".copilot");this.sessionStateDir=Ce(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await cu(this.sessionStateDir)}catch{return e}for(let n of r){let s=Ce(this.sessionStateDir,n);if((await zt(s).catch(()=>null))?.isDirectory())try{let o=await this.extractSummary(s,n);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.resolveSessionDir(e);if(!r)return null;let n=await this.readWorkspaceYaml(r),s=Ce(r,"events.jsonl"),i=await zt(s).catch(()=>null),o=i?s:Ce(r,"workspace.yaml"),a=await se(i?s:r),l=[],c=[],d=n?.cwd||"(unknown workspace)",u,f,p,y,h,_,m=n?.id||Fy(r)||e,E=ao();if(i)for await(let g of re(s)){let v=bt(g.timestamp)||a.modifiedAt;if(uu(E,g),g.type==="session.start"&&g.data){g.data.sessionId&&(m=g.data.sessionId),g.data.copilotVersion&&(f=g.data.copilotVersion),g.data.startTime&&(_=bt(g.data.startTime)),g.data.selectedModel&&(u=g.data.selectedModel),g.data.context&&(g.data.context.cwd&&(d=g.data.context.cwd),g.data.context.branch&&(p=g.data.context.branch));continue}if(g.type==="session.model_change"&&g.data?.newModel){u=g.data.newModel;continue}if(g.type==="user.message"&&g.data){let I=g.data.content||"";I&&c.push(I);let T=I.trim();T&&(y||(y=F(T,80)),h=F(T,80)),l.push({role:"user",timestamp:v,content:J(T||I)});continue}if(g.type==="assistant.message"&&g.data){let I=(g.data.content||"").trim();if(I&&l.push({role:"assistant",timestamp:v,content:J(I),model:u}),g.data.toolRequests)for(let T of g.data.toolRequests)l.push({role:"tool_use",timestamp:v,content:T.name||"unknown tool",toolName:T.name,toolInput:T.arguments?JSON.stringify(T.arguments,null,2):void 0,toolInputData:ke(T.arguments),toolCallId:T.toolCallId});continue}if(g.type==="tool.execution_complete"&&g.data){let I=g.data.result?.content||"",T=g.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:v,content:J(I),toolDetailedContent:T?J(T):void 0,toolCallId:g.data.toolCallId});continue}if(g.type==="assistant.reasoning"&&g.data?.content){l.push({role:"thinking",timestamp:v,content:J(g.data.content)});continue}if(g.type==="session.error"||g.type==="session.warning"||g.type==="session.info"||g.type==="system.message"){let I=g.data?.message||"";I.trim()&&l.push({role:"system",timestamp:v,content:J(I)});continue}}if(!y){let g=(n?.summary||"").trim();g&&(y=F(g,80))}return jy(l),{provider:"copilot",sessionId:m,cwd:d,createdAt:_??bt(n?.created_at)??a.createdAt,modifiedAt:bt(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",gitBranch:p,firstUserMessage:y,lastUserMessage:h,messageCount:l.filter(g=>g.role==="user"||g.role==="assistant").length,filePath:o,...du(E),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=Ce(e,"events.jsonl"),i=await zt(s).catch(()=>null),o=i?s:Ce(e,"workspace.yaml"),a=await se(i?s:e),l=i?await ve(s,20):[],c=n?.id||r,d=n?.cwd||"(unknown workspace)",u,f,p,y,h;for(let m of l)if(m.type==="session.start"&&m.data&&(m.data.sessionId&&(c=m.data.sessionId),m.data.copilotVersion&&(f=m.data.copilotVersion),m.data.startTime&&(p=bt(m.data.startTime)),m.data.selectedModel&&(u=m.data.selectedModel),m.data.context?.cwd&&(d=m.data.context.cwd)),m.type==="session.model_change"&&m.data?.newModel&&(u||(u=m.data.newModel)),m.type==="user.message"&&m.data){let E=(m.data.content||"").trim();E&&(y||(y=F(E,80)),h=F(E,80))}if(!y){let m=(n?.summary||"").trim();m&&(y=F(m,80))}let _=i?await Uy(s):{messageCount:0,tokens:ao()};return{provider:"copilot",sessionId:c,cwd:d,createdAt:p??bt(n?.created_at)??a.createdAt,modifiedAt:bt(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",firstUserMessage:y,lastUserMessage:_.lastUserMessage??h,messageCount:_.messageCount,filePath:o,...du(_.tokens)}}async readWorkspaceYaml(e){let r=Ce(e,"workspace.yaml");try{let n=await Dy(r,"utf-8");return $y(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await My(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await cu(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=Ce(this.sessionStateDir,e);if((await zt(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=Ce(this.sessionStateDir,s);(await zt(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=Ce(this.sessionStateDir,s);if(!(await zt(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 co(t){return new lo(t)}var lo,uo=O(()=>{"use strict";mu();Ie();Ge();z();
|
|
78
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(d===void 0)continue;let u=`copilot-shell:${d}:${n.toolCallId}`;r.set(d,u),n.backgroundTaskId=u,l!==void 0&&(l.backgroundTaskId=u);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=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function Wy(t){let e=new Map;for(let r of t)r.role==="tool_result"&&r.toolCallId!==void 0&&e.set(r.toolCallId,r);return e}var ss,mu=O(()=>{"use strict";ce();ss=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||Ce(W,".copilot");this.sessionStateDir=Ce(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await cu(this.sessionStateDir)}catch{return e}for(let n of r){let s=Ce(this.sessionStateDir,n);if((await zt(s).catch(()=>null))?.isDirectory())try{let o=await this.extractSummary(s,n);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.resolveSessionDir(e);if(!r)return null;let n=await this.readWorkspaceYaml(r),s=Ce(r,"events.jsonl"),i=await zt(s).catch(()=>null),o=i?s:Ce(r,"workspace.yaml"),a=await se(i?s:r),l=[],c=[],d=n?.cwd||"(unknown workspace)",u,f,p,y,h,_,m=n?.id||Fy(r)||e,E=ao();if(i)for await(let g of re(s)){let v=bt(g.timestamp)||a.modifiedAt;if(uu(E,g),g.type==="session.start"&&g.data){g.data.sessionId&&(m=g.data.sessionId),g.data.copilotVersion&&(f=g.data.copilotVersion),g.data.startTime&&(_=bt(g.data.startTime)),g.data.selectedModel&&(u=g.data.selectedModel),g.data.context&&(g.data.context.cwd&&(d=g.data.context.cwd),g.data.context.branch&&(p=g.data.context.branch));continue}if(g.type==="session.model_change"&&g.data?.newModel){u=g.data.newModel;continue}if(g.type==="user.message"&&g.data){let I=g.data.content||"";I&&c.push(I);let T=I.trim();T&&(y||(y=F(T,80)),h=F(T,80)),l.push({role:"user",timestamp:v,content:J(T||I)});continue}if(g.type==="assistant.message"&&g.data){let I=(g.data.content||"").trim();if(I&&l.push({role:"assistant",timestamp:v,content:J(I),model:u}),g.data.toolRequests)for(let T of g.data.toolRequests)l.push({role:"tool_use",timestamp:v,content:T.name||"unknown tool",toolName:T.name,toolInput:T.arguments?JSON.stringify(T.arguments,null,2):void 0,toolInputData:ke(T.arguments),toolCallId:T.toolCallId});continue}if(g.type==="tool.execution_complete"&&g.data){let I=g.data.result?.content||"",T=g.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:v,content:J(I),toolDetailedContent:T?J(T):void 0,toolCallId:g.data.toolCallId});continue}if(g.type==="assistant.reasoning"&&g.data?.content){l.push({role:"thinking",timestamp:v,content:J(g.data.content)});continue}if(g.type==="session.error"||g.type==="session.warning"||g.type==="session.info"||g.type==="system.message"){let I=g.data?.message||"";I.trim()&&l.push({role:"system",timestamp:v,content:J(I)});continue}}if(!y){let g=(n?.summary||"").trim();g&&(y=F(g,80))}return jy(l),{provider:"copilot",sessionId:m,cwd:d,createdAt:_??bt(n?.created_at)??a.createdAt,modifiedAt:bt(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",gitBranch:p,firstUserMessage:y,lastUserMessage:h,messageCount:l.filter(g=>g.role==="user"||g.role==="assistant").length,filePath:o,...du(E),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=Ce(e,"events.jsonl"),i=await zt(s).catch(()=>null),o=i?s:Ce(e,"workspace.yaml"),a=await se(i?s:e),l=i?await ve(s,20):[],c=n?.id||r,d=n?.cwd||"(unknown workspace)",u,f,p,y,h;for(let m of l)if(m.type==="session.start"&&m.data&&(m.data.sessionId&&(c=m.data.sessionId),m.data.copilotVersion&&(f=m.data.copilotVersion),m.data.startTime&&(p=bt(m.data.startTime)),m.data.selectedModel&&(u=m.data.selectedModel),m.data.context?.cwd&&(d=m.data.context.cwd)),m.type==="session.model_change"&&m.data?.newModel&&(u||(u=m.data.newModel)),m.type==="user.message"&&m.data){let E=(m.data.content||"").trim();E&&(y||(y=F(E,80)),h=F(E,80))}if(!y){let m=(n?.summary||"").trim();m&&(y=F(m,80))}let _=i?await Uy(s):{messageCount:0,tokens:ao()};return{provider:"copilot",sessionId:c,cwd:d,createdAt:p??bt(n?.created_at)??a.createdAt,modifiedAt:bt(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",firstUserMessage:y,lastUserMessage:_.lastUserMessage??h,messageCount:_.messageCount,filePath:o,...du(_.tokens)}}async readWorkspaceYaml(e){let r=Ce(e,"workspace.yaml");try{let n=await Dy(r,"utf-8");return $y(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await My(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await cu(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=Ce(this.sessionStateDir,e);if((await zt(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=Ce(this.sessionStateDir,s);(await zt(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=Ce(this.sessionStateDir,s);if(!(await zt(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 co(t){return new lo(t)}var lo,uo=O(()=>{"use strict";mu();Ie();Ge();z();_e();lo=class extends K{copilotDir;constructor(e){super({provider:new ss(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",H,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>Pe(r,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return $e({...e,env:this.copilotDir!==void 0?{...e.env??process.env,COPILOT_HOME:this.copilotDir}:e.env,binary:"copilot",acpTool:"copilot"})}async seed(e,r){let n=await super.seed(e,r);if(r?.model===void 0||r.model.trim().length===0)return n;let s="copilot seed does not implement per-session model selection";return Te({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});function fo(){return new mo}var mo,po=O(()=>{"use strict";Yn();Ie();Ge();_e();mo=class extends K{constructor(){super({provider:new Kt,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",H],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>Pe(e,{...r,acpTool:"opencode"})})}openSession(e){return $e({...e,binary:"opencode",acpTool:"opencode"})}seedArgsFor(e){let r=["run"];return e?.model&&r.push("--model",e.model),e?.effort&&r.push("--variant",e.effort),r.push(e?.prompt??H),r}}});import{appendFile as By,mkdir as Hy,readFile as fu,readdir as pu,rm as Xy,stat as hu}from"node:fs/promises";import{basename as qy,dirname as Gy,isAbsolute as gu,join as At,relative as Jy,resolve as ho}from"node:path";function go(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function zy(t){return typeof t=="number"?new Date(t):go(t)??new Date(0)}function _u(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
|
|
79
79
|
`).trim():""}function yu(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function Qy(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:yu(t)??""}function Zy(t){let e=eE(t),r=new Set;for(let n of t){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&&(r.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of t){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"||!r.has(s))continue;n.backgroundTaskId=s;let i=e.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function eE(t){let e=new Map;for(let r of t)r.role==="tool_result"&&r.toolCallId!==void 0&&e.set(r.toolCallId,r);return e}var Vy,Ky,Yy,is,Eu=O(()=>{"use strict";ce();Vy="1.4",Ky="1.5",Yy=new Set([Vy,Ky]),is=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=ho(e?.kimiHome??process.env.KIMI_CODE_HOME??At(W,".kimi-code")),this.sessionsDir=At(this.homeDir,"sessions")}async discoverSessions(){let e=[];for(let r of await this.sessionFiles())try{let n=await this.summary(r);n&&e.push(n)}catch{}return e.sort((r,n)=>n.modifiedAt.getTime()-r.modifiedAt.getTime())}async loadSession(e){let r=await this.findSession(e);if(!r)return null;let n=await this.summary(r);if(!n)return null;let s=await this.parseWire(r.wirePath);return{...n,messages:s.messages,userPrompts:s.userPrompts}}async resolveSessionPath(e){return(await this.findSession(e))?.wirePath??null}async deleteSession(e){let r=await this.findSession(e);return r?(await Xy(r.sessionDir,{recursive:!0,force:!0}),await Hy(Gy(this.indexPath()),{recursive:!0,mode:448}),await By(this.indexPath(),`${JSON.stringify({sessionId:r.sessionId,deleted:!0})}
|
|
80
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return At(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),r=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&r.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let n;try{n=await pu(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=At(this.sessionsDir,s.name),o;try{o=await pu(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=At(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await fu(this.indexPath(),"utf-8")}catch{return new Map}let r=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?r.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&r.set(s.sessionId,{sessionId:s.sessionId,sessionDir:ho(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:At(r,"state.json"),wirePath:At(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!gu(e)||qy(e)!==r)return!1;let n=Jy(this.sessionsDir,ho(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!gu(n)}async findSession(e){let r=await this.sessionFiles(),n=r.find(i=>i.sessionId===e);if(n)return n;let s=r.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let r=JSON.parse(await fu(e,"utf-8"));return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}async summary(e){let r=await this.readState(e.statePath);if(!r)return null;let n;try{n=await hu(e.wirePath)}catch{return null}let s=await hu(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=go(r.createdAt)??s.birthtime,a=go(r.updatedAt)??(s.mtime>n.mtime?s.mtime:n.mtime);return{provider:"kimi",sessionId:e.sessionId,slug:r.title,cwd:r.workDir??e.indexedWorkDir??"(unknown)",createdAt:o,modifiedAt:a,model:i.model,startCommand:"kimi",firstUserMessage:i.firstUserMessage,lastUserMessage:i.lastUserMessage??(r.lastPrompt?F(r.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 r=[],n=[],s=new Set,i=!0,o,a,l,c=0,d=0,u=0,f=0,p=!1,y=0,h,_;for await(let m of re(e)){let E=zy(m.time??m.created_at);if(i&&(i=!1,m.type==="metadata"&&!Yy.has(m.protocol_version))){let v=`Kimi transcript wire protocol version ${JSON.stringify(m.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:E,content:v}],userPrompts:[],messageCount:1,firstUserMessage:v,lastUserMessage:v}}if((m.type==="config.update"||m.type==="profile.bind")&&m.modelAlias&&(o=m.modelAlias),m.type==="usage.record"){m.model&&(o=m.model),p||=m.usage!==void 0;let v=m.usage?.inputOther??0,I=m.usage?.inputCacheRead??0,T=m.usage?.inputCacheCreation??0,w=m.usage?.output??0;c+=v,d+=I,u+=T,f+=w,m.usageScope==="turn"&&(h=v+I+T,_={inputTokens:v,cachedInputTokens:I,cacheWriteInputTokens:T,outputTokens:w,totalTokens:h+w});continue}if(m.type==="turn.prompt"&&m.origin?.kind==="user"){let v=_u(m.input);v&&((!m.promptId||!s.has(m.promptId))&&(n.push(v),m.promptId&&s.add(m.promptId)),a??=F(v,80),l=F(v,80),r.push({role:"user",timestamp:E,content:v}),y++);continue}if(m.type==="turn.steer"){let v=_u(m.input);v&&(r.push({role:"system",timestamp:E,content:v}),y++);continue}if(m.type!=="context.append_loop_event"||!m.event)continue;let g=m.event;g.type==="content.part"&&g.part?.type==="text"&&g.part.text?(r.push({role:"assistant",timestamp:E,content:g.part.text,model:o}),y++):g.type==="content.part"&&g.part?.type==="think"&&g.part.think?r.push({role:"thinking",timestamp:E,content:g.part.think,model:o}):g.type==="tool.call"?r.push({role:"tool_use",timestamp:E,content:g.name??"tool",toolName:g.name,toolInput:yu(g.args),toolInputData:ke(g.args),toolCallId:g.toolCallId,model:o}):g.type==="tool.result"&&r.push({role:"tool_result",timestamp:E,content:Qy(g.result),toolCallId:g.toolCallId,model:o})}return Zy(r),{messages:r,userPrompts:n,messageCount:y,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:p?c:void 0,totalCachedInputTokens:p?d:void 0,totalCacheWriteInputTokens:p?u:void 0,totalOutputTokens:p?f:void 0,lastInputTokens:h,lastTokenUsage:_}}}});function yo(t){return new _o(t)}var _o,Eo=O(()=>{"use strict";Eu();Ie();Ge();
|
|
80
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return At(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),r=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&r.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let n;try{n=await pu(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=At(this.sessionsDir,s.name),o;try{o=await pu(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=At(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await fu(this.indexPath(),"utf-8")}catch{return new Map}let r=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?r.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&r.set(s.sessionId,{sessionId:s.sessionId,sessionDir:ho(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:At(r,"state.json"),wirePath:At(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!gu(e)||qy(e)!==r)return!1;let n=Jy(this.sessionsDir,ho(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!gu(n)}async findSession(e){let r=await this.sessionFiles(),n=r.find(i=>i.sessionId===e);if(n)return n;let s=r.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let r=JSON.parse(await fu(e,"utf-8"));return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}async summary(e){let r=await this.readState(e.statePath);if(!r)return null;let n;try{n=await hu(e.wirePath)}catch{return null}let s=await hu(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=go(r.createdAt)??s.birthtime,a=go(r.updatedAt)??(s.mtime>n.mtime?s.mtime:n.mtime);return{provider:"kimi",sessionId:e.sessionId,slug:r.title,cwd:r.workDir??e.indexedWorkDir??"(unknown)",createdAt:o,modifiedAt:a,model:i.model,startCommand:"kimi",firstUserMessage:i.firstUserMessage,lastUserMessage:i.lastUserMessage??(r.lastPrompt?F(r.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 r=[],n=[],s=new Set,i=!0,o,a,l,c=0,d=0,u=0,f=0,p=!1,y=0,h,_;for await(let m of re(e)){let E=zy(m.time??m.created_at);if(i&&(i=!1,m.type==="metadata"&&!Yy.has(m.protocol_version))){let v=`Kimi transcript wire protocol version ${JSON.stringify(m.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:E,content:v}],userPrompts:[],messageCount:1,firstUserMessage:v,lastUserMessage:v}}if((m.type==="config.update"||m.type==="profile.bind")&&m.modelAlias&&(o=m.modelAlias),m.type==="usage.record"){m.model&&(o=m.model),p||=m.usage!==void 0;let v=m.usage?.inputOther??0,I=m.usage?.inputCacheRead??0,T=m.usage?.inputCacheCreation??0,w=m.usage?.output??0;c+=v,d+=I,u+=T,f+=w,m.usageScope==="turn"&&(h=v+I+T,_={inputTokens:v,cachedInputTokens:I,cacheWriteInputTokens:T,outputTokens:w,totalTokens:h+w});continue}if(m.type==="turn.prompt"&&m.origin?.kind==="user"){let v=_u(m.input);v&&((!m.promptId||!s.has(m.promptId))&&(n.push(v),m.promptId&&s.add(m.promptId)),a??=F(v,80),l=F(v,80),r.push({role:"user",timestamp:E,content:v}),y++);continue}if(m.type==="turn.steer"){let v=_u(m.input);v&&(r.push({role:"system",timestamp:E,content:v}),y++);continue}if(m.type!=="context.append_loop_event"||!m.event)continue;let g=m.event;g.type==="content.part"&&g.part?.type==="text"&&g.part.text?(r.push({role:"assistant",timestamp:E,content:g.part.text,model:o}),y++):g.type==="content.part"&&g.part?.type==="think"&&g.part.think?r.push({role:"thinking",timestamp:E,content:g.part.think,model:o}):g.type==="tool.call"?r.push({role:"tool_use",timestamp:E,content:g.name??"tool",toolName:g.name,toolInput:yu(g.args),toolInputData:ke(g.args),toolCallId:g.toolCallId,model:o}):g.type==="tool.result"&&r.push({role:"tool_result",timestamp:E,content:Qy(g.result),toolCallId:g.toolCallId,model:o})}return Zy(r),{messages:r,userPrompts:n,messageCount:y,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:p?c:void 0,totalCachedInputTokens:p?d:void 0,totalCacheWriteInputTokens:p?u:void 0,totalOutputTokens:p?f:void 0,lastInputTokens:h,lastTokenUsage:_}}}});function yo(t){return new _o(t)}var _o,Eo=O(()=>{"use strict";Eu();Ie();Ge();_e();_o=class extends K{kimiHome;constructor(e){super({provider:new is(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",H,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(r,n)=>Pe(r,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return $e({...e,env:this.kimiHome!==void 0?{...e.env??process.env,KIMI_CODE_HOME:this.kimiHome}:e.env,binary:"kimi",acpTool:"kimi"})}seedArgsFor(e){let r=[];return e?.model&&r.push("--model",e.model),r.push("-p",e?.prompt??H,"--output-format","stream-json"),r}}});import{spawn as tE}from"node:child_process";import{mkdirSync as rE}from"node:fs";function So(t){return new To(t)}async function nE(t,e){let r=Date.now(),n=Tu({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});de("lmplayer",n,e.permissionMode??"yolo");let s=await wu(e.binary,n,{cwd:e.cwd,env:ue(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(Su(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-r}}function Tu(t){let e=["run"];return t.model&&e.push("--model",t.model),t.sessionId&&e.push("--session",t.sessionId),t.formatJson&&e.push("--format","json"),t.effort&&e.push("--effort",t.effort),e.push(...ot("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function Su(t){if(t.error)return t.error;let e=Sr(t.stderr).trim();return e?e.slice(0,500):`exit code ${t.code}`}function wu(t,e,r){return new Promise((n,s)=>{let i;try{i=tE(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(h){s(h);return}let o="",a="",l="",c,d,u,f=[],p=!1,y=h=>{let _=h.trim();if(!_)return;let m;try{m=JSON.parse(_)}catch{f.push(h),r.onText?.(h);return}if(!Qt(m))return;let E=os(m,!1);c===void 0&&E!==void 0&&(c=E),d=os(m,!0)??d;let g=sE(m);g!==void 0&&(u=g);let v=vu(m);v&&(f.push(v),r.onText?.(v))};i.stdout?.on("data",h=>{let _=h.toString("utf8");o+=_,l+=_;let m=l.indexOf(`
|
|
81
81
|
`);for(;m>=0;){let E=l.slice(0,m);l=l.slice(m+1),y(E),m=l.indexOf(`
|
|
82
|
-
`)}}),i.stderr?.on("data",h=>{a+=h.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",h=>{p||(p=!0,l.length>0&&y(l),n({code:h,stdout:o,stderr:a,sessionId:c??d,text:f.join(""),error:u}))}),i.on("error",h=>{p||(p=!0,s(h))})})}function sE(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(Qt(e)){let r=e.data;if(Qt(r)&&typeof r.message=="string"&&r.message.length>0)return typeof e.name=="string"?`${e.name}: ${r.message}`:r.message;if(typeof e.message=="string"&&e.message.length>0)return e.message}}function vu(t){for(let e of["text","content","delta","output","message"]){let r=t[e];if(typeof r=="string")return r}for(let e of["data","event","payload","part"]){let r=t[e];if(Qt(r)){let n=vu(r);if(n)return n}}}function os(t,e){for(let n of["sessionID","sessionId","session_id"]){let s=t[n];if(typeof s=="string"&&s.length>0)return s}let r=t.session;if(typeof r=="string"&&r.length>0)return r;if(Qt(r)){let n=os(r,e);if(n!==void 0)return n}if(e){let n=t.id;if(typeof n=="string"&&n.length>0)return n}for(let n of["data","event","payload","part"]){let s=t[n];if(Qt(s)){let i=os(s,e);if(i!==void 0)return i}}}function Qt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var To,wo=O(()=>{"use strict";Yn();Ie();
|
|
82
|
+
`)}}),i.stderr?.on("data",h=>{a+=h.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",h=>{p||(p=!0,l.length>0&&y(l),n({code:h,stdout:o,stderr:a,sessionId:c??d,text:f.join(""),error:u}))}),i.on("error",h=>{p||(p=!0,s(h))})})}function sE(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(Qt(e)){let r=e.data;if(Qt(r)&&typeof r.message=="string"&&r.message.length>0)return typeof e.name=="string"?`${e.name}: ${r.message}`:r.message;if(typeof e.message=="string"&&e.message.length>0)return e.message}}function vu(t){for(let e of["text","content","delta","output","message"]){let r=t[e];if(typeof r=="string")return r}for(let e of["data","event","payload","part"]){let r=t[e];if(Qt(r)){let n=vu(r);if(n)return n}}}function os(t,e){for(let n of["sessionID","sessionId","session_id"]){let s=t[n];if(typeof s=="string"&&s.length>0)return s}let r=t.session;if(typeof r=="string"&&r.length>0)return r;if(Qt(r)){let n=os(r,e);if(n!==void 0)return n}if(e){let n=t.id;if(typeof n=="string"&&n.length>0)return n}for(let n of["data","event","payload","part"]){let s=t[n];if(Qt(s)){let i=os(s,e);if(i!==void 0)return i}}}function Qt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var To,wo=O(()=>{"use strict";Yn();Ie();_e();qe();Xe();vi();To=class extends K{constructor(e){super({provider:new Kt({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",H],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:nE})}seedArgsFor(e){return Tu({prompt:e?.prompt??H,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){rE(e,{recursive:!0});let n=this.seedArgsFor(r);de("lmplayer",n);try{let s=await wu(this.binary,n,{cwd:e,env:Jt(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:Su(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 "${H}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as as,readFile as iE,rm as oE}from"node:fs/promises";import{basename as Iu,join as ut}from"node:path";function aE(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function jr(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function lE(t,e){if(!e)return;t.observed=!0;let r=jr(e.promptTokenCount),n=jr(e.cachedContentTokenCount),s=jr(e.candidatesTokenCount),i=jr(e.thoughtsTokenCount);t.totalInputTokens+=r,t.totalCachedInputTokens+=n,t.totalOutputTokens+=s,t.totalReasoningOutputTokens+=i,t.lastInputTokens=r,t.lastTokenUsage={inputTokens:Math.max(r-n,0),cachedInputTokens:n,outputTokens:s,reasoningOutputTokens:i,totalTokens:jr(e.totalTokenCount)||r+s}}function cE(t){return{totalInputTokens:t.observed?t.totalInputTokens:void 0,totalCachedInputTokens:t.observed?t.totalCachedInputTokens:void 0,totalOutputTokens:t.observed?t.totalOutputTokens:void 0,totalReasoningOutputTokens:t.observed?t.totalReasoningOutputTokens:void 0,lastInputTokens:t.lastInputTokens,lastTokenUsage:t.lastTokenUsage}}function xu(t){return t.type==="user"||t.message?.role==="user"}function bu(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function Au(t){let e=t.message;return e?typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(r=>r.type==="text").map(r=>r.text||"").join(`
|
|
83
83
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
84
|
-
`):"":""}function Ru(t){return t.model||t.message?.model}function dE(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:Nu(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Wr(t,e=!1){if(t!==void 0){if(typeof t=="string")return t;try{return JSON.stringify(t,null,e?2:void 0)}catch{return String(t)}}}function uE(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Wr(e.output??e.error??t)}return Wr(t)}function Nu(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function ku(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Wr(t.args,!0),toolInputData:ke(t.args),toolCallId:t.id,model:r}}var ls,Lu=O(()=>{"use strict";ce();ls=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||ut(W,".qwen")}async discoverSessions(){let e=ut(this.baseDir,"projects"),r;try{r=await as(e)}catch{return[]}let n=[];for(let s of r){let i=ut(e,s,"chats"),o;try{o=await as(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=ut(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await se(e),i="(unknown)",o,a,l,c,d=0;for await(let u of re(e)){if(n=!0,u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),xu(u)){let f=Au(u).trim();f&&(l||(l=F(f,80)),c=F(f,80),d++)}if(bu(u)){let f=Ru(u);f&&(o=f),d+=dE(u)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=Iu(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await se(e),s="(unknown)",i,o,a,l,c,d,u=[],f=aE();for await(let p of re(e)){if(lE(f,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let y=p.message,h=p.timestamp?new Date(p.timestamp):n.modifiedAt;if(p.type==="tool_result"){let _=Nu(p).filter(m=>m.functionResponse!==void 0);_.length===0&&p.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:h,content:Wr(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let m of _){let E=m.functionResponse,g=uE(E.response),v=Wr(p.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:h,content:v??g??p.toolCallResult?.status??"tool result",toolName:E.name,toolCallId:p.toolCallResult?.callId??E.id,...g!==void 0?{toolDetailedContent:g}:{}})}}else if(xu(p)){let _=Au(p);_.trim()&&(c||(c=F(_.trim(),80)),d=F(_.trim(),80)),u.push({role:"user",timestamp:h,content:_})}else if(bu(p)){let _=Ru(p);if(_&&(i=_),Array.isArray(y.content))for(let m of y.content)m.type==="text"&&m.text?u.push({role:"assistant",timestamp:h,content:m.text,model:_}):m.type==="thinking"&&m.thinking?u.push({role:"thinking",timestamp:h,content:m.thinking}):m.functionCall&&u.push(ku(m.functionCall,h,_));else if(typeof y.content=="string")u.push({role:"assistant",timestamp:h,content:y.content,model:_});else if(Array.isArray(y.parts))for(let m of y.parts)if(m.thought||m.type==="thinking"){let E=m.thinking||m.text;E&&u.push({role:"thinking",timestamp:h,content:E})}else m.functionCall?u.push(ku(m.functionCall,h,_)):m.text&&u.push({role:"assistant",timestamp:h,content:m.text,model:_})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...cE(f),messages:u}}async resolveSessionPath(e){let r=ut(this.baseDir,"projects");try{let n=await as(r),s=[];for(let i of n){let o=ut(r,i,"chats",`${e}.jsonl`);try{return await iE(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=ut(r,i,"chats"),a;try{a=await as(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Iu(l,".jsonl").startsWith(e)&&s.push(ut(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{return await oE(r),!0}catch{return!1}}}});function Io(){return new vo}var vo,xo=O(()=>{"use strict";Lu();Ie();Ge();ge();vo=class extends K{constructor(){super({provider:new ls,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:zn})}openSession(e){return Qn({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Cu,readFile as Ou,rm as Du,stat as Mu}from"node:fs/promises";import{basename as bo,join as Ue}from"node:path";import{fileURLToPath as mE}from"node:url";async function fE(t){let e=await Promise.all(t.map(r=>se(r)));return{createdAt:new Date(Math.min(...e.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(r=>r.modifiedAt.getTime())))}}function pE(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Fu(t){return t.type==="USER_INPUT"}function Pu(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function hE(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function $u(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function Uu(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function gE(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function _E(t){for await(let e of re(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=yE(s);if(i)return i}let n=EE(e.content);if(n)return n}return null}function yE(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,r=e.Cwd??e.cwd??e.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function EE(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function TE(t,e){if(t.status!=="RUNNING"||!t.content)return;let r=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(t.content);if(!(!r||r[1]!==e)&&!(t.step_index===void 0||Number(r[3])!==t.step_index))return r[2]}function SE(t,e){let r=new Set;for(let n of e){let s=wE(t,r,n);if(!s)continue;r.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 wE(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:bE(r.event.content);if(n!==void 0)return ju(t.filter(i=>!e.has(i)&&AE(i)===n),r.event.step_index);let s=xE(r.event);if(s!==void 0)return ju(t.filter(i=>!e.has(i)&&vE(i.name,r.event.type)&&Bu(IE(i))===s),r.event.step_index)}function ju(t,e){if(t.length===0)return;if(t.length===1)return t[0];if(e===void 0)return;let r=t.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 r[0].distance<r[1].distance?r[0].call:void 0}function vE(t,e){return e==="VIEW_FILE"?t==="view_file":e!=="CODE_ACTION"?!1:t==="write_to_file"||t==="replace_file_content"||t==="multi_replace_file_content"}function IE(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function xE(t){if(!t.content)return;let e;return t.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(t.content)?.[1]:t.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(t.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(t.content)?.[1]),Bu(e)}function Bu(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return mE(e)}catch{return}}function bE(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function AE(t){if(t.name==="run_command"){let e=t.input?.CommandLine;return typeof e=="string"?e:void 0}if(t.name==="schedule"){let e=t.input?.DurationSeconds,r=t.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof r!="string"?void 0:`Timer: ${e}s, Prompt: ${r}`}}function Wu(t){if(t.endsWith(".db"))return bo(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var cs,Hu=O(()=>{"use strict";ce();cs=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Ue(W,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Ue(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Ue(this.baseDir,"conversations"),r;try{r=await Cu(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=bo(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Ue(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return Ue(this.baseDir,"brain",e,".system_generated","logs",r?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let r of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await Mu(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await fE([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of re(n)){let f=Uu(u.content);if(f&&(a=f),Fu(u)){let p=$u(u.content).trim();p&&(l||(l=F(p,80)),c=F(p,80)),d++}else Pu(u)&&u.content&&d++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=Wu(r);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,d=[],u=[];if(i)for await(let f of re(i)){let p=pE(f.created_at,s.modifiedAt),y=Uu(f.content);if(y&&(a=y),Fu(f)){let h=$u(f.content),_=h.trim();_&&(l||(l=F(_,80)),c=F(_,80)),o.push({role:"user",timestamp:p,content:h});continue}if(Array.isArray(f.tool_calls))for(let h of f.tool_calls){let _=h.name||"tool",m=gE(h.args),E=ke(h.args),g={role:"tool_use",timestamp:p,content:m,toolName:_,toolInput:m,toolInputData:E};o.push(g),d.push({name:_,stepIndex:f.step_index,input:E,message:g})}if(Pu(f)&&f.content)o.push({role:"assistant",timestamp:p,content:f.content,model:a});else if(hE(f)&&f.content){let h=TE(f,n),_=h===void 0?null:await this.readTaskLog(n,h),m={role:"tool_result",timestamp:_?.modifiedAt??p,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:h,..._===null?{}:{toolDetailedContent:_.content}};o.push(m),u.push({event:f,message:m})}f.thinking&&o.push({role:"thinking",timestamp:p,content:f.thinking})}return SE(d,u),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(f=>f.role==="user"||f.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await Mu(r),r}catch{}let n=Ue(this.baseDir,"conversations");try{let s=[];for(let i of await Cu(n)){if(!i.endsWith(".db"))continue;bo(i,".db").startsWith(e)&&s.push(Ue(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;let n=Wu(r);return n?(await Du(this.conversationPath(n),{force:!0}),await Du(Ue(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,r){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(r){let s=await _E(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Ue(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await Ou(r,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}async readTaskLog(e,r){if(!/^task-\d+$/.test(r))return null;let n=Ue(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([Ou(n,"utf8"),se(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as RE}from"node:child_process";import{StringDecoder as Xu}from"node:string_decoder";function ds(t){return async(e,r)=>{let n=Date.now(),s=t.buildArgs(e,r);t.assertArgs?.(s,r),r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await kE(t.label,r.binary,s,{cwd:r.cwd,env:ue(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function kE(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=RE(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(f){i(f);return}let a="",l="",c=new Xu("utf8"),d=new Xu("utf8");o.stdout?.on("data",f=>{a+=c.write(f)}),o.stderr?.on("data",f=>{l+=d.write(f)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",f=>{n.signal?.removeEventListener("abort",u),i(f)}),o.on("close",(f,p)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),f===0){s({stdout:a,stderr:l});return}let y=p?`signal ${p}`:`exit code ${f}`,h=l.trim()||a.trim();i(new Error(`${t} failed (${y})${h?`: ${h}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var Ao=O(()=>{"use strict";Xe()});function ko(t){return new Ro(t)}function LE(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Ro,NE,No=O(()=>{"use strict";Hu();Ie();ge();qe();Ao();Ro=class extends K{constructor(e){super({provider:new cs(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:NE})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}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}`}}},NE=ds({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",LE(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>de("agy",t,e.permissionMode??"yolo")})});import CE from"node:zlib";function WE(t,e){return t[e]===DE&&t[e+1]===ME&&t[e+2]===FE&&t[e+3]===PE}function qu(t,e){return(t[e]&240)===80&&t[e+1]===$E&&t[e+2]===UE&&t[e+3]===jE}function BE(t,e){if(qu(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!WE(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,d=(c&1)!==0,u=c>>1&3,f=c>>3;if(r+=3,u===3||(r+=u===1?1:f,r>t.length))return;if(d)break}if(o&&(r+=4),!(r>t.length))return r-e}}function HE(t){let e=[],r=0;for(;r+4<=t.length;){let n=BE(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function us(t){let e=[];for(let r of HE(t))qu(r,0)||e.push(OE(r).toString("utf8"));return e.join("")}var OE,DE,ME,FE,PE,$E,UE,jE,Lo=O(()=>{"use strict";OE=CE.zstdDecompressSync,DE=40,ME=181,FE=47,PE=253,$E=42,UE=77,jE=24});import{readdir as Co,rm as XE,stat as qE}from"node:fs/promises";import{join as mt}from"node:path";function GE(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Oo(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string"&&e.push(r.text);return e.join("")}function JE(t){if(!Array.isArray(t))return[];let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="reasoning"&&typeof r.text=="string"&&e.push(r.text);return e}function Gu(t){let e=[];for(let r of t){let n=r.data??{},s=r.time?new Date(r.time):new Date(0);if(r.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:Oo(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of JE(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Oo(i?.content),model:i?.source?.model})}else if(r.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(r.type==="tool/result"){let i=n,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:Oo(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function VE(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type==="turn/end")return r.data?.reason?.kind==="completed"?"complete":"aborted";if(r.type==="turn/start")return"in_progress"}}function Ju(t,e,r){let n=t.find(p=>p.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 p of t)if(p.type==="request/header"){let y=p.data?.header;y?.config?.model&&(a=y.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,f=r.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:f[0]?.content,lastUserMessage:f.at(-1)?.content,messageCount:r.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...KE(t)}}function KE(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let d=ms(c.inputTokens),u=ms(c.cacheReadTokens),f=ms(c.outputTokens),p=ms(c.reasoningTokens);r+=d,n+=u,s+=f,i+=p,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:f,reasoningOutputTokens:p,totalTokens:d+u+f}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function ms(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var fs,Vu=O(()=>{"use strict";ce();Lo();fs=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||mt(W,".dsh");this.sessionsDir=mt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Co(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Co(mt(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 r=await this.findSessionDir(e);if(!r)return null;let n=await this.readRecords(r.cwdDir,r.sessionDir);if(n.length===0)return null;let s=Gu(n),i=Ju(n,r.filePath,s);return i?{...i,turnStatus:VE(n),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let r=await this.findSessionDir(e);return r?(await XE(mt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return mt(this.sessionsDir,GE(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Co(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=mt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await qE(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=mt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=us(i),a=[];for(let l of o.split(`
|
|
84
|
+
`):"":""}function Ru(t){return t.model||t.message?.model}function dE(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:Nu(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Wr(t,e=!1){if(t!==void 0){if(typeof t=="string")return t;try{return JSON.stringify(t,null,e?2:void 0)}catch{return String(t)}}}function uE(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Wr(e.output??e.error??t)}return Wr(t)}function Nu(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function ku(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Wr(t.args,!0),toolInputData:ke(t.args),toolCallId:t.id,model:r}}var ls,Lu=O(()=>{"use strict";ce();ls=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||ut(W,".qwen")}async discoverSessions(){let e=ut(this.baseDir,"projects"),r;try{r=await as(e)}catch{return[]}let n=[];for(let s of r){let i=ut(e,s,"chats"),o;try{o=await as(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=ut(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await se(e),i="(unknown)",o,a,l,c,d=0;for await(let u of re(e)){if(n=!0,u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),xu(u)){let f=Au(u).trim();f&&(l||(l=F(f,80)),c=F(f,80),d++)}if(bu(u)){let f=Ru(u);f&&(o=f),d+=dE(u)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=Iu(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await se(e),s="(unknown)",i,o,a,l,c,d,u=[],f=aE();for await(let p of re(e)){if(lE(f,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let y=p.message,h=p.timestamp?new Date(p.timestamp):n.modifiedAt;if(p.type==="tool_result"){let _=Nu(p).filter(m=>m.functionResponse!==void 0);_.length===0&&p.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:h,content:Wr(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let m of _){let E=m.functionResponse,g=uE(E.response),v=Wr(p.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:h,content:v??g??p.toolCallResult?.status??"tool result",toolName:E.name,toolCallId:p.toolCallResult?.callId??E.id,...g!==void 0?{toolDetailedContent:g}:{}})}}else if(xu(p)){let _=Au(p);_.trim()&&(c||(c=F(_.trim(),80)),d=F(_.trim(),80)),u.push({role:"user",timestamp:h,content:_})}else if(bu(p)){let _=Ru(p);if(_&&(i=_),Array.isArray(y.content))for(let m of y.content)m.type==="text"&&m.text?u.push({role:"assistant",timestamp:h,content:m.text,model:_}):m.type==="thinking"&&m.thinking?u.push({role:"thinking",timestamp:h,content:m.thinking}):m.functionCall&&u.push(ku(m.functionCall,h,_));else if(typeof y.content=="string")u.push({role:"assistant",timestamp:h,content:y.content,model:_});else if(Array.isArray(y.parts))for(let m of y.parts)if(m.thought||m.type==="thinking"){let E=m.thinking||m.text;E&&u.push({role:"thinking",timestamp:h,content:E})}else m.functionCall?u.push(ku(m.functionCall,h,_)):m.text&&u.push({role:"assistant",timestamp:h,content:m.text,model:_})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...cE(f),messages:u}}async resolveSessionPath(e){let r=ut(this.baseDir,"projects");try{let n=await as(r),s=[];for(let i of n){let o=ut(r,i,"chats",`${e}.jsonl`);try{return await iE(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=ut(r,i,"chats"),a;try{a=await as(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Iu(l,".jsonl").startsWith(e)&&s.push(ut(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{return await oE(r),!0}catch{return!1}}}});function Io(){return new vo}var vo,xo=O(()=>{"use strict";Lu();Ie();Ge();_e();vo=class extends K{constructor(){super({provider:new ls,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:zn})}openSession(e){return Qn({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Cu,readFile as Ou,rm as Du,stat as Mu}from"node:fs/promises";import{basename as bo,join as Ue}from"node:path";import{fileURLToPath as mE}from"node:url";async function fE(t){let e=await Promise.all(t.map(r=>se(r)));return{createdAt:new Date(Math.min(...e.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(r=>r.modifiedAt.getTime())))}}function pE(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Fu(t){return t.type==="USER_INPUT"}function Pu(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function hE(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function $u(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function Uu(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function gE(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function _E(t){for await(let e of re(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=yE(s);if(i)return i}let n=EE(e.content);if(n)return n}return null}function yE(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,r=e.Cwd??e.cwd??e.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function EE(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function TE(t,e){if(t.status!=="RUNNING"||!t.content)return;let r=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(t.content);if(!(!r||r[1]!==e)&&!(t.step_index===void 0||Number(r[3])!==t.step_index))return r[2]}function SE(t,e){let r=new Set;for(let n of e){let s=wE(t,r,n);if(!s)continue;r.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 wE(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:bE(r.event.content);if(n!==void 0)return ju(t.filter(i=>!e.has(i)&&AE(i)===n),r.event.step_index);let s=xE(r.event);if(s!==void 0)return ju(t.filter(i=>!e.has(i)&&vE(i.name,r.event.type)&&Bu(IE(i))===s),r.event.step_index)}function ju(t,e){if(t.length===0)return;if(t.length===1)return t[0];if(e===void 0)return;let r=t.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 r[0].distance<r[1].distance?r[0].call:void 0}function vE(t,e){return e==="VIEW_FILE"?t==="view_file":e!=="CODE_ACTION"?!1:t==="write_to_file"||t==="replace_file_content"||t==="multi_replace_file_content"}function IE(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function xE(t){if(!t.content)return;let e;return t.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(t.content)?.[1]:t.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(t.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(t.content)?.[1]),Bu(e)}function Bu(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return mE(e)}catch{return}}function bE(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function AE(t){if(t.name==="run_command"){let e=t.input?.CommandLine;return typeof e=="string"?e:void 0}if(t.name==="schedule"){let e=t.input?.DurationSeconds,r=t.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof r!="string"?void 0:`Timer: ${e}s, Prompt: ${r}`}}function Wu(t){if(t.endsWith(".db"))return bo(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var cs,Hu=O(()=>{"use strict";ce();cs=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Ue(W,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Ue(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Ue(this.baseDir,"conversations"),r;try{r=await Cu(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=bo(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Ue(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return Ue(this.baseDir,"brain",e,".system_generated","logs",r?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let r of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await Mu(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await fE([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of re(n)){let f=Uu(u.content);if(f&&(a=f),Fu(u)){let p=$u(u.content).trim();p&&(l||(l=F(p,80)),c=F(p,80)),d++}else Pu(u)&&u.content&&d++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=Wu(r);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,d=[],u=[];if(i)for await(let f of re(i)){let p=pE(f.created_at,s.modifiedAt),y=Uu(f.content);if(y&&(a=y),Fu(f)){let h=$u(f.content),_=h.trim();_&&(l||(l=F(_,80)),c=F(_,80)),o.push({role:"user",timestamp:p,content:h});continue}if(Array.isArray(f.tool_calls))for(let h of f.tool_calls){let _=h.name||"tool",m=gE(h.args),E=ke(h.args),g={role:"tool_use",timestamp:p,content:m,toolName:_,toolInput:m,toolInputData:E};o.push(g),d.push({name:_,stepIndex:f.step_index,input:E,message:g})}if(Pu(f)&&f.content)o.push({role:"assistant",timestamp:p,content:f.content,model:a});else if(hE(f)&&f.content){let h=TE(f,n),_=h===void 0?null:await this.readTaskLog(n,h),m={role:"tool_result",timestamp:_?.modifiedAt??p,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:h,..._===null?{}:{toolDetailedContent:_.content}};o.push(m),u.push({event:f,message:m})}f.thinking&&o.push({role:"thinking",timestamp:p,content:f.thinking})}return SE(d,u),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(f=>f.role==="user"||f.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await Mu(r),r}catch{}let n=Ue(this.baseDir,"conversations");try{let s=[];for(let i of await Cu(n)){if(!i.endsWith(".db"))continue;bo(i,".db").startsWith(e)&&s.push(Ue(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;let n=Wu(r);return n?(await Du(this.conversationPath(n),{force:!0}),await Du(Ue(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,r){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(r){let s=await _E(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Ue(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await Ou(r,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}async readTaskLog(e,r){if(!/^task-\d+$/.test(r))return null;let n=Ue(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([Ou(n,"utf8"),se(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as RE}from"node:child_process";import{StringDecoder as Xu}from"node:string_decoder";function ds(t){return async(e,r)=>{let n=Date.now(),s=t.buildArgs(e,r);t.assertArgs?.(s,r),r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await kE(t.label,r.binary,s,{cwd:r.cwd,env:ue(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function kE(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=RE(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(f){i(f);return}let a="",l="",c=new Xu("utf8"),d=new Xu("utf8");o.stdout?.on("data",f=>{a+=c.write(f)}),o.stderr?.on("data",f=>{l+=d.write(f)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",f=>{n.signal?.removeEventListener("abort",u),i(f)}),o.on("close",(f,p)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),f===0){s({stdout:a,stderr:l});return}let y=p?`signal ${p}`:`exit code ${f}`,h=l.trim()||a.trim();i(new Error(`${t} failed (${y})${h?`: ${h}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var Ao=O(()=>{"use strict";Xe()});function ko(t){return new Ro(t)}function LE(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Ro,NE,No=O(()=>{"use strict";Hu();Ie();_e();qe();Ao();Ro=class extends K{constructor(e){super({provider:new cs(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:NE})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}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}`}}},NE=ds({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",LE(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>de("agy",t,e.permissionMode??"yolo")})});import CE from"node:zlib";function WE(t,e){return t[e]===DE&&t[e+1]===ME&&t[e+2]===FE&&t[e+3]===PE}function qu(t,e){return(t[e]&240)===80&&t[e+1]===$E&&t[e+2]===UE&&t[e+3]===jE}function BE(t,e){if(qu(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!WE(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,d=(c&1)!==0,u=c>>1&3,f=c>>3;if(r+=3,u===3||(r+=u===1?1:f,r>t.length))return;if(d)break}if(o&&(r+=4),!(r>t.length))return r-e}}function HE(t){let e=[],r=0;for(;r+4<=t.length;){let n=BE(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function us(t){let e=[];for(let r of HE(t))qu(r,0)||e.push(OE(r).toString("utf8"));return e.join("")}var OE,DE,ME,FE,PE,$E,UE,jE,Lo=O(()=>{"use strict";OE=CE.zstdDecompressSync,DE=40,ME=181,FE=47,PE=253,$E=42,UE=77,jE=24});import{readdir as Co,rm as XE,stat as qE}from"node:fs/promises";import{join as mt}from"node:path";function GE(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Oo(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string"&&e.push(r.text);return e.join("")}function JE(t){if(!Array.isArray(t))return[];let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="reasoning"&&typeof r.text=="string"&&e.push(r.text);return e}function Gu(t){let e=[];for(let r of t){let n=r.data??{},s=r.time?new Date(r.time):new Date(0);if(r.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:Oo(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of JE(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Oo(i?.content),model:i?.source?.model})}else if(r.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(r.type==="tool/result"){let i=n,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:Oo(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function VE(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type==="turn/end")return r.data?.reason?.kind==="completed"?"complete":"aborted";if(r.type==="turn/start")return"in_progress"}}function Ju(t,e,r){let n=t.find(p=>p.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 p of t)if(p.type==="request/header"){let y=p.data?.header;y?.config?.model&&(a=y.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,f=r.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:f[0]?.content,lastUserMessage:f.at(-1)?.content,messageCount:r.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...KE(t)}}function KE(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let d=ms(c.inputTokens),u=ms(c.cacheReadTokens),f=ms(c.outputTokens),p=ms(c.reasoningTokens);r+=d,n+=u,s+=f,i+=p,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:f,reasoningOutputTokens:p,totalTokens:d+u+f}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function ms(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var fs,Vu=O(()=>{"use strict";ce();Lo();fs=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||mt(W,".dsh");this.sessionsDir=mt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Co(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Co(mt(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 r=await this.findSessionDir(e);if(!r)return null;let n=await this.readRecords(r.cwdDir,r.sessionDir);if(n.length===0)return null;let s=Gu(n),i=Ju(n,r.filePath,s);return i?{...i,turnStatus:VE(n),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let r=await this.findSessionDir(e);return r?(await XE(mt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return mt(this.sessionsDir,GE(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Co(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=mt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await qE(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=mt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=us(i),a=[];for(let l of o.split(`
|
|
85
85
|
`))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,r){let n=await this.readRecords(e,r);if(n.length===0)return null;let s=mt(this.sessionsDir,e,r,"session.jsonl.zstd");return Ju(n,s,Gu(n))}}});import{spawn as YE}from"node:child_process";async function ps(t,e=r=>Do.spawn(r)){if(ft){let r=await ft.catch(()=>{});if(r?.alive)return r;ft=void 0}return ft=e(t),ft}async function Br(){if(!ft)return;(await ft.catch(()=>{}))?.shutdown(),ft=void 0}var zE,Ku,Zt,Do,ft,Yu=O(()=>{"use strict";zE=/dsh web:\s*(https?:\/\/\S+)/,Ku=2e4,Zt=class t extends Error{method;detail;constructor(e,r){super(`dsh RPC ${e} failed: ${JSON.stringify(r)}`),this.name="DshRpcCallError",this.method=e,this.detail=r,Object.setPrototypeOf(this,t.prototype)}},Do=class t{baseUrl;child;constructor(e,r){this.baseUrl=e,this.child=r}static forTesting(e){return new t(e,void 0)}async rpc(e,r){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:r})})}catch(a){throw new Zt(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 Zt(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 Zt(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new Zt(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((r,n)=>{let s=YE("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 ${Ku}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},Ku);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let d=zE.exec(o);d&&(i=!0,clearTimeout(l),r(new t(d[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,d)=>{if(i)return;i=!0,clearTimeout(l);let u=d?`signal ${d}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${u}): ${a.slice(0,500)}`))})})}}});import{randomUUID as QE}from"node:crypto";import{existsSync as zu}from"node:fs";import{readFile as ZE,mkdir as eT}from"node:fs/promises";function $o(t){return new Po(t)}function Fo(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function rT(t){let e=t?.kind??"unknown",r=t?.error?.message;return r?`dsh turn ended with reason=${e}: ${r}`:`dsh turn ended with reason=${e} and no assistant text`}function hs(t){return t instanceof Error?t.message:String(t)}async function nT(t){let e=await Qu(t),r=-1;for(let n of e)n.type==="turn/end"&&typeof n.seq=="number"&&n.seq>r&&(r=n.seq);return r}async function Qu(t){let e;try{e=await ZE(t)}catch{return[]}let r=us(e),n=[];for(let s of r.split(`
|
|
86
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function sT(t){let r=t.data?.message?.content;if(typeof r=="string")return r;if(!Array.isArray(r))return"";let n=[];for(let s of r)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&n.push(s.text);return n.join("")}var tT,Mo,Po,Uo=O(()=>{"use strict";Ie();Vu();Lo();Yu();
|
|
86
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function sT(t){let r=t.data?.message?.content;if(typeof r=="string")return r;if(!Array.isArray(r))return"";let n=[];for(let s of r)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&n.push(s.text);return n.join("")}var tT,Mo,Po,Uo=O(()=>{"use strict";Ie();Vu();Lo();Yu();_e();qe();tT=500,Mo=8*60*60*1e3;Po=class extends K{dshProvider;constructor(e){let r=new fs(e);super({provider:r,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=r}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,r){await eT(e,{recursive:!0});let n=`session-${QE()}`,s=Fo(process.env);de("dsh",[],"yolo");try{let i;try{i=await ps(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${hs(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${hs(a)}`}}if(r?.model)try{await i.rpc("session.selectModel",{sessionId:n,provider:"deepseek-official",model:r.model})}catch(a){return{success:!1,error:`session.selectModel("${r.model}") failed: ${hs(a)}`}}let o=r?.prompt??H;try{await this.promptAndWait(i,e,n,o,Mo)}catch(a){return{success:!1,error:`seed turn failed: ${hs(a)}`}}return{success:!0,sessionId:n}}finally{await Br()}}async dshPromptTurn(e,r){let n=Date.now();if(r.bundleSession!==void 0){let o=r.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:r.signal});return{text:a.text,sessionId:a.sessionId,durationMs:a.durationMs,...a.warnings!==void 0?{warnings:a.warnings}:{}}}let s=Fo(r.env??process.env);de("dsh",[],r.permissionMode??"yolo");let i;try{let o=await ps(s);r.model&&(await o.rpc("session.selectModel",{sessionId:r.sessionId,provider:"deepseek-official",model:r.model}),r.onProgress?.({kind:"system",summary:`dsh model set to ${r.model}`})),r.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),i=await this.promptAndWait(o,r.cwd,r.sessionId,e,r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Mo)}finally{await Br()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:r.sessionId,durationMs:Date.now()-n}}async openSession(e){let r=Fo(e.env??process.env);de("dsh",[],e.permissionMode??"yolo");let n=await ps(r),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!zu(s))throw await Br(),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,d=!1,u=!1,f=async()=>{u||(u=!0,await Br())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(p,y={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(d)throw new Error("dsh bundle session has a turn still in flight");if(y.signal?.aborted)throw new Error("Aborted");if(!zu(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);d=!0;let h=Date.now();try{let _=o.promptAndWait(n,e.cwd,i,p,Mo,y.signal);_.catch(()=>{});let m=await Promise.race([_,new Promise((E,g)=>{y.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await f()})().finally(()=>g(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:m,sessionId:i,durationMs:Date.now()-h}}finally{d=!1}},close(){return c!==null||(c=(async()=>{l=!0,await f()})()),c}}}async promptAndWait(e,r,n,s,i,o){let a=this.dshProvider.sessionFilePath(r,n),l=await nT(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 d=await Qu(a),u=d.find(f=>f.type==="turn/end"&&(f.seq??-1)>l);if(u){let f=u.data?.reason,p=[...d].reverse().find(h=>h.type==="assistant/message"),y=p?sT(p):"";if(f?.kind!=="completed"&&!y)throw new Error(rT(f));return y}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(f=>setTimeout(f,tT))}}}});import{existsSync as iT}from"node:fs";import{join as nm,resolve as oT}from"node:path";import{createRequire as aT}from"node:module";function lT(){return jo===null&&(jo=aT(import.meta.url)("node:sqlite").DatabaseSync),jo}function Wo(t={}){return oT(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||nm(W,".hermes"))}function cT(t={}){return nm(Wo(t),"state.db")}function Hr(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function ye(t){return typeof t=="string"&&t.length>0?t:void 0}function dT(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function tm(t){return ye(t.cwd)??ye(dT(t.model_config).cwd)??"(unknown)"}function uT(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function mT(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string")return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function rm(t){let e=t.input_tokens??0,r=t.output_tokens??0,n=t.cache_read_tokens??0,s=t.cache_write_tokens??0,i=t.reasoning_tokens??0;return(t.message_count??0)>0&&e+r+n+s+i>0?{totalInputTokens:e,totalCachedInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:r,totalReasoningOutputTokens:i}:{}}var jo,Zu,em,gs,sm=O(()=>{"use strict";ce();z();jo=null;Zu="acp";em=`id, source, model, model_config, started_at,
|
|
87
87
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
88
88
|
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;gs=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=cT(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!iT(this.dbPath))return null;let e=null;try{return e=new(lT())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(r){return e?.close(),R({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),null}}selectSessionRow(e,r){return e.prepare(`SELECT ${em} FROM sessions WHERE id = ? AND source = ?`).get(r,Zu)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let r=e.prepare(`SELECT ${em} FROM sessions
|
|
89
89
|
WHERE source = ?
|
|
90
90
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
91
|
-
LIMIT ?`).all(Zu,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:
|
|
91
|
+
LIMIT ?`).all(Zu,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:ye(s.title),cwd:tm(s),createdAt:Hr(s.started_at),modifiedAt:Hr(s.last_activity_at??s.started_at),model:ye(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...rm(s)})}return n}catch(r){return R({event:"hermes_discover_sessions_failed",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),[]}finally{e.close()}}activeMessageRows(e,r){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,
|
|
92
92
|
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(r)}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(r)}}previewTexts(e,r){try{let[n,s]=["ASC","DESC"].map(i=>{let o=`SELECT content FROM messages WHERE session_id = ?
|
|
93
|
-
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(r)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(r)}return a?F(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let d=Hr(c.timestamp),u=c.content??"";if(c.role==="user"){u&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(u),u.length>0&&(a||(a=F(u,80)),l=F(u,80)),i.push({role:"user",timestamp:d,content:u||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:d,content:u,toolCallId:_e(c.tool_call_id),toolName:_e(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:_e(n.model),stopReason:_e(c.finish_reason)});for(let f of uT(c.tool_calls)){let p=mT(f.function?.arguments);i.push({role:"tool_use",timestamp:d,content:_e(f.function?.name)??"tool_call",toolName:_e(f.function?.name),toolCallId:_e(f.call_id)??_e(f.id),toolInput:typeof f.function?.arguments=="string"?f.function.arguments:JSON.stringify(f.function?.arguments??{}),toolInputData:ke(p)})}}return{provider:this.name,sessionId:n.id,slug:_e(n.title),cwd:tm(n),createdAt:Hr(n.started_at),modifiedAt:Hr(n.last_activity_at??n.started_at),model:_e(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...rm(n),messages:i,userPrompts:o}}catch(n){return R({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{r.close()}}async resolveSessionPath(e){let r=this.openDb();if(!r)return null;try{return this.selectSessionRow(r,e)?this.dbPath:null}catch{return null}finally{r.close()}}async deleteSession(e){return!1}}});import{mkdir as fT}from"node:fs/promises";function hT(t){return pT.test(t)}function im(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return gT}function Ho(t){return new Bo(t)}var pT,gT,Bo,Xo=O(()=>{"use strict";Ie();sm();Ge();ge();z();pT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;gT="dont_ask";Bo=class extends K{hermesProvider;hermesHome;constructor(e){let r=new gs(e);super({provider:r,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)=>Pe(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:im(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Wo(e)}async openSession(e){return $e({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:im(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await fT(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";R({event:"hermes_effort_ignored",provider:this.name,effort:r.effort,reason:i}),n.push(`hermes seed ignored effort=${r.effort}: ${i}`)}let s;try{s=await this.sendTurn(r?.prompt??H,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return hT(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(R({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 om,rm as _T,stat as yT}from"node:fs/promises";import{join as qo}from"node:path";function Go(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function am(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var _s,lm=O(()=>{"use strict";ce();_s=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||qo(W,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let r of await this.listSessionFiles())try{let n=await this.extractSummary(r);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await om(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=qo(this.baseDir,n);try{if(!(await yT(s)).isDirectory())continue;for(let i of await om(s))i.endsWith(".jsonl")&&r.push(qo(s,i))}catch{}}return r}async readHeader(e){for await(let r of re(e))return r.type==="session"?r:null;return null}async extractSummary(e){let r=await this.readHeader(e);if(!r)return null;let n=await se(e),s,i,o,a=0,l=0,c=0,d=0,u=0,f=0,p=0,y;for await(let h of re(e)){if(h.type==="model_change"&&h.provider&&h.modelId){s=`${h.provider}/${h.modelId}`;continue}if(h.type!=="message"||!h.message)continue;let _=h.message;if(_.provider&&_.model&&(s=`${_.provider}/${_.model}`),_.role==="user"){let m=Go(_).trim();m&&(i||(i=F(m,80)),o=F(m,80)),a++}else if(_.role==="assistant"){a++;let m=_.usage;m&&(l+=m.input??0,c+=m.cacheRead??0,d+=m.cacheWrite??0,u+=m.output??0,f+=m.reasoning??0,p=m.input??0,y={inputTokens:m.input,cachedInputTokens:m.cacheRead,cacheWriteInputTokens:m.cacheWrite,outputTokens:m.output,reasoningOutputTokens:m.reasoning,totalTokens:m.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.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:d,totalOutputTokens:u,totalReasoningOutputTokens:f,lastInputTokens:p,lastTokenUsage:y}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=await this.extractSummary(r);if(!n)return null;let s=[],i=n.model;for await(let o of re(r)){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:Go(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:am(c.arguments),toolName:c.name??"tool",toolInput:am(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Go(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...n,model:i,messages:s}}async resolveSessionPath(e){let r=`_${e}.jsonl`,n=[];for(let s of await this.listSessionFiles()){if(s.endsWith(r))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&n.push(s)}return n.length===1?n[0]:null}async deleteSession(e){let r=await this.resolveSessionPath(e);return r?(await _T(r,{force:!0}),!0):!1}}});function Vo(t){return new Jo(t)}var Jo,ET,Ko=O(()=>{"use strict";lm();Ie();ge();qe();Ao();Jo=class extends K{constructor(e){super({provider:new _s(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:ET})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}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}`}}},ET=ds({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>de("pi",t,e.permissionMode??"yolo")})});import{createHash as TT}from"node:crypto";import{existsSync as ST,mkdirSync as zo,readFileSync as wT,renameSync as vT,rmdirSync as gm,statSync as IT,writeFileSync as xT}from"node:fs";import{dirname as ta,join as cm,resolve as Yo}from"node:path";function bT(t){return TT("sha256").update(t).digest("hex").slice(0,8)}function AT(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function RT(t,e){let r=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(r);return n!==null?n[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function _m(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function ys(t){return Math.max(1,Math.ceil(t.length/4))}function tr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Yo(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?cm(ta(Yo(r)),".lmctl-claude-mock","sessions.json"):cm(Yo(t),".lmctl-claude-mock","sessions.json")}function dm(){return{schemaVersion:1,sessions:{}}}function Xr(t){if(!ST(t))return dm();try{let e=JSON.parse(wT(t,"utf8")),r=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=Qo(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return dm()}}function ym(t,e){zo(ta(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;xT(r,`${JSON.stringify(e,null,2)}
|
|
94
|
-
`,"utf8"),vT(r,t)}function LT(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function CT(t){let e=`${t}.lock`;zo(ta(t),{recursive:!0});let r=Date.now()+um;for(;;)try{return zo(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-IT(e).mtimeMs>kT){try{gm(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${um}ms: ${e}`);LT(NT)}}function OT(t){try{gm(t)}catch{}}function Em(t,e){let r=CT(t);try{return e()}finally{OT(r)}}function DT(t){return{...t,timestamp:t.timestamp.toISOString()}}function MT(t){return{...t,timestamp:new Date(t.timestamp)}}function FT(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(DT)}}function Tm(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(MT)}}function Es(t,e=process.cwd()){let r=er.get(t);if(r!==void 0)return r;let s=Xr(tr(e)).sessions[t];if(s===void 0)return;let i=Tm(s);return er.set(i.sessionId,i),i}function mm(t){er.set(t.sessionId,t);let e=tr(t.cwd);Em(e,()=>{let r=Xr(e);r.sessions[t.sessionId]=FT({...t,filePath:e}),ym(e,r)})}function PT(t,e=process.cwd()){let r=tr(e);return Em(r,()=>{let n=Xr(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],ym(r,n)),s})}function $T(){let t=Xr(tr()),e=Object.values(t.sessions).map(Tm);for(let r of e)er.set(r.sessionId,r);return e}function Qo(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function fm(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Qo(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=Qo(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function pm(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function UT(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=fm(r[t]??r[_m(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=fm(n[s]);if(i!==void 0)return i}}}function hm(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function ra(){return new ea}var er,kT,NT,um,Zo,ea,na=O(()=>{"use strict";er=new Map;kT=5e3,NT=15,um=1e4;Zo=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of $T())e.set(r.sessionId,r);for(let r of er.values())e.set(r.sessionId,r);return[...e.values()].map(hm)}async loadSession(e){let r=Es(e);return r===void 0?null:{...hm(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Es(e)?.filePath??null}async deleteSession(e){let r=er.delete(e),n=PT(e);return r||n}},ea=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Zo;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,r){let n=AT(RT(e,r)),s=`mock-${n}-${bT(`${e}:${n}`)}`,i=new Date,o=tr(e),a=Es(s,e),l=r?.prompt??"ClaudeMock seed",c=ys(l),d={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 d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=ys("ACK: ClaudeMock seeded"),mm(d),{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,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Es(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Xr(tr(r.cwd)),a=UT(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await pm(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${_m(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:r.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=ys(e),s.totalOutputTokens+=ys(c),mm(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await pm(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function pt(t){let e=[Ki({claudeDir:t?.claudeDir}),Zi({codexDir:t?.codexDir,codeDir:t?.codeDir}),io({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),co({copilotDir:t?.copilotDir}),fo(),yo({kimiHome:t?.kimiHome}),So({lmplayerDbPath:t?.lmplayerDbPath}),Io(),ko({agyDir:t?.agyDir}),$o({dshHome:t?.dshHome}),Ho({hermesHome:t?.hermesHome}),Vo({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(ra()),e}var sa=O(()=>{"use strict";Yi();eo();oo();uo();po();Eo();wo();xo();No();Uo();Xo();Ko();na();Yi();eo();oo();uo();po();Eo();wo();xo();No();Uo();Xo();Ko();na()});var Ts,Ss,Sm=O(()=>{"use strict";Ts=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],Ss=["agy","pi","lmplayer"]});var vm={};Wf(vm,{BUNDLE_CAPABLE_PROVIDERS:()=>Ts,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Ss,ProviderRegistry:()=>Tr,TransportConnectionError:()=>Y,TransportError:()=>it,TransportJsonError:()=>Fn,TransportProcessError:()=>wr,TransportRpcError:()=>vr,_resetDefaultRegistryForTests:()=>jT,bundleSupportedProviders:()=>vs,chat:()=>qr,countTokens:()=>HT,createAdapterRegistry:()=>st,createAllAdapters:()=>pt,listSessions:()=>BT,openBundleSession:()=>oa,seed:()=>aa});function rr(){return ws===null&&(ws=st(pt())),ws}function jT(){ws=null}function ia(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function qr(t){let e=t.registry??rr(),r=ia(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=await r.sendTurn(t.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 vs(t){return(t??rr()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function oa(t){let e=t.registry??rr(),r=ia(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${vs(e).join(", ")})`);return r.openSession(t)}async function aa(t){let e=t.registry??rr(),r=ia(e,t.provider),n=await wm(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.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 wm(e,t.provider,t.cwd),a=WT(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function wm(t,e,r){let n=await t.listAll({provider:e,workspace:r}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function WT(t,e){let r=[];for(let n of e.keys())t.has(n)||r.push(n);return r.length===1?r[0]:void 0}async function BT(t={}){return(t.registry??rr()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function HT(t){let r=await(t.registry??rr()).getSession(t.sessionId,t.provider);if(!r)throw new Error(`session "${t.sessionId}" not found`);let n=r.totalInputTokens??0,s=r.totalCachedInputTokens??0,i=r.totalCacheWriteInputTokens??0,o=r.totalOutputTokens??0,a=r.totalReasoningOutputTokens??0;return{provider:r.provider,sessionId:r.sessionId,input:n,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:n+s+i+o+a,lastTurn:r.lastTokenUsage}}var ws,Gr=O(()=>{"use strict";Ei();sa();Ei();sa();Sm();vt();ws=null});import{spawn as Pa,spawnSync as js}from"node:child_process";import{randomUUID as Hf}from"node:crypto";import{tmpdir as Xf}from"node:os";import*as D from"node:fs";import*as ae from"node:path";import*as Xa from"node:readline";import{fileURLToPath as qa}from"node:url";var L=class extends Error{message;line;column;stage;file;constructor(e,r,n,s,i){let o=i&&i!=="<main>"?`${i}:${r}:${n}`:`${r}:${n}`;super(`[${s} Error at ${o}] ${e}`),this.name="LMScriptError",this.message=e,this.line=r,this.column=n,this.stage=s,this.file=i}},
|
|
93
|
+
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(r)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(r)}return a?F(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let d=Hr(c.timestamp),u=c.content??"";if(c.role==="user"){u&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(u),u.length>0&&(a||(a=F(u,80)),l=F(u,80)),i.push({role:"user",timestamp:d,content:u||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:d,content:u,toolCallId:ye(c.tool_call_id),toolName:ye(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:ye(n.model),stopReason:ye(c.finish_reason)});for(let f of uT(c.tool_calls)){let p=mT(f.function?.arguments);i.push({role:"tool_use",timestamp:d,content:ye(f.function?.name)??"tool_call",toolName:ye(f.function?.name),toolCallId:ye(f.call_id)??ye(f.id),toolInput:typeof f.function?.arguments=="string"?f.function.arguments:JSON.stringify(f.function?.arguments??{}),toolInputData:ke(p)})}}return{provider:this.name,sessionId:n.id,slug:ye(n.title),cwd:tm(n),createdAt:Hr(n.started_at),modifiedAt:Hr(n.last_activity_at??n.started_at),model:ye(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...rm(n),messages:i,userPrompts:o}}catch(n){return R({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{r.close()}}async resolveSessionPath(e){let r=this.openDb();if(!r)return null;try{return this.selectSessionRow(r,e)?this.dbPath:null}catch{return null}finally{r.close()}}async deleteSession(e){return!1}}});import{mkdir as fT}from"node:fs/promises";function hT(t){return pT.test(t)}function im(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return gT}function Ho(t){return new Bo(t)}var pT,gT,Bo,Xo=O(()=>{"use strict";Ie();sm();Ge();_e();z();pT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;gT="dont_ask";Bo=class extends K{hermesProvider;hermesHome;constructor(e){let r=new gs(e);super({provider:r,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)=>Pe(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:im(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Wo(e)}async openSession(e){return $e({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:im(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await fT(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";R({event:"hermes_effort_ignored",provider:this.name,effort:r.effort,reason:i}),n.push(`hermes seed ignored effort=${r.effort}: ${i}`)}let s;try{s=await this.sendTurn(r?.prompt??H,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return hT(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(R({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 om,rm as _T,stat as yT}from"node:fs/promises";import{join as qo}from"node:path";function Go(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function am(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var _s,lm=O(()=>{"use strict";ce();_s=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||qo(W,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let r of await this.listSessionFiles())try{let n=await this.extractSummary(r);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await om(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=qo(this.baseDir,n);try{if(!(await yT(s)).isDirectory())continue;for(let i of await om(s))i.endsWith(".jsonl")&&r.push(qo(s,i))}catch{}}return r}async readHeader(e){for await(let r of re(e))return r.type==="session"?r:null;return null}async extractSummary(e){let r=await this.readHeader(e);if(!r)return null;let n=await se(e),s,i,o,a=0,l=0,c=0,d=0,u=0,f=0,p=0,y;for await(let h of re(e)){if(h.type==="model_change"&&h.provider&&h.modelId){s=`${h.provider}/${h.modelId}`;continue}if(h.type!=="message"||!h.message)continue;let _=h.message;if(_.provider&&_.model&&(s=`${_.provider}/${_.model}`),_.role==="user"){let m=Go(_).trim();m&&(i||(i=F(m,80)),o=F(m,80)),a++}else if(_.role==="assistant"){a++;let m=_.usage;m&&(l+=m.input??0,c+=m.cacheRead??0,d+=m.cacheWrite??0,u+=m.output??0,f+=m.reasoning??0,p=m.input??0,y={inputTokens:m.input,cachedInputTokens:m.cacheRead,cacheWriteInputTokens:m.cacheWrite,outputTokens:m.output,reasoningOutputTokens:m.reasoning,totalTokens:m.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.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:d,totalOutputTokens:u,totalReasoningOutputTokens:f,lastInputTokens:p,lastTokenUsage:y}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=await this.extractSummary(r);if(!n)return null;let s=[],i=n.model;for await(let o of re(r)){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:Go(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:am(c.arguments),toolName:c.name??"tool",toolInput:am(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Go(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...n,model:i,messages:s}}async resolveSessionPath(e){let r=`_${e}.jsonl`,n=[];for(let s of await this.listSessionFiles()){if(s.endsWith(r))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&n.push(s)}return n.length===1?n[0]:null}async deleteSession(e){let r=await this.resolveSessionPath(e);return r?(await _T(r,{force:!0}),!0):!1}}});function Vo(t){return new Jo(t)}var Jo,ET,Ko=O(()=>{"use strict";lm();Ie();_e();qe();Ao();Jo=class extends K{constructor(e){super({provider:new _s(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:ET})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}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}`}}},ET=ds({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>de("pi",t,e.permissionMode??"yolo")})});import{createHash as TT}from"node:crypto";import{existsSync as ST,mkdirSync as zo,readFileSync as wT,renameSync as vT,rmdirSync as gm,statSync as IT,writeFileSync as xT}from"node:fs";import{dirname as ta,join as cm,resolve as Yo}from"node:path";function bT(t){return TT("sha256").update(t).digest("hex").slice(0,8)}function AT(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function RT(t,e){let r=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(r);return n!==null?n[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function _m(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function ys(t){return Math.max(1,Math.ceil(t.length/4))}function tr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Yo(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?cm(ta(Yo(r)),".lmctl-claude-mock","sessions.json"):cm(Yo(t),".lmctl-claude-mock","sessions.json")}function dm(){return{schemaVersion:1,sessions:{}}}function Xr(t){if(!ST(t))return dm();try{let e=JSON.parse(wT(t,"utf8")),r=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=Qo(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return dm()}}function ym(t,e){zo(ta(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;xT(r,`${JSON.stringify(e,null,2)}
|
|
94
|
+
`,"utf8"),vT(r,t)}function LT(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function CT(t){let e=`${t}.lock`;zo(ta(t),{recursive:!0});let r=Date.now()+um;for(;;)try{return zo(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-IT(e).mtimeMs>kT){try{gm(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${um}ms: ${e}`);LT(NT)}}function OT(t){try{gm(t)}catch{}}function Em(t,e){let r=CT(t);try{return e()}finally{OT(r)}}function DT(t){return{...t,timestamp:t.timestamp.toISOString()}}function MT(t){return{...t,timestamp:new Date(t.timestamp)}}function FT(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(DT)}}function Tm(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(MT)}}function Es(t,e=process.cwd()){let r=er.get(t);if(r!==void 0)return r;let s=Xr(tr(e)).sessions[t];if(s===void 0)return;let i=Tm(s);return er.set(i.sessionId,i),i}function mm(t){er.set(t.sessionId,t);let e=tr(t.cwd);Em(e,()=>{let r=Xr(e);r.sessions[t.sessionId]=FT({...t,filePath:e}),ym(e,r)})}function PT(t,e=process.cwd()){let r=tr(e);return Em(r,()=>{let n=Xr(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],ym(r,n)),s})}function $T(){let t=Xr(tr()),e=Object.values(t.sessions).map(Tm);for(let r of e)er.set(r.sessionId,r);return e}function Qo(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function fm(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Qo(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=Qo(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function pm(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function UT(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=fm(r[t]??r[_m(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=fm(n[s]);if(i!==void 0)return i}}}function hm(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function ra(){return new ea}var er,kT,NT,um,Zo,ea,na=O(()=>{"use strict";er=new Map;kT=5e3,NT=15,um=1e4;Zo=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of $T())e.set(r.sessionId,r);for(let r of er.values())e.set(r.sessionId,r);return[...e.values()].map(hm)}async loadSession(e){let r=Es(e);return r===void 0?null:{...hm(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Es(e)?.filePath??null}async deleteSession(e){let r=er.delete(e),n=PT(e);return r||n}},ea=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Zo;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,r){let n=AT(RT(e,r)),s=`mock-${n}-${bT(`${e}:${n}`)}`,i=new Date,o=tr(e),a=Es(s,e),l=r?.prompt??"ClaudeMock seed",c=ys(l),d={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 d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=ys("ACK: ClaudeMock seeded"),mm(d),{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,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Es(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Xr(tr(r.cwd)),a=UT(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await pm(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${_m(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:r.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=ys(e),s.totalOutputTokens+=ys(c),mm(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await pm(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function pt(t){let e=[Ki({claudeDir:t?.claudeDir}),Zi({codexDir:t?.codexDir,codeDir:t?.codeDir}),io({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),co({copilotDir:t?.copilotDir}),fo(),yo({kimiHome:t?.kimiHome}),So({lmplayerDbPath:t?.lmplayerDbPath}),Io(),ko({agyDir:t?.agyDir}),$o({dshHome:t?.dshHome}),Ho({hermesHome:t?.hermesHome}),Vo({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(ra()),e}var sa=O(()=>{"use strict";Yi();eo();oo();uo();po();Eo();wo();xo();No();Uo();Xo();Ko();na();Yi();eo();oo();uo();po();Eo();wo();xo();No();Uo();Xo();Ko();na()});var Ts,Ss,Sm=O(()=>{"use strict";Ts=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],Ss=["agy","pi","lmplayer"]});var vm={};Wf(vm,{BUNDLE_CAPABLE_PROVIDERS:()=>Ts,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Ss,ProviderRegistry:()=>Tr,TransportConnectionError:()=>Y,TransportError:()=>it,TransportJsonError:()=>Fn,TransportProcessError:()=>wr,TransportRpcError:()=>vr,_resetDefaultRegistryForTests:()=>jT,bundleSupportedProviders:()=>vs,chat:()=>qr,countTokens:()=>HT,createAdapterRegistry:()=>st,createAllAdapters:()=>pt,listSessions:()=>BT,openBundleSession:()=>oa,seed:()=>aa});function rr(){return ws===null&&(ws=st(pt())),ws}function jT(){ws=null}function ia(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function qr(t){let e=t.registry??rr(),r=ia(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=await r.sendTurn(t.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 vs(t){return(t??rr()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function oa(t){let e=t.registry??rr(),r=ia(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${vs(e).join(", ")})`);return r.openSession(t)}async function aa(t){let e=t.registry??rr(),r=ia(e,t.provider),n=await wm(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.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 wm(e,t.provider,t.cwd),a=WT(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function wm(t,e,r){let n=await t.listAll({provider:e,workspace:r}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function WT(t,e){let r=[];for(let n of e.keys())t.has(n)||r.push(n);return r.length===1?r[0]:void 0}async function BT(t={}){return(t.registry??rr()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function HT(t){let r=await(t.registry??rr()).getSession(t.sessionId,t.provider);if(!r)throw new Error(`session "${t.sessionId}" not found`);let n=r.totalInputTokens??0,s=r.totalCachedInputTokens??0,i=r.totalCacheWriteInputTokens??0,o=r.totalOutputTokens??0,a=r.totalReasoningOutputTokens??0;return{provider:r.provider,sessionId:r.sessionId,input:n,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:n+s+i+o+a,lastTurn:r.lastTokenUsage}}var ws,Gr=O(()=>{"use strict";Ei();sa();Ei();sa();Sm();vt();ws=null});import{spawn as Pa,spawnSync as js}from"node:child_process";import{randomUUID as Hf}from"node:crypto";import{tmpdir as Xf}from"node:os";import*as D from"node:fs";import*as ae from"node:path";import*as Xa from"node:readline";import{fileURLToPath as qa}from"node:url";var L=class extends Error{message;line;column;stage;file;constructor(e,r,n,s,i){let o=i&&i!=="<main>"?`${i}:${r}:${n}`:`${r}:${n}`;super(`[${s} Error at ${o}] ${e}`),this.name="LMScriptError",this.message=e,this.line=r,this.column=n,this.stage=s,this.file=i}},pe=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};function Ga(t,e){let r=t.file&&t.file!=="<main>"?`${t.file}:${t.line}:${t.column}`:`${t.line}:${t.column}`,n=e;if(t.file&&(!n||n&&t.file!=="<main>"&&t.file!=="<std>"))try{D.existsSync(t.file)&&D.statSync(t.file).isFile()&&(n=D.readFileSync(t.file,"utf-8"))}catch{}if(!n)return`[${t.severity.toUpperCase()} at ${r}] ${t.message}`;let s=n.split(`
|
|
95
95
|
`),i=String(t.line),o=t.line-1,a=s[o]??"",l=" | ",c=` ${i.padStart(4," ")} | `,d=" ".repeat(Math.max(0,t.column-1));return`[${t.severity.toUpperCase()} at ${r}] ${t.message}
|
|
96
96
|
`+l+`
|
|
97
97
|
${c}${a}
|
|
@@ -246,16 +246,17 @@ fn clamp(val, low, high) {
|
|
|
246
246
|
`)+(T.output.length>0?`
|
|
247
247
|
`:""),S=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&S===0,stdout:w,output:[...T.output],value:T.value,exit_code:S,code:S,errors:T.errors??[]};return x.toString=()=>w,x})();{let T=I.run(g,{file:E}),w=T.output.join(`
|
|
248
248
|
`)+(T.output.length>0?`
|
|
249
|
-
`:""),S=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&S===0,stdout:w,output:[...T.output],value:T.value,exit_code:S,code:S,errors:T.errors??[]};return x.toString=()=>w,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 y=e.get("urlget");(!y||y.isDefault)&&this.hostFunctions.set("urlget",{fn:_=>this.isAsync?qf(_):Va(_),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.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(E=>setTimeout(E,_));let m=Date.now()+_;for(;Date.now()<m;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Ne,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 r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new Ne(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);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;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){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,r)}catch(s){if(s instanceof Je)break;if(s instanceof Ve)continue;throw s}}return}case"ForStmt":{let n=new Ne(r);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 Je)break;if(!(i instanceof Ve))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new Ot(n)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;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,r);default:return}}evalExpr(e,r){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,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);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;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),Ke(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,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)Ke(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);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]:Oe(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),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,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),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,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof Dt)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>tn)throw this.callDepth--,new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",o);let l=new Ne(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Ot)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(...r)}catch(l){throw l instanceof Ee||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,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new Dt(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Ne,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 r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new Ne(r);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,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,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;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,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,r,n)}catch(i){if(i instanceof Je)break;if(i instanceof Ve)continue;throw i}}return}case"ForStmt":{let s=new Ne(r);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 Je)break;if(!(o instanceof Ve))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new Ot(s)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;case"SyncAssignStmt":{let s=r.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,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,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,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Ke(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],r,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],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,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;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Ke(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,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Ke(s,i.key,await this.evalExprAsync(i.value,r,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 d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,d)}),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,r,n),i=await this.evalExprAsync(e.index,r,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]:Oe(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,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,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,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,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>tn)throw this.asyncCallDepth.set(o,d-1),new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",a);let u=new Ne(this.globalEnv,!0);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof Ot)return f.value;throw f}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof Ee||d?.name==="LMScriptExit"||d?.isControlFlow?d:new L(`Error in host function '${l}': ${d?.message||String(d)}`,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]}},Yf=[{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;"}],zf=[{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:"getstr",category:"Maps & Key-Value",signature:"getstr(obj: any, path: string|array): string",description:'Typed form of get(): reads a string field, "" when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null", not "" -- getstr never does that).',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array): array",description:"Typed form of get(): reads an array field, [] when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{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");'}],Qf=[{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 Zf(t,e){if(e===void 0)return`${t}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${t}(${i.join(", ")}): any`}let r=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`${t}(${[...r,...n,...s].join(", ")}): any`}function Ba(t,e){let r=new Date(t),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(r.getFullYear());case"%m":return n(r.getMonth()+1);case"%d":return n(r.getDate());case"%H":return n(r.getHours());case"%M":return n(r.getMinutes());case"%S":return n(r.getSeconds());case"%%":return"%";default:return s}})}function ur(t,e){let r=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(t).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[r++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}var je=class t{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 Yf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of zf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Qf)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,r){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,r)}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(r=>(r.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 r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=D.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
249
|
+
`:""),S=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&S===0,stdout:w,output:[...T.output],value:T.value,exit_code:S,code:S,errors:T.errors??[]};return x.toString=()=>w,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 y=e.get("urlget");(!y||y.isDefault)&&this.hostFunctions.set("urlget",{fn:_=>this.isAsync?qf(_):Va(_),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.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(E=>setTimeout(E,_));let m=Date.now()+_;for(;Date.now()<m;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Ne,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 r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new Ne(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);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;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){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,r)}catch(s){if(s instanceof Je)break;if(s instanceof Ve)continue;throw s}}return}case"ForStmt":{let n=new Ne(r);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 Je)break;if(!(i instanceof Ve))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new Ot(n)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;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,r);default:return}}evalExpr(e,r){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,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);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;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),Ke(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,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)Ke(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);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]:Oe(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),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,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),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,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof Dt)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>tn)throw this.callDepth--,new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",o);let l=new Ne(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof Ot)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(...r)}catch(l){throw l instanceof pe||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,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new Dt(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Ne,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 r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new Ne(r);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,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,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;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,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,r,n)}catch(i){if(i instanceof Je)break;if(i instanceof Ve)continue;throw i}}return}case"ForStmt":{let s=new Ne(r);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 Je)break;if(!(o instanceof Ve))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new Ot(s)}case"BreakStmt":throw new Je;case"ContinueStmt":throw new Ve;case"SyncAssignStmt":{let s=r.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,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,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,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),Ke(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],r,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],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,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;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),Ke(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,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)Ke(s,i.key,await this.evalExprAsync(i.value,r,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 d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,d)}),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,r,n),i=await this.evalExprAsync(e.index,r,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]:Oe(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,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,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,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,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>tn)throw this.asyncCallDepth.set(o,d-1),new L(`Execution fuel exhausted: maximum function call depth exceeded (${tn})`,s,i,"RUNTIME",a);let u=new Ne(this.globalEnv,!0);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof Ot)return f.value;throw f}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof pe||d?.name==="LMScriptExit"||d?.isControlFlow?d:new L(`Error in host function '${l}': ${d?.message||String(d)}`,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]}},Yf=[{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;"}],zf=[{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:"getstr",category:"Maps & Key-Value",signature:"getstr(obj: any, path: string|array): string",description:'Typed form of get(): reads a string field, "" when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null", not "" -- getstr never does that).',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array): array",description:"Typed form of get(): reads an array field, [] when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{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:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), prints "error: <message>" to stderr and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{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");'}],Qf=[{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 Zf(t,e){if(e===void 0)return`${t}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${t}(${i.join(", ")}): any`}let r=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`${t}(${[...r,...n,...s].join(", ")}): any`}function Ba(t,e){let r=new Date(t),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(r.getFullYear());case"%m":return n(r.getMonth()+1);case"%d":return n(r.getDate());case"%H":return n(r.getHours());case"%M":return n(r.getMinutes());case"%S":return n(r.getSeconds());case"%%":return"%";default:return s}})}function ur(t,e){let r=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(t).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[r++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}var je=class t{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 Yf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of zf)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Qf)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,r){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,r)}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(r=>(r.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 r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>D.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=D.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
250
250
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
251
251
|
`)&&(r=r.slice(0,-1)),n?r.length===0?[""]:r.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,r)=>{if(!Array.isArray(r))throw new Error("write_lines: second argument must be an array of lines");let n=r.length===0?"":r.map(String).join(`
|
|
252
252
|
`)+`
|
|
253
|
-
`;return D.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(D.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 D.readdirSync(ae.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>(D.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>(D.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,r)=>(D.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=D.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>(D.writeFileSync(e,JSON.stringify(r,null,n),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,r=!0,n=",")=>{let s=D.readFileSync(e,"utf-8");return $a(s,r,n)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,r,n=",")=>(D.writeFileSync(e,ja(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",$a,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",ja,{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=ae.resolve(Xf(),`lmscript-${Hf()}`),r=D.openSync(e,"wx",384);return D.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>D.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new
|
|
253
|
+
`;return D.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(D.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 D.readdirSync(ae.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>(D.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>(D.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,r)=>(D.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=D.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>(D.writeFileSync(e,JSON.stringify(r,null,n),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,r=!0,n=",")=>{let s=D.readFileSync(e,"utf-8");return $a(s,r,n)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,r,n=",")=>(D.writeFileSync(e,ja(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",$a,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",ja,{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=ae.resolve(Xf(),`lmscript-${Hf()}`),r=D.openSync(e,"wx",384);return D.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>D.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new pe(Number(e))},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>D.existsSync(e)?(D.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>D.existsSync(e)?(D.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,r=!0)=>(D.mkdirSync(e,{recursive:!!r}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,r=!1)=>D.existsSync(e)?(r?D.rmSync(e,{recursive:!0,force:!0}):D.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,r)=>(D.copyFileSync(e,r),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,r)=>(D.renameSync(e,r),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,r)=>ae.basename(e,r),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>ae.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>ae.join(...e),void 0,"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>ae.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,r=null)=>process.env[e]!==void 0?process.env[e]:r,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,r=null)=>process.env[e]!==void 0?process.env[e]:r,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,r)=>(process.env[e]=String(r),!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,...r)=>(e.push(...r),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,...r)=>(e.unshift(...r),e),void 0,"Adds item(s) to front of array and returns the array",!0,!0),this.registerFunction("insert",(e,r,n)=>{let s=r<0?e.length+r:r;return e.splice(s,0,n),e},3,"Inserts item at index and returns the array",!0,!0),this.registerFunction("remove_at",(e,r)=>{let n=r<0?e.length+r:r,s=e.splice(n,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...r)=>e.concat(...r),void 0,"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,r)=>{if(!Array.isArray(e))return e;let n=[...e];return r?n.sort((s,i)=>{let o=s?s[r]:void 0,a=i?i[r]: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,r)=>this.hostFunctions.get("sort").fn(e,r),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((r,n)=>r+(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 r of Object.keys(e))delete e[r];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,r=6e4)=>{if(!Number.isSafeInteger(r)||r<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsyncMode?za(e,r):Ya(e,r)},{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,r=[])=>{let n=ae.resolve(String(e));if(!D.existsSync(n))throw new Error(`run_script: file not found: '${n}'`);let s=D.readFileSync(n,"utf-8"),i=Array.isArray(r)?r.map(String):[],o=new t;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(`
|
|
254
254
|
`)+(a.output.length>0?`
|
|
255
255
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d})();{let a=o.run(s,{file:n}),l=a.output.join(`
|
|
256
256
|
`)+(a.output.length>0?`
|
|
257
257
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d}},{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 r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
|
|
258
|
-
`):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>Va(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 r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?fr(e):mr(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,r)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,r)},{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(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,r=null)=>Gf(e,r),{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,r)=>JSON.stringify(e,null,r),{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,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=lr(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r)=>{let n=lr(e,r);return n==null?"":String(n)},2,'Reads a string field from a map/request form; "" when missing or null (never the string "null")'),this.registerFunction("getnum",(e,r,n=0)=>{let s=lr(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=lr(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r)=>{let n=lr(e,r);return Array.isArray(n)?n:[]},2,"Reads an array field from a map/request form; [] when missing, null, or not actually an array"),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(Oe(i,a)==null||typeof Oe(i,a)!="object")&&Ke(i,a,{}),i=Oe(i,a)}return s.length>0&&Ke(i,s[s.length-1],n),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,r)=>Array.isArray(e)?e.map(n=>Oe(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Oe(s,r)===n):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,r,n)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&Oe(i,r)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,r)=>({...e,...r}),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,r)=>(e&&typeof e=="object"&&delete e[r],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...r)=>{let n=ur(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),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 r=e.split(/\r?\n/);for(let n=r.length-1;n>=0;n--){let s=r[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,r=", ")=>Array.isArray(e)?e.join(r):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 r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),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,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,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 Dt,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>Ka(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[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 d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let f=Number(u);o+=f<r.length?a(r[f]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>ur(e,r),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,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,r,n="")=>new RegExp(r,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,r,n="")=>{let s=String(e).match(new RegExp(r,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,r,n="")=>{let s=String(e).match(new RegExp(r,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,r,n="")=>{let s=String(e).match(new RegExp(r,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,r,n="")=>{let s=new RegExp(r,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,r,n="")=>{let s=new RegExp(r,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,r,n,s="")=>String(e).replace(new RegExp(r,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,r,n="")=>String(e).split(new RegExp(r,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,r,n=1)=>{let s=r===void 0?0:e,i=r===void 0?e:r,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 r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...r)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},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,r)=>Math.pow(e,r),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,r)=>Ba(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Ba(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,r,n)=>e?r: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 Dt?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,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,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${p}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:Zf(e,n),description:a}),this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,r){return this.initialGlobals.set(e,r),this}getGlobal(e){return this.initialGlobals.get(e)}scanAndCheck(e,r={}){try{let{program:n}=Kf(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new Hs(this.hostFunctions,{...r,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||r.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:n instanceof Error?n.message:String(n),line:1,column:1,severity:"error",file:r.file}],hasConcurrency:!1}}}run(e,r={}){let n=[],{ast:s,diagnostics:i,hasConcurrency:o}=this.scanAndCheck(e,r);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:r.file}],output:n};let l;try{l=new an(this.hostFunctions,u=>n.push(u),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let d=l.getRecordedErrors();return this.lastRecordedErrors=d,{success:!0,value:c,diagnostics:i,output:n,errors:d}}catch(c){let d=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=d,c instanceof Ee||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let y=typeof c.exitCode=="number"?c.exitCode:0;return{success:y===0,value:y,exitCode:y,diagnostics:i,output:n,errors:d}}let u=c instanceof L?c.line:1,f=c instanceof L?c.column:1,p=c instanceof L&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);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 an(this.hostFunctions,d=>n.push(d),!0,this.initialGlobals,r.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 Ee||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof L?l.line:1,u=l instanceof L?l.column:1,f=l instanceof L&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,severity:"error",file:f}],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 ep(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
258
|
+
`):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>Va(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 r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?fr(e):mr(e),{min:0,max:1},"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",!0),this.registerFunction("json",(e,r)=>{if(typeof e=="string")try{return JSON.parse(e)}catch(n){throw new Error(`Invalid JSON string: ${n.message}`)}return JSON.stringify(e,null,r)},{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(r){throw new Error(`JSON parse error: ${r.message}`)}},1,"Parses JSON string into object/array"),this.registerFunction("json_parse_safe",(e,r=null)=>Gf(e,r),{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,r)=>JSON.stringify(e,null,r),{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,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=lr(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r)=>{let n=lr(e,r);return n==null?"":String(n)},2,'Reads a string field from a map/request form; "" when missing or null (never the string "null")'),this.registerFunction("getnum",(e,r,n=0)=>{let s=lr(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=lr(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r)=>{let n=lr(e,r);return Array.isArray(n)?n:[]},2,"Reads an array field from a map/request form; [] when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
|
|
259
|
+
`):console.error(`error: ${String(r)}`),new pe(2);return e},2,'Stops the script (stderr message, exit 2) if value is missing -- "", null, [], or false -- else returns value unchanged, so it composes with getstr/getnum/getbool/getlist'),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(Oe(i,a)==null||typeof Oe(i,a)!="object")&&Ke(i,a,{}),i=Oe(i,a)}return s.length>0&&Ke(i,s[s.length-1],n),e},3,"Sets nested property by path",!0,!0),this.registerFunction("pluck",(e,r)=>Array.isArray(e)?e.map(n=>Oe(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Oe(s,r)===n):[],3,"Filters array of objects where item[key] == value"),this.registerFunction("find_by",(e,r,n)=>{if(!Array.isArray(e))return null;let s=e.find(i=>i!=null&&Oe(i,r)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,r)=>({...e,...r}),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,r)=>(e&&typeof e=="object"&&delete e[r],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...r)=>{let n=ur(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),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 r=e.split(/\r?\n/);for(let n=r.length-1;n>=0;n--){let s=r[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,r=", ")=>Array.isArray(e)?e.join(r):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 r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),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,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,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 Dt,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>Ka(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[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 d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let f=Number(u);o+=f<r.length?a(r[f]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>ur(e,r),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,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,r,n="")=>new RegExp(r,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,r,n="")=>{let s=String(e).match(new RegExp(r,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,r,n="")=>{let s=String(e).match(new RegExp(r,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,r,n="")=>{let s=String(e).match(new RegExp(r,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,r,n="")=>{let s=new RegExp(r,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,r,n="")=>{let s=new RegExp(r,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,r,n,s="")=>String(e).replace(new RegExp(r,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,r,n="")=>String(e).split(new RegExp(r,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,r,n=1)=>{let s=r===void 0?0:e,i=r===void 0?e:r,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 r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...r)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},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,r)=>Math.pow(e,r),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,r)=>Ba(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Ba(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,r,n)=>e?r: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 Dt?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,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,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${p}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:Zf(e,n),description:a}),this}getFunctionOriginModule(e){return this.functionOriginModule.get(e)}initialGlobals=new Map;setGlobal(e,r){return this.initialGlobals.set(e,r),this}getGlobal(e){return this.initialGlobals.get(e)}scanAndCheck(e,r={}){try{let{program:n}=Kf(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new Hs(this.hostFunctions,{...r,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||r.file}],hasConcurrency:!1}:{ast:null,diagnostics:[{message:n instanceof Error?n.message:String(n),line:1,column:1,severity:"error",file:r.file}],hasConcurrency:!1}}}run(e,r={}){let n=[],{ast:s,diagnostics:i,hasConcurrency:o}=this.scanAndCheck(e,r);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:r.file}],output:n};let l;try{l=new an(this.hostFunctions,u=>n.push(u),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let d=l.getRecordedErrors();return this.lastRecordedErrors=d,{success:!0,value:c,diagnostics:i,output:n,errors:d}}catch(c){let d=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=d,c instanceof pe||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let y=typeof c.exitCode=="number"?c.exitCode:0;return{success:y===0,value:y,exitCode:y,diagnostics:i,output:n,errors:d}}let u=c instanceof L?c.line:1,f=c instanceof L?c.column:1,p=c instanceof L&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);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 an(this.hostFunctions,d=>n.push(d),!0,this.initialGlobals,r.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 p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof L?l.line:1,u=l instanceof L?l.column:1,f=l instanceof L&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,severity:"error",file:f}],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 ep(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
259
260
|
`);let t=new je,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=t.run(`
|
|
260
261
|
fn factorial(n) {
|
|
261
262
|
if (n <= 1) {
|
|
@@ -491,9 +492,9 @@ fn clamp(val, low, high) {
|
|
|
491
492
|
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=Ks(i,ol(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 be(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
492
493
|
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??ol(n),isLead:Ft(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}z();import{existsSync as Np,mkdirSync as Lp,readFileSync as Cp,renameSync as Op,unlinkSync as Dp,writeFileSync as Mp}from"node:fs";import{homedir as ml}from"node:os";import{dirname as pr,join as fe,resolve as Fp}from"node:path";var fn="lmctl",pn="lmctl0",Pp={existsSync:Np,mkdirSync:Lp,readFileSync:Cp,writeFileSync:Mp,renameSync:Op,unlinkSync:Dp},Ae=Pp,ti;function gn(t,e,r){let n=pr(Fp(r)),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())Me(fe(o,".mcp.json"),"mcpServers",[ze(),Qe()]),a.has("opencode")&&Me(fe(o,".opencode","opencode.json"),"mcp",[fl(),pl()]),a.has("kimi")&&Me(fe(o,".kimi-code","mcp.json"),"mcpServers",[ze(),Qe()]);for(let o of s)Wp(o)}function $p(t=ti??ml()){return fe(t,".copilot","mcp-config.json")}function Up(t,e){Ae.mkdirSync(pr(t),{recursive:!0});let r=fe(pr(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Ae.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
493
494
|
`,"utf8"),Ae.renameSync(r,t)}catch(n){try{Ae.unlinkSync(r)}catch{}throw n}}function jp(t,e){Ae.mkdirSync(pr(t),{recursive:!0});let r=fe(pr(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Ae.writeFileSync(r,e,"utf8"),Ae.renameSync(r,t)}catch(n){try{Ae.unlinkSync(r)}catch{}throw n}}function Me(t,e,r){try{if(!Ae.existsSync(t))return;let n=JSON.parse(Ae.readFileSync(t,"utf8"));if(!$t(n)||!$t(n[e]))return;let s={...n[e]},i=[];for(let{name:o,shouldRemove:a}of r)Object.prototype.hasOwnProperty.call(s,o)&&a(s[o])&&(delete s[o],i.push(o));if(i.length===0)return;n[e]=s,Up(t,n),R({event:"mcp_cleanup",path:t,removed:i})}catch{}}function ze(){return{name:pn,shouldRemove:Kp}}function fl(){return{name:pn,shouldRemove:Yp}}function Qe(){return{name:fn,shouldRemove:Jp}}function pl(){return{name:fn,shouldRemove:Vp}}function Wp(t){let e=ti??ml();switch(t){case"copilot":Me($p(e),"mcpServers",[ze(),Qe()]);return;case"claude":Me(fe(e,".claude.json"),"mcpServers",[ze(),Qe()]);return;case"gemini":Me(fe(e,".gemini","settings.json"),"mcpServers",[ze(),Qe()]);return;case"qwen":Me(fe(e,".qwen","settings.json"),"mcpServers",[ze(),Qe()]);return;case"agy":Me(fe(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[ze(),Qe()]);return;case"opencode":Me(fe(e,".config","opencode","opencode.json"),"mcp",[fl(),pl()]);return;case"kimi":Me(fe(ti===void 0?process.env.KIMI_CODE_HOME??fe(e,".kimi-code"):fe(e,".kimi-code"),"mcp.json"),"mcpServers",[ze(),Qe()]);return;case"codex":Bp(fe(e,".codex","config.toml"));return;default:return}}function Bp(t){try{if(!Ae.existsSync(t))return;let e=Ae.readFileSync(t,"utf8"),r=Hp(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=hl(l);if(c===null)return;if(c!==void 0){if(ul(c,r)){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 d=qp(l);if(d===null)return;if(d!==void 0&&ul(d,r)){i.add(d[1]);continue}s.push(l)}if(i.size===0)return;jp(t,s.join(`
|
|
494
|
-
`)),R({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function ul(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function Hp(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=hl(s);if(i===null)return null;if(i!==void 0){r=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=Xp(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==fn&&c[1]!==pn)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=gl(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=Gp(l);if(u===null)return null;d.args=u}e.set(c[1],d)}let n=new Set;for(let[s,i]of e.entries())s===fn&&yl(i.command,i.args)&&n.add(s),s===pn&&El(i.command,i.args)&&n.add(s);return n}function Xp(t,e){if(t.startsWith("mcp_servers"))return hn(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=hn(t);return r===null?null:[...e,...r]}function hl(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:hn(e[1])}function qp(t){let e=t.indexOf("=");if(e<0)return;let r=t.slice(0,e).trim();if(!(r.length===0||!r.startsWith("mcp_servers")))return hn(r)}function hn(t){let e=[],r=0,n=()=>{for(;r<t.length&&/\s/.test(t[r]);)r+=1};for(;r<t.length;){if(n(),r>=t.length)return null;if(t[r]==='"'){r+=1;let s="",i=!1;for(;r<t.length;){let o=t[r];if(o==="\\"){if(r+1>=t.length)return null;s+=t[r+1],r+=2;continue}if(o==='"'){r+=1,i=!0;break}s+=o,r+=1}if(!i)return null;e.push(s)}else{let s=r;for(;r<t.length&&/[A-Za-z0-9_-]/.test(t[r]);)r+=1;if(r===s)return null;e.push(t.slice(s,r))}if(n(),r>=t.length)break;if(t[r]!==".")return null;r+=1}return e.length>0?e:null}function gl(t){let e=_l(t).trim();if(e.startsWith('"'))try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function Gp(t){let e=_l(t).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).trim();if(r.length===0)return[];let n=r.split(",").map(s=>gl(s.trim()));return n.some(s=>s===null)?null:n}function _l(t){let e;for(let r=0;r<t.length;r+=1){let n=t[r];if(e!==void 0){if(e==='"'&&n==="\\"){r+=1;continue}n===e&&(e=void 0);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return t.slice(0,r)}return t}function Jp(t){return $t(t)?t.type==="stdio"&&typeof t.command=="string"&&yl(t.command,t.args):!1}function Vp(t){return!$t(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Sl(t.command[0])&&t.command[1]==="mcp"||t.command.length===3&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&typeof t.command[2]=="string"&&Tl(t.command[0],[t.command[1],t.command[2]])}function Kp(t){return $t(t)?t.type==="stdio"&&El(t.command,t.args):!1}function Yp(t){return!$t(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&wl(t.command[0])&&t.command[1]==="mcp"}function yl(t,e){return Sl(t)&&vl(e)||Tl(t,e)}function El(t,e){return wl(t)&&vl(e)}function Tl(t,e){return zp(t)&&Array.isArray(e)&&e.length===2&&Qp(e[0])&&e[1]==="mcp"}function Sl(t){return typeof t=="string"&&ri(t)==="lmctl"}function wl(t){return typeof t=="string"&&ri(t)==="lmctl0"}function zp(t){if(typeof t!="string")return!1;let e=ri(t).toLowerCase();return e==="node"||e==="node.exe"}function Qp(t){if(typeof t!="string")return!1;let e=t.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function ri(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function vl(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function $t(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bl(t){let e=Il(t.registry,t.fromTeamfile);if(e===void 0)return Ut(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!xl(e,t.fromAlias))return Ut(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Il(t.registry,t.toTeamfile);return r===void 0?Ut(`target team is not registered in policy graph: ${t.toTeamfile}`):xl(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Ut(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Ut(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Ut(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Il(t,e){return t.teams.find(r=>r.teamfile===e)}function xl(t,e){return t.aliases.some(r=>r===e)}function Ut(t){return{allowed:!1,outOfPolicy:!0,reason:t}}import{basename as Zp}from"node:path";var eh=6e4,th=2,Al=8*60*60*1e3;function kl(t,e){let r=new Date(e.now.getTime()-jt()).toISOString(),n=Cl(t,r).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=nh(e.sender,n),i=sh(e.sender,n);i!==null&&i.teamfile===e.root&&!Rl(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>Rl(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,y)=>y-p)[0]??null,d=c!==null&&e.now.getTime()-c<eh,u=ni(e.sender,n).length;return{stop:l.length>=1&&d&&u>=th,chain:ih(a)}}function Nl(t,e){let r=new Date(e.now.getTime()-jt()).toISOString(),n=Cl(t,r),s=ni(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 jt(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Al;let r=Number(e);return!Number.isFinite(r)||r<=0?Al:r}function Ll(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function rh(t){return{sender:{teamfile:t.sender_teamfile,alias:t.sender_alias},receiver:{teamfile:t.receiver_teamfile,alias:t.receiver_alias},at:Date.parse(t.started_at)}}function Cl(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(rh).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function nh(t,e,r={}){let n=new Map;for(let a of e)n.set(yt(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([yt(t)]);for(let a=0;a<64;a+=1){let l=n.get(yt(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:")&&r.includePromptSender!==!0)break;let d=yt(l.sender);if(o.has(d))break;s.unshift(c),o.add(d),i=l.sender}return s}function ni(t,e){let r=yt(t),n=new Set([r]),s=[r],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=yt(l.sender),d=yt(l.receiver);c!==a&&d!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(d)||(n.add(d),s.push(d)))}}return i.sort((o,a)=>o.at-a.at)}function sh(t,e){let r=ni(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Rl(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function yt(t){return`${t.teamfile}\0${t.alias}`}function ih(t){return t.map(e=>`${Zp(e.teamfile)}:${e.alias}`).join(" \u2192 ")}z();import{randomUUID as mc}from"node:crypto";import{existsSync as _c,mkdirSync as eg,renameSync as tg,rmdirSync as rg}from"node:fs";import{hostname as hi}from"node:os";import{existsSync as oh}from"node:fs";import{createRequire as ah}from"node:module";var si=null;function lh(){return si===null&&(si=ah(import.meta.url)("node:sqlite").DatabaseSync),si}var oi=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!oh(e))throw new Error("unable to open database file");this.name=e,this.handle=new(lh())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new ai(this.handle.prepare(e))}exec(e){this.handle.exec(e),this.updateTransactionDepth(e)}pragma(e,r){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}let s=this.prepare(n).get();return r?.simple===!0?s===void 0?void 0:Object.values(s)[0]:s}transaction(e){return(...r)=>{if(this.transactionDepth===0){this.exec("BEGIN");try{let s=e(...r);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(...r);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 r=e.trim().match(/^([A-Za-z]+)/)?.[1]?.toUpperCase();if(r!==void 0){if(r==="BEGIN"||r==="SAVEPOINT"){this.transactionDepth+=1;return}if(r==="COMMIT"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}if(r==="RELEASE"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}r==="ROLLBACK"&&!/^ROLLBACK\s+TO\b/i.test(e.trim())&&(this.transactionDepth=0)}}},_n=oi,ai=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...ii(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...ii(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...ii(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&li(e)?Object.values(e):li(e)?{...e}:e}};function ii(t){return t.length===1&&ch(t[0])?[t[0]]:t}function ch(t){if(!li(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function li(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}import{existsSync as Th,mkdirSync as Sh,readFileSync as Fl}from"node:fs";import{randomUUID as wh}from"node:crypto";import{homedir as vh}from"node:os";import{dirname as Pl,join as Ih,resolve as $l}from"node:path";import{fileURLToPath as xh,pathToFileURL as bh}from"node:url";import{createHash as mh}from"node:crypto";import{createHash as dh}from"node:crypto";function uh(t,e,r){return dh("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function pe(t,e,r){let n=uh(e.stream_id,e.intentKey??e.event_type,e.observedLastSeq),s=t.prepare(`INSERT INTO message_event (event_id, ts, stream_id, event_type, payload)
|
|
495
|
+
`)),R({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function ul(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function Hp(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=hl(s);if(i===null)return null;if(i!==void 0){r=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=Xp(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==fn&&c[1]!==pn)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=gl(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=Gp(l);if(u===null)return null;d.args=u}e.set(c[1],d)}let n=new Set;for(let[s,i]of e.entries())s===fn&&yl(i.command,i.args)&&n.add(s),s===pn&&El(i.command,i.args)&&n.add(s);return n}function Xp(t,e){if(t.startsWith("mcp_servers"))return hn(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=hn(t);return r===null?null:[...e,...r]}function hl(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:hn(e[1])}function qp(t){let e=t.indexOf("=");if(e<0)return;let r=t.slice(0,e).trim();if(!(r.length===0||!r.startsWith("mcp_servers")))return hn(r)}function hn(t){let e=[],r=0,n=()=>{for(;r<t.length&&/\s/.test(t[r]);)r+=1};for(;r<t.length;){if(n(),r>=t.length)return null;if(t[r]==='"'){r+=1;let s="",i=!1;for(;r<t.length;){let o=t[r];if(o==="\\"){if(r+1>=t.length)return null;s+=t[r+1],r+=2;continue}if(o==='"'){r+=1,i=!0;break}s+=o,r+=1}if(!i)return null;e.push(s)}else{let s=r;for(;r<t.length&&/[A-Za-z0-9_-]/.test(t[r]);)r+=1;if(r===s)return null;e.push(t.slice(s,r))}if(n(),r>=t.length)break;if(t[r]!==".")return null;r+=1}return e.length>0?e:null}function gl(t){let e=_l(t).trim();if(e.startsWith('"'))try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function Gp(t){let e=_l(t).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).trim();if(r.length===0)return[];let n=r.split(",").map(s=>gl(s.trim()));return n.some(s=>s===null)?null:n}function _l(t){let e;for(let r=0;r<t.length;r+=1){let n=t[r];if(e!==void 0){if(e==='"'&&n==="\\"){r+=1;continue}n===e&&(e=void 0);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return t.slice(0,r)}return t}function Jp(t){return $t(t)?t.type==="stdio"&&typeof t.command=="string"&&yl(t.command,t.args):!1}function Vp(t){return!$t(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Sl(t.command[0])&&t.command[1]==="mcp"||t.command.length===3&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&typeof t.command[2]=="string"&&Tl(t.command[0],[t.command[1],t.command[2]])}function Kp(t){return $t(t)?t.type==="stdio"&&El(t.command,t.args):!1}function Yp(t){return!$t(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&wl(t.command[0])&&t.command[1]==="mcp"}function yl(t,e){return Sl(t)&&vl(e)||Tl(t,e)}function El(t,e){return wl(t)&&vl(e)}function Tl(t,e){return zp(t)&&Array.isArray(e)&&e.length===2&&Qp(e[0])&&e[1]==="mcp"}function Sl(t){return typeof t=="string"&&ri(t)==="lmctl"}function wl(t){return typeof t=="string"&&ri(t)==="lmctl0"}function zp(t){if(typeof t!="string")return!1;let e=ri(t).toLowerCase();return e==="node"||e==="node.exe"}function Qp(t){if(typeof t!="string")return!1;let e=t.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function ri(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function vl(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function $t(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bl(t){let e=Il(t.registry,t.fromTeamfile);if(e===void 0)return Ut(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!xl(e,t.fromAlias))return Ut(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Il(t.registry,t.toTeamfile);return r===void 0?Ut(`target team is not registered in policy graph: ${t.toTeamfile}`):xl(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Ut(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Ut(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Ut(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Il(t,e){return t.teams.find(r=>r.teamfile===e)}function xl(t,e){return t.aliases.some(r=>r===e)}function Ut(t){return{allowed:!1,outOfPolicy:!0,reason:t}}import{basename as Zp}from"node:path";var eh=6e4,th=2,Al=8*60*60*1e3;function kl(t,e){let r=new Date(e.now.getTime()-jt()).toISOString(),n=Cl(t,r).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=nh(e.sender,n),i=sh(e.sender,n);i!==null&&i.teamfile===e.root&&!Rl(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>Rl(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,y)=>y-p)[0]??null,d=c!==null&&e.now.getTime()-c<eh,u=ni(e.sender,n).length;return{stop:l.length>=1&&d&&u>=th,chain:ih(a)}}function Nl(t,e){let r=new Date(e.now.getTime()-jt()).toISOString(),n=Cl(t,r),s=ni(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 jt(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Al;let r=Number(e);return!Number.isFinite(r)||r<=0?Al:r}function Ll(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function rh(t){return{sender:{teamfile:t.sender_teamfile,alias:t.sender_alias},receiver:{teamfile:t.receiver_teamfile,alias:t.receiver_alias},at:Date.parse(t.started_at)}}function Cl(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(rh).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function nh(t,e,r={}){let n=new Map;for(let a of e)n.set(yt(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([yt(t)]);for(let a=0;a<64;a+=1){let l=n.get(yt(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:")&&r.includePromptSender!==!0)break;let d=yt(l.sender);if(o.has(d))break;s.unshift(c),o.add(d),i=l.sender}return s}function ni(t,e){let r=yt(t),n=new Set([r]),s=[r],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=yt(l.sender),d=yt(l.receiver);c!==a&&d!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(d)||(n.add(d),s.push(d)))}}return i.sort((o,a)=>o.at-a.at)}function sh(t,e){let r=ni(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Rl(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function yt(t){return`${t.teamfile}\0${t.alias}`}function ih(t){return t.map(e=>`${Zp(e.teamfile)}:${e.alias}`).join(" \u2192 ")}z();import{randomUUID as mc}from"node:crypto";import{existsSync as _c,mkdirSync as eg,renameSync as tg,rmdirSync as rg}from"node:fs";import{hostname as hi}from"node:os";import{existsSync as oh}from"node:fs";import{createRequire as ah}from"node:module";var si=null;function lh(){return si===null&&(si=ah(import.meta.url)("node:sqlite").DatabaseSync),si}var oi=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!oh(e))throw new Error("unable to open database file");this.name=e,this.handle=new(lh())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new ai(this.handle.prepare(e))}exec(e){this.handle.exec(e),this.updateTransactionDepth(e)}pragma(e,r){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}let s=this.prepare(n).get();return r?.simple===!0?s===void 0?void 0:Object.values(s)[0]:s}transaction(e){return(...r)=>{if(this.transactionDepth===0){this.exec("BEGIN");try{let s=e(...r);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(...r);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 r=e.trim().match(/^([A-Za-z]+)/)?.[1]?.toUpperCase();if(r!==void 0){if(r==="BEGIN"||r==="SAVEPOINT"){this.transactionDepth+=1;return}if(r==="COMMIT"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}if(r==="RELEASE"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}r==="ROLLBACK"&&!/^ROLLBACK\s+TO\b/i.test(e.trim())&&(this.transactionDepth=0)}}},_n=oi,ai=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...ii(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...ii(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...ii(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&li(e)?Object.values(e):li(e)?{...e}:e}};function ii(t){return t.length===1&&ch(t[0])?[t[0]]:t}function ch(t){if(!li(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function li(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}import{existsSync as Th,mkdirSync as Sh,readFileSync as Fl}from"node:fs";import{randomUUID as wh}from"node:crypto";import{homedir as vh}from"node:os";import{dirname as Pl,join as Ih,resolve as $l}from"node:path";import{fileURLToPath as xh,pathToFileURL as bh}from"node:url";import{createHash as mh}from"node:crypto";import{createHash as dh}from"node:crypto";function uh(t,e,r){return dh("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function he(t,e,r){let n=uh(e.stream_id,e.intentKey??e.event_type,e.observedLastSeq),s=t.prepare(`INSERT INTO message_event (event_id, ts, stream_id, event_type, payload)
|
|
495
496
|
VALUES (?, ?, ?, ?, ?)
|
|
496
|
-
ON CONFLICT(event_id) DO NOTHING`),i=t.prepare("SELECT seq FROM message_event WHERE event_id = ?");return t.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 r(l),{appended:!0,seq:l,event_id:n}})()}var X={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 Et(t,e){return t==null?null:{teamfile:t,alias:e??""}}function fh(t,e,r){return`lease_${mh("sha256").update(`${t}\0${e}\0${r}`).digest("hex").slice(0,16)}`}function yn(t,e,r,n){r.forEach((s,i)=>{
|
|
497
|
+
ON CONFLICT(event_id) DO NOTHING`),i=t.prepare("SELECT seq FROM message_event WHERE event_id = ?");return t.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 r(l),{appended:!0,seq:l,event_id:n}})()}var X={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 Et(t,e){return t==null?null:{teamfile:t,alias:e??""}}function fh(t,e,r){return`lease_${mh("sha256").update(`${t}\0${e}\0${r}`).digest("hex").slice(0,16)}`}function yn(t,e,r,n){r.forEach((s,i)=>{he(t,{stream_id:e,event_type:s.event_type,payload:s.payload,observedLastSeq:i,ts:s.ts},()=>{}).appended?n.appended+=1:n.skipped+=1})}function ph(t){let e=`msg_tcl_${t.id}`,r=Et(t.sender_teamfile,t.sender_alias),n=Et(t.receiver_teamfile,t.receiver_alias),s={table:"team_chat_log",id:t.id},i={message_id:e,sender:r,receiver:n,root_teamfile:t.root_teamfile,legacy:s},o=[{event_type:X.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.message,origin:t.origin,correlation_status:"legacy-unavailable"}}];return t.status!=="running"&&o.push({event_type:X.HANDLED,ts:t.created_at,payload:{...i,outcome:t.status,receipt:t.response,error:t.error_detail,truncated:t.truncated===1}}),{streamId:e,events:o}}function hh(t){let e=`msg_mbx_${t.id}`,r=Et(t.sender_teamfile,t.sender_alias),n=Et(t.receiver_teamfile,t.receiver_alias),s={table:"agent_mailbox",id:t.id},i={message_id:e,sender:r,receiver:n,root_teamfile:t.root_teamfile,legacy:s},o=[];if(t.message_type==="response"){let a=t.request_mailbox_id!==null?`msg_mbx_${t.request_mailbox_id}`:null;return o.push({event_type:X.RESPONSE_CREATE,ts:t.created_at,payload:{...i,message_type:"response",content:t.payload,in_reply_to_message_id:a,correlation_status:"legacy-unavailable"}}),o.push({event_type:X.RESPONSE_ENQUEUE,ts:t.created_at,payload:{...i,message_type:"response",in_reply_to_message_id:a}}),t.delivered_at!==null&&o.push({event_type:X.RESPONSE_DELIVERED,ts:t.delivered_at,payload:{...i,message_type:"response",receipt:t.receipt}}),{streamId:e,events:o}}return o.push({event_type:X.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.payload,correlation_status:"legacy-unavailable"}}),o.push({event_type:X.ENQUEUE,ts:t.created_at,payload:{...i,message_type:"request"}}),t.waited_at!==null&&o.push({event_type:X.WAIT_REGISTER,ts:t.waited_at,payload:{...i,waited_by:t.waited_by}}),(t.delivering_at!==null||t.delivery_holder_pid!==null)&&o.push({event_type:X.DELIVER_CLAIM,ts:t.delivering_at??t.created_at,payload:{...i,pid:t.delivery_holder_pid,host:t.delivery_holder_host}}),t.delivered_at!==null&&o.push({event_type:X.DELIVERED,ts:t.delivered_at,payload:{...i,receipt:t.receipt}}),{streamId:e,events:o}}function gh(t){let e=`inv_${t.id}`,r=Et(t.target_teamfile,t.target_alias),n={table:"tracked_invocation",id:t.id},s=[{event_type:X.INVOCATION_START,ts:t.started_at,payload:{invocation_id:e,kind:t.kind,origin:t.origin,launch_source:t.launch_source,from_identity:t.from_identity,target:r,root_teamfile:t.root_teamfile,scope_teamfile:t.scope_teamfile,cwd:t.cwd,command:t.command,request_payload:t.request_payload,started_at:t.started_at,request_message_id:t.team_chat_log_id!==null?`msg_tcl_${t.team_chat_log_id}`:null,holder_pid:t.holder_pid,holder_host:t.holder_host,legacy:n}}];return t.notified_by!==null&&s.push({event_type:X.INVOCATION_NOTIFY_CLAIM,ts:t.notified_at??t.started_at,payload:{invocation_id:e,notified_by:t.notified_by,notified_at:t.notified_at,legacy:n}}),t.status!=="running"&&s.push({event_type:X.INVOCATION_FINISH,ts:t.ended_at??t.started_at,payload:{invocation_id:e,status:t.status,ended_at:t.ended_at,exit_code:t.exit_code,signal:t.signal,result_summary:t.result_summary,error:t.error,legacy:n}}),{streamId:e,events:s}}function _h(t){let e=fh(t.receiver_teamfile,t.receiver_alias,t.started_at),r=Et(t.receiver_teamfile,t.receiver_alias),n=Et(t.sender_teamfile,t.sender_alias);return{streamId:e,events:[{event_type:X.INFLIGHT_TAKE,ts:t.started_at,payload:{lease_id:e,receiver:r,sender:n,holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at,legacy:{table:"agent_inflight",receiver_teamfile:t.receiver_teamfile,receiver_alias:t.receiver_alias}}}]}}function En(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Ol(t){let e={appended:0,skipped:0},r={team_chat_log:0,agent_mailbox:0,tracked_invocation:0,agent_inflight:0};t.transaction(()=>{if(En(t,"team_chat_log"))for(let i of t.prepare("SELECT * FROM team_chat_log ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=ph(i);yn(t,a,l,e),r.team_chat_log+=e.appended+e.skipped-o}if(En(t,"agent_mailbox"))for(let i of t.prepare("SELECT * FROM agent_mailbox ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=hh(i);yn(t,a,l,e),r.agent_mailbox+=e.appended+e.skipped-o}if(En(t,"tracked_invocation"))for(let i of t.prepare("SELECT * FROM tracked_invocation ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=gh(i);yn(t,a,l,e),r.tracked_invocation+=e.appended+e.skipped-o}if(En(t,"agent_inflight"))for(let i of t.prepare("SELECT * FROM agent_inflight ORDER BY receiver_teamfile, receiver_alias").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=_h(i);yn(t,a,l,e),r.agent_inflight+=e.appended+e.skipped-o}yh(t)})();let s=i=>t.prepare(`SELECT count(*) AS n FROM ${i}`).get().n;return{appended:e.appended,skipped:e.skipped,bySource:r,projections:{agent_state:s("agent_state"),message_pending:s("message_pending"),invocation_state:s("invocation_state")}}}function yh(t){t.exec("DELETE FROM agent_state"),t.exec("DELETE FROM message_pending"),t.exec("DELETE FROM invocation_state");let e=t.prepare("SELECT seq, stream_id, event_type, payload FROM message_event ORDER BY seq").all();for(let r of e){let n=JSON.parse(r.payload);Eh(t,r.seq,r.stream_id,r.event_type,n)}}function ie(t,e,r){let n=t[e];return n!=null?n[r]??null:null}function Eh(t,e,r,n,s){switch(n){case X.ENQUEUE:case X.RESPONSE_ENQUEUE:{let i=n===X.RESPONSE_ENQUEUE;t.prepare(`INSERT INTO message_pending
|
|
497
498
|
(message_id, message_type, in_reply_to, sender_teamfile, sender_alias,
|
|
498
499
|
receiver_teamfile, receiver_alias, lifecycle_state, created_seq, last_seq)
|
|
499
500
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)
|
|
@@ -1523,12 +1524,12 @@ fn clamp(val, low, high) {
|
|
|
1523
1524
|
SET currently_handling_message_id = NULL,
|
|
1524
1525
|
currently_handling_since = NULL
|
|
1525
1526
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1526
|
-
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function qh(t,e){let r=e??new Date(Date.now()-Bt()).toISOString();return In({holder_pid:t.holder_pid,started_at:t.started_at??""},r)}function Gh(t,e,r){return e==="force"||e==="session-idle"?e:r?"force":t.holder_pid!==null&&!we(t.holder_pid)?"dead-pid":"stale"}function Jh(t){return{sender:ci(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:t.holder_host,started_at:t.started_at}}function Xt(t,e){if(t!==1)throw new Error(`event projection CAS failed during ${e}`)}function mi(t,e,r){let n=Be(e),s=ci(r.sender_teamfile,r.sender_alias),i=Kl(r.receiver_teamfile,r.receiver_alias,{provider:r.receiver_provider,sessionId:r.receiver_session_id}),o={message_id:n,message_type:"request",sender:s,receiver:i,root_teamfile:r.root_teamfile,legacy:{table:"team_chat_log",id:e}};return
|
|
1527
|
+
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function qh(t,e){let r=e??new Date(Date.now()-Bt()).toISOString();return In({holder_pid:t.holder_pid,started_at:t.started_at??""},r)}function Gh(t,e,r){return e==="force"||e==="session-idle"?e:r?"force":t.holder_pid!==null&&!we(t.holder_pid)?"dead-pid":"stale"}function Jh(t){return{sender:ci(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:t.holder_host,started_at:t.started_at}}function Xt(t,e){if(t!==1)throw new Error(`event projection CAS failed during ${e}`)}function mi(t,e,r){let n=Be(e),s=ci(r.sender_teamfile,r.sender_alias),i=Kl(r.receiver_teamfile,r.receiver_alias,{provider:r.receiver_provider,sessionId:r.receiver_session_id}),o={message_id:n,message_type:"request",sender:s,receiver:i,root_teamfile:r.root_teamfile,legacy:{table:"team_chat_log",id:e}};return he(t,{stream_id:n,event_type:"CREATE",observedLastSeq:0,ts:r.created_at,payload:{...o,content:r.message,provider_prompt:r.provider_prompt??r.message,origin:r.origin,...Xh(t,r.sender_teamfile,r.sender_alias)}},()=>{di(t,r.receiver_teamfile,r.receiver_alias,n,r.created_at)}),n}function xn(t,e,r){let n=Be(e),s={message_id:n,message_type:"request",sender:ci(r.sender_teamfile,r.sender_alias),receiver:Kl(r.receiver_teamfile,r.receiver_alias,{provider:r.receiver_provider,sessionId:r.receiver_session_id}),root_teamfile:r.root_teamfile,legacy:{table:"team_chat_log",id:e}};return he(t,{stream_id:n,event_type:"HANDLED",observedLastSeq:1,ts:r.created_at,payload:{...s,outcome:r.status,receipt:r.response,error:r.error_detail,truncated:r.truncated===1}},()=>{ui(t,r.receiver_teamfile,r.receiver_alias,n)}),n}function Vh(t){return{sender:tt(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at}}function Yl(t,e,r,n){let s=t.prepare(`UPDATE agent_state
|
|
1527
1528
|
SET lease_id = NULL, sender_teamfile = NULL, sender_alias = NULL,
|
|
1528
1529
|
holder_pid = NULL, holder_host = NULL, started_at = NULL,
|
|
1529
1530
|
last_heartbeat_at = NULL, last_seq = ?
|
|
1530
1531
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1531
|
-
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Xt(s.changes,n)}function zl(t,e,r,n,s=null,i=!1){let o=Wh();if(r!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=Ht(t,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||qh(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let u=Gh(a,n,i),f=Jh(a),p=a.lease_id;
|
|
1532
|
+
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Xt(s.changes,n)}function zl(t,e,r,n,s=null,i=!1){let o=Wh();if(r!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=Ht(t,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||qh(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let u=Gh(a,n,i),f=Jh(a),p=a.lease_id;he(t,{stream_id:p,event_type:"INFLIGHT_RECLAIM",observedLastSeq:a.last_seq,ts:e.started_at,payload:{receiver:tt(e.receiver_teamfile,e.receiver_alias),reason:u,previous_holder:f}},y=>Yl(t,a,y,"INFLIGHT_RECLAIM")),a=Ht(t,e.receiver_teamfile,e.receiver_alias)}let l=a?.last_seq??0,c=`lease_${jh()}`;return he(t,{stream_id:c,event_type:"INFLIGHT_TAKE",observedLastSeq:l,ts:e.started_at,payload:{lease_id:c,receiver:tt(e.receiver_teamfile,e.receiver_alias),sender:tt(e.sender_teamfile,e.sender_alias),holder_pid:e.holder_pid,holder_host:o,started_at:e.started_at}},d=>{if(a===null){t.prepare(`INSERT INTO agent_state
|
|
1532
1533
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile,
|
|
1533
1534
|
sender_alias, holder_pid, holder_host, started_at,
|
|
1534
1535
|
last_heartbeat_at, last_seq)
|
|
@@ -1542,11 +1543,11 @@ fn clamp(val, low, high) {
|
|
|
1542
1543
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1543
1544
|
AND lease_id = ?
|
|
1544
1545
|
AND sender_teamfile = ? AND sender_alias = ?
|
|
1545
|
-
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,r,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function Er(t,e,r,n){let s=Ht(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||
|
|
1546
|
+
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,r,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function Er(t,e,r,n){let s=Ht(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||he(t,{stream_id:s.lease_id,event_type:r,observedLastSeq:s.last_seq,payload:{receiver:tt(e.receiver_teamfile,e.receiver_alias),...r==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:Vh(e)}:{lease_id:s.lease_id}}},i=>Yl(t,s,i,r))}function Zl(t,e){let r=Ht(t,e.teamfile,e.alias),n=r?.last_seq??0;he(t,{stream_id:e.lock_id,event_type:"TERMINAL_LOCK_TAKE",observedLastSeq:n,ts:e.started_at,payload:{receiver:tt(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(r===null){t.prepare(`INSERT INTO agent_state
|
|
1546
1547
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
1547
1548
|
VALUES (?, ?, ?, ?)`).run(e.teamfile,e.alias,e.lock_id,s);return}let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = ?, last_seq = ?
|
|
1548
1549
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1549
|
-
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);Xt(i.changes,"TERMINAL_LOCK_TAKE")})}function fi(t,e,r=!1){let n=Ht(t,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||
|
|
1550
|
+
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);Xt(i.changes,"TERMINAL_LOCK_TAKE")})}function fi(t,e,r=!1){let n=Ht(t,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||he(t,{stream_id:e.lock_id,event_type:r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE",observedLastSeq:n.last_seq,payload:{receiver:tt(e.teamfile,e.alias),lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host}},s=>{let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = NULL, last_seq = ?
|
|
1550
1551
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1551
1552
|
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);Xt(i.changes,r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE")})}function ec(t,e,r){let n=Ht(t,r.targetTeamfile,r.targetAlias);if(n===null){t.prepare(`INSERT INTO agent_state
|
|
1552
1553
|
(receiver_teamfile, receiver_alias, terminal_invocation_id,
|
|
@@ -1566,13 +1567,13 @@ fn clamp(val, low, high) {
|
|
|
1566
1567
|
terminal_invocation_host = NULL,
|
|
1567
1568
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1568
1569
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1569
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);Xt(s.changes,"terminal INVOCATION_FINISH")}var Kh="INVOCATION_START",Yh="INVOCATION_FINISH",zh="INVOCATION_NOTIFY_CLAIM";function nc(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function pi(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function sc(t,e){let r=Tt(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;
|
|
1570
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);Xt(s.changes,"terminal INVOCATION_FINISH")}var Kh="INVOCATION_START",Yh="INVOCATION_FINISH",zh="INVOCATION_NOTIFY_CLAIM";function nc(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function pi(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function sc(t,e){let r=Tt(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;he(t,{stream_id:r,event_type:Kh,observedLastSeq:0,ts:e.started_at,payload:{invocation_id:r,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=>{t.prepare(`INSERT INTO invocation_state
|
|
1570
1571
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1571
1572
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1572
1573
|
status, started_at, last_heartbeat_at, last_seq)
|
|
1573
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)`).run(r,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),pi(e)&&ec(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function bn(t,e){let r=Tt(e.id),n=nc(t,r);return n===null?!1:(
|
|
1574
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)`).run(r,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),pi(e)&&ec(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function bn(t,e){let r=Tt(e.id),n=nc(t,r);return n===null?!1:(he(t,{stream_id:r,event_type:Yh,observedLastSeq:n.last_seq,ts:e.ended_at??e.started_at,payload:{invocation_id:r,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(t.prepare(`UPDATE invocation_state
|
|
1574
1575
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1575
|
-
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,r,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${r}`);pi(e)&&rc(t,s,r)}),!0)}function ic(t,e,r,n){let s=Tt(e.id),i=nc(t,s);return i===null?!1:(
|
|
1576
|
+
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,r,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${r}`);pi(e)&&rc(t,s,r)}),!0)}function ic(t,e,r,n){let s=Tt(e.id),i=nc(t,s);return i===null?!1:(he(t,{stream_id:s,event_type:zh,observedLastSeq:i.last_seq,ts:n,payload:{invocation_id:s,notified_by:r,notified_at:n,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(t.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(r,n,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function oc(t,e,r){let n=Tt(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),pi(e)&&tc(t,n,r)}function ac(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,Tt(e))}function lc(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,Tt(e))}var Qh="other",Zh=["not_enough_information","dont_know","other_work"],RI=new Set([Qh,...Zh]),cc="@abort",dc="invalid_decision";var uc="workflow_escalation";function C(){return new Date().toISOString()}function ng(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!_c(t))return e;let r;try{r=new _n(t,{readonly:!0})}catch{return e}try{let n=[];try{n=r.prepare("SELECT teamfile_path, name, raw_text, raw_sha256, registered_at, last_seeded_at FROM root_team").all()}catch{}let s=[];try{s=r.prepare("SELECT key, value FROM lmctl_config").all()}catch{}return{rootTeams:n,config:s}}finally{r.close()}}function sg(t){if(t===":memory:"||!_c(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let r of["","-wal","-shm"]){let n=`${t}${r}`;try{tg(n,`${e}${r}`)}catch{}}return e}function fc(t,e){let r=e instanceof Error?e.message:String(e);try{let n=ng(t),s=sg(t),i=new An(Tn({dbPath:t}));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 ${t} to schema v${et} (${r}); 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}.
|
|
1576
1577
|
`:`
|
|
1577
1578
|
`)),i}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${t}: unusable (${r}), 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 pc(t,e){let r;try{return r=Tn({dbPath:t,allowSchemaSkew:e}),{dal:new An(r)}}catch(n){if(n instanceof hr)throw n;let s;if(r!==void 0)try{s=r.pragma("user_version",{simple:!0})}catch{}try{r?.close()}catch{}return{cause:n,dbVersion:s}}}var ig=3,yc=".recovery.lock",og=20,ag=50;function lg(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function cg(t){if(t===":memory:")return!0;try{return eg(`${t}${yc}`),!0}catch{return!1}}function dg(t){if(t!==":memory:")try{rg(`${t}${yc}`)}catch{}}function St(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",r={};for(let n=0;n<ig;n+=1)if(r=pc(t.path,e),r.dal!==void 0)return r.dal;if(r.dbVersion!==void 0&&r.dbVersion>et){let n=r.cause instanceof Error?r.cause.message:String(r.cause);throw new Error(`${t.path}: state.db schema is v${r.dbVersion}; this build (understands v${et}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<og;n+=1){if(cg(t.path))try{return fc(t.path,r.cause)}finally{dg(t.path)}lg(ag);let s=pc(t.path,e);if(s.dal!==void 0)return s.dal}return fc(t.path,r.cause)}var An=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=hg(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,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(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,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 y=this.getJob(a.id);return{claimed:!1,reason:y?.locked_until!==null&&y?.locked_until!==void 0&&y.locked_until>=i?"locked":"not_claimable",job_id:r,status:y?.status??a.status,locked_by:y?.locked_by??a.locked_by,locked_until:y?.locked_until??a.locked_until}}let p=this.getJob(a.id);return p===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:p}}),this.resumeRunTxn=e.transaction((r,n,s)=>gg("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);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(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==uc)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 d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="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!==cc&&!a.includes(n))return{resumed:!1,reason:dc};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}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,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,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=zl(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(r.receiver_teamfile,r.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,...r){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(...r)}insertWorkflow(e){hc(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,C()),n=this.getWorkflow(Number(r.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){hc(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===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(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,C());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.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,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,C());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);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(r,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,r){return this.stmts.setTriggerCursor.run(r,C(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(C(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}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 r=this.stmts.insertTeam.run(e.name,C());return this.stmts.getTeam.get(r.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 r=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(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,C(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,C());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=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(r.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,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.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 r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,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,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.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,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=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,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,C(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,C(),e)??null}closeIssue(e,r,n){let s=C(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,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,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.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,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=C();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,C(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,C(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=mc(),s=C();return this.stmts.insertChatbotSession.run(n,e,r??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,r,n,s){let i=C(),o=this.stmts.insertChatbotMessage.run(e,r,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,r){this.stmts.upsertConfig.run(e,r,C())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=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(r.changes===1)return this.stmts.getJob.get(r.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 r=C(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=C(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=C(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:C();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===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,r.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,r){return this.stmts.setJobRun.run(r,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,r){return this.stmts.setPromptDispatchCompleted.run(r??C(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,C());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} 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 r=C(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),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 r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.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,r){return this.stmts.loadMailboxCursor.get(e,r)??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,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);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 r=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(r.lastInsertRowid);return mi(this.db,n,e),xn(this.db,n,e),n})()}beginTeamChatLog(e){return this.db.transaction(()=>{let r=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(r.lastInsertRowid);return mi(this.db,n,e),n})()}finishTeamChatLog(e,r){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${e}`);xn(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{di(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>ui(this.db,e,r,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}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 r=e.started_at??C(),n=e.holder_host??hi(),s=e.last_heartbeat_at??r,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,Re(e.command),r,e.holder_pid??null,n,s,Re(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return sc(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,r,n={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,r];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,r){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.db.prepare(`
|
|
1578
1579
|
SELECT * FROM tracked_invocation
|
|
@@ -2037,12 +2038,12 @@ ${t}`:`${r}
|
|
|
2037
2038
|
`)}}var Da=[{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_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_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(t=>({...t,module:"lmctl"}));function lv(t){for(let e of Da)t.registerFunctionDoc(e)}function Rf(t={}){let e=new je;e.isAsyncMode=!0;let r=t.scriptArgs??[];if(e.setGlobal("args",[...r]),e.setGlobal("ARGV",[...r]),t.io){let n=t.io;e.registerFunction("print",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
2038
2039
|
`),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+`
|
|
2039
2040
|
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=ur(s,i);return n.stdout.write(o+`
|
|
2040
|
-
`),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 fr(s,i,o)}return mr(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 kf(t,e,r,n=process.env){t.registerFunction("lm_exit",(h=0)=>{let _=Math.floor(Number(h)),m=Number.isFinite(_)&&_>=0&&_<=255?_:1;throw new
|
|
2041
|
+
`),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 fr(s,i,o)}return mr(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 kf(t,e,r,n=process.env){t.registerFunction("lm_exit",(h=0)=>{let _=Math.floor(Number(h)),m=Number.isFinite(_)&&_>=0&&_<=255?_:1;throw new pe(m)},{min:0,max:1},"Exits the LMScript execution with an exit code"),t.registerFunction("lm_log",(...h)=>{let _=h.map(m=>typeof m=="object"?JSON.stringify(m):String(m)).join(" ");return e.stderr.write(_+(_.endsWith(`
|
|
2041
2042
|
`)?"":`
|
|
2042
2043
|
`)),_},void 0,"Writes formatted log message to stderr"),t.registerFunction("lm_error",(...h)=>{let _=h.map(m=>typeof m=="object"?JSON.stringify(m):String(m)).join(" ");return e.stderr.write(`error: ${_}
|
|
2043
2044
|
`),r.recordError(_),_},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(h,_=!1)=>{try{let m=rv(String(h),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2044
|
-
`);return!!_?[m.trim()].filter(g=>g.length>0):m.split(/\n\s*\n/u).map(g=>g.trim()).filter(Boolean)}catch(m){throw wt(e,`batch: ${m instanceof Error?m.message:String(m)}`),new
|
|
2045
|
-
`);try{if(T){let V=await j(e,q=>(Ln(q,g.teamfile,g.alias),vn(q,g.teamfile,g.alias)));if(V.busy){let q=V.reason==="in-flight"?`${g.alias} is servicing ${V.inFlight.sender_alias} (${V.inFlight.sender_teamfile}) since ${V.inFlight.started_at} \u2014 wait and retry`:V.source==="terminal-lock"?Jr(V.terminalLock):`${g.alias} is busy (interactive terminal); wait and retry`;return S!==null&&await j(e,me=>{me.finishTrackedInvocation(S,{status:"busy",exit_code:1,error:q,result_summary:"0 prompts completed"})}),wt(e,`batch: cannot start bundle: ${q}`),null}let te=await j(e,q=>iv(w,q)),ne=await j(e,q=>wn(q,{receiver_teamfile:g.teamfile,receiver_alias:g.alias,sender_teamfile:te?.teamfile??g.teamfile,sender_alias:te?.alias??"operator",ttlMs:jt(w)}));if(!ne.acquired){let q=`${g.alias} is servicing ${ne.current.sender_alias} (${ne.current.sender_teamfile}) since ${ne.current.started_at} \u2014 wait and retry`;return S!==null&&await j(e,me=>{me.finishTrackedInvocation(S,{status:"busy",exit_code:1,error:q,result_summary:"0 prompts completed"})}),wt(e,`batch: cannot start bundle: ${q}`),null}x={row:ne.lease,leaseId:ne.leaseId};let
|
|
2045
|
+
`);return!!_?[m.trim()].filter(g=>g.length>0):m.split(/\n\s*\n/u).map(g=>g.trim()).filter(Boolean)}catch(m){throw wt(e,`batch: ${m instanceof Error?m.message:String(m)}`),new pe(1)}};t.registerFunction("lm_read_prompts",(h,_=!1)=>s(h,_),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",h=>s(h,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",h=>{try{return Ye(String(h)).members.map(m=>({alias:m.alias,provider:m.provider,model:m.model,sessionid:m.session,sessiondir:m.sessiondir}))}catch(_){throw new Error(`Failed to read teamfile '${h}': ${_?.message||String(_)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(h,_)=>{try{let m=_t(String(h),String(_),e.dal);return{alias:m.alias,provider:m.provider,model:m.model,sessionid:m.sessionid,sessiondir:m.sessiondir,isLead:m.isLead,teamfile:m.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(h,_,m,E={})=>{if(typeof h!="string"){if(!h||Array.isArray(h)||typeof h!="object"||typeof h.provider!="string"||!h.provider.trim())throw new Error("lm_batch_open: member map requires provider");let A=_??{};if(typeof A!="object"||Array.isArray(A)||m!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let U={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...h},sourceMember:h,options:{...A},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(U),U}if(typeof _!="string"||typeof m!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let g;try{g=_t(String(h),String(_),e.dal)}catch(A){return wt(e,`batch: ${A?.message||String(A)}`),null}let v=Number(E?.promptCount??1),T=!!!E?.legacy&&v>1&&await sv(g),w={...e.env??n},S=await ov(e,{member:g,batchfile:String(m),promptCount:v,parentInvocationId:Nn(w.LMCTL_INVOCATION_ID)});S!==null&&(w.LMCTL_INVOCATION_ID=String(S));let x,b,k,$=!1;e.stderr.write(`batch ${nt()}: starting ${v} prompt${v===1?"":"s"} -> ${g.alias} (teamfile=${h} input=${m})
|
|
2046
|
+
`);try{if(T){let V=await j(e,q=>(Ln(q,g.teamfile,g.alias),vn(q,g.teamfile,g.alias)));if(V.busy){let q=V.reason==="in-flight"?`${g.alias} is servicing ${V.inFlight.sender_alias} (${V.inFlight.sender_teamfile}) since ${V.inFlight.started_at} \u2014 wait and retry`:V.source==="terminal-lock"?Jr(V.terminalLock):`${g.alias} is busy (interactive terminal); wait and retry`;return S!==null&&await j(e,me=>{me.finishTrackedInvocation(S,{status:"busy",exit_code:1,error:q,result_summary:"0 prompts completed"})}),wt(e,`batch: cannot start bundle: ${q}`),null}let te=await j(e,q=>iv(w,q)),ne=await j(e,q=>wn(q,{receiver_teamfile:g.teamfile,receiver_alias:g.alias,sender_teamfile:te?.teamfile??g.teamfile,sender_alias:te?.alias??"operator",ttlMs:jt(w)}));if(!ne.acquired){let q=`${g.alias} is servicing ${ne.current.sender_alias} (${ne.current.sender_teamfile}) since ${ne.current.started_at} \u2014 wait and retry`;return S!==null&&await j(e,me=>{me.finishTrackedInvocation(S,{status:"busy",exit_code:1,error:q,result_summary:"0 prompts completed"})}),wt(e,`batch: cannot start bundle: ${q}`),null}x={row:ne.lease,leaseId:ne.leaseId};let Ee=Sn(q=>j(e,me=>me.heartbeatAgentInflight(x.row,x.leaseId,q)));k={stop:()=>clearInterval(Ee)};let ht=qt(e,q=>`batch ${nt()}: opening provider session (${q}s elapsed)
|
|
2046
2047
|
`);try{let q={...w};try{let me=await j(e,M=>M.getRootTeam(g.teamfile)?.name??null);me!==null&&(q.LMBEE_TEAM_NAME=me)}catch{}b=await oa({provider:g.provider,sessionId:g.sessionid,cwd:g.sessiondir,env:q,...g.model!==void 0?{model:g.model}:{},...g.effort!==void 0?{effort:g.effort}:{},alias:g.alias,isLead:g.isLead,permissionMode:"yolo",holdOpen:ma(e,{teamfile:g.teamfile,alias:g.alias},q)}),$=!0}catch{k&&k.stop(),k=void 0,await Oa(e,x),x=void 0,$=!1}finally{ht.stop()}}let U={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(h),alias:String(_),batchfile:String(m),member:g,promptCount:v,useBundle:$,rootId:S,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:x,bundleSession:b,heartbeatTimer:k,closed:!1,env:w};return r.registerBatch(U),U}catch(A){if(k){try{k.stop()}catch{}k=void 0}if(x){try{await Oa(e,x)}catch{}x=void 0}if(b){try{await b.close()}catch{}b=void 0}if(S!==null)try{await j(e,U=>{U.finishTrackedInvocation(S,{status:"error",exit_code:1,error:A?.message||String(A),result_summary:"0 prompts completed"})})}catch{}throw A}},{min:1,max:4},"Opens a batch from a member map or a teamfile with lifecycle management"),t.registerFunction("lm_batch_turn",async(h,_,m,E)=>{let g=typeof h=="string"?r.getBatch(h):h?.id?r.getBatch(h.id)??h:void 0;if(!g)throw new Error("Invalid or unmanaged batch handle");if(g.kind==="agent"){if(r.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 w=g.member.sessionid,S=await d(g.member,String(_),g.options);return g.member.sessionid&&g.sourceMember.provider===g.member.provider&&g.sourceMember.sessionid===w&&(g.sourceMember.sessionid=g.member.sessionid),S.status!=="ok"&&(g.failed=!0),{status:S.status,reply:S.reply.replace(/\n+$/u,""),error:S.error}}finally{g.inFlight=!1}}let v=Number(m),I=Number(E);e.stderr.write(`batch ${nt()}: prompt ${v}/${I} -> ${g.member.alias}
|
|
2047
2048
|
`);let T=qt(e,w=>`batch ${nt()}: prompt ${v}/${I} still running (${w}s elapsed)
|
|
2048
2049
|
`);try{let w=await pa({teamfile:g.member.teamfile,alias:g.member.alias,prompt:String(_),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:x=>{T.poke(),x.kind==="warning"&&e.stderr.write(x.message)}}),S=w.replyText?String(w.replyText).replace(/\n+$/u,""):"";if(w.status!=="ok"){let x=w.status==="stalled"?"provider stalled":w.status==="empty"?"provider returned no content and no observed activity for this turn":w.message,b=`batch: stopped at prompt ${v}/${I} (${v-1} completed): ${x}; later prompts were not sent`;return g.rootFinish={status:w.status==="busy"?"busy":"error",exit_code:1,error:b,result_summary:`${v-1}/${I} prompts completed`},wt(e,b),{status:w.status,reply:S,error:b}}return{status:"ok",reply:S,error:null}}catch(w){let S=`batch: stopped at prompt ${v}/${I} (${v-1} completed): ${w instanceof Error?w.message:String(w)}; later prompts were not sent`;return g.rootFinish={status:"error",exit_code:1,error:S,result_summary:`${v-1}/${I} prompts completed`},wt(e,S),{status:"error",reply:"",error:S}}finally{T.stop()}},4,"Executes a prompt turn within a batch session"),t.registerFunction("lm_batch_close",async(h,_="done",m)=>{let E=typeof h=="string"?r.getBatch(h):h?.id?r.getBatch(h.id)??h:void 0;return E?(await Af(E,e,_==="done"?"done":_==="cancelled"?"cancelled":"error",m),!0):!1},{min:1,max:3},"Closes a batch session and cleans up resources"),t.registerFunction("lm_ratelimit_readings",async(h={})=>{try{if(!h||typeof h!="object"||Array.isArray(h))throw new Error("lm_ratelimit_readings: options must be a map");let _=h.providers??(h.provider===void 0?["all"]:[h.provider]);if(!Array.isArray(_)||_.some(E=>typeof E!="string"||!E||E.startsWith("-")))throw new Error("lm_ratelimit_readings: providers must be a list of provider names");let m=h.timeoutSeconds??15;if(typeof m!="number"||!Number.isFinite(m)||m<=0)throw new Error("lm_ratelimit_readings: timeoutSeconds must be a positive finite number");return bf({providers:_.length?_:["all"],timeoutSeconds:m,env:e.env??n,progress:E=>{e.stderr.write(`${E}
|
|
@@ -2063,7 +2064,7 @@ ${t}`:`${r}
|
|
|
2063
2064
|
`)}};try{let d=Cf(r,e,i,n);l=d;let u=await d.runAsync(t,{file:s,stderr:f=>{r.stderr.write(f.endsWith(`
|
|
2064
2065
|
`)?f:`${f}
|
|
2065
2066
|
`)}});if(c(),u.exitCode!==void 0)return u.exitCode;if(!u.success){for(let f of u.diagnostics){let p=f.file?`${f.file}:${f.line}:${f.column}`:`${f.line}:${f.column}`;r.stderr.write(`error:${p}: ${f.message}
|
|
2066
|
-
`)}return 1}return i.hasErrors()||u.errors&&u.errors.length>0?1:0}catch(d){return c(),d instanceof
|
|
2067
|
+
`)}return 1}return i.hasErrors()||u.errors&&u.errors.length>0?1:0}catch(d){return c(),d instanceof pe||d?.name==="LMScriptExit"?d.exitCode:(r.stderr.write(`error: ${d instanceof Error?d.message:String(d)}
|
|
2067
2068
|
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(r)}}var dv=`# batchscript.lms - Test-only comparison with procedural lmctl batch
|
|
2068
2069
|
# Arguments: [teamfile, alias, batchfile, flags...]
|
|
2069
2070
|
|
|
@@ -2131,4 +2132,4 @@ for (i = 0; i < len(prompts); i = i + 1) {
|
|
|
2131
2132
|
|
|
2132
2133
|
lm_batch_close(handle, "done");
|
|
2133
2134
|
lm_exit(0);
|
|
2134
|
-
`;export{dv as BATCH_LMS,Da as LMCTL_FUNCTION_DOCS,je as LMScript,
|
|
2135
|
+
`;export{dv as BATCH_LMS,Da as LMCTL_FUNCTION_DOCS,je as LMScript,pe as LMScriptExit,or as ResourceRegistry,Rf as createBaseScriptEngine,Cf as createLmScriptEngine,Nf as lmctlModule,lv as registerLmctlDocs,kf as registerLmctlHostFunctions,Lf as registerLmctlModule,cv as runScriptEngine};
|