@lmctl-ai/lmctl 0.2.35 → 0.2.37
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/data/price-data.json +1 -1
- package/dist/cli/index.js +399 -399
- package/dist/cli/script.js +182 -182
- package/dist/db/sqlite.d.ts +9 -3
- package/package.json +1 -1
package/dist/cli/script.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);if(e[0]!=="---")throw new We("frontmatter must start at line 1 with `---` on its own line");let r={},n=-1;for(let o=1;o<e.length;o++){let a=e[o];if(a==="---"){n=o;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new We(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!
|
|
3
|
-
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=
|
|
4
|
-
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(
|
|
5
|
-
allowed keys: ${
|
|
6
|
-
`)}){let n=Xe(t,
|
|
7
|
-
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=
|
|
8
|
-
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??
|
|
9
|
-
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(
|
|
1
|
+
var Cg=Object.create;var Ci=Object.defineProperty;var Og=Object.getOwnPropertyDescriptor;var Dg=Object.getOwnPropertyNames;var Mg=Object.getPrototypeOf,Fg=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(t&&(e=t(t=0)),e);var Pg=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Yl=(t,e)=>{for(var r in e)Ci(t,r,{get:e[r],enumerable:!0})},$g=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Dg(e))!Fg.call(t,s)&&s!==r&&Ci(t,s,{get:()=>e[s],enumerable:!(n=Og(e,s))||n.enumerable});return t};var zl=(t,e,r)=>(r=t!=null?Cg(Mg(t)):{},$g(e||!t||!t.__esModule?Ci(r,"default",{value:t,enumerable:!0}):r,t));function fc(t){if(t.length===0||!t.startsWith("---"))throw new We("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
2
|
+
`);if(e[0]!=="---")throw new We("frontmatter must start at line 1 with `---` on its own line");let r={},n=-1;for(let o=1;o<e.length;o++){let a=e[o];if(a==="---"){n=o;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new We(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!Qg.has(c))throw new We(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Xn.join(", ")}`);r[c]=u}if(n===-1)throw new We("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Xn)if(r[o]===void 0)throw new We(`missing required frontmatter key "${o}" \u2014 required: ${Xn.join(", ")}`);let s=0;for(let o=0;o<=n;o++)s+=e[o].length+1;s>t.length&&(s=t.length);let i=r.members.split(",").map(o=>o.trim()).filter(Boolean);return{title:r.title,description:r.description,members:i,bodyOffset:s}}var Xn,Qg,We,pc=A(()=>{"use strict";Xn=["title","description","members"],Qg=new Set(Xn),We=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as Zg,writeFileSync as Ak,renameSync as kk,existsSync as gc}from"node:fs";import{basename as e_,resolve as tr,dirname as Ui}from"node:path";function r_(t){let e={},r=/(\w+)=(?:"([^"]*)"|([\S]*))/g,n;for(;(n=r.exec(t))!==null;){let s=n[1],i=n[2]!==void 0?n[2]:n[3];e[s]=i}return e}function n_(t){return/^\s*_MEMBER_\s+\S/.test(t)}function s_(t){return/^\s*_SESSION_\s+\S/.test(t)}function i_(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function qn(t){return/\.(?:lmctl|lmc)$/i.test(t)}function Xr(t){return e_(t).replace(/\.(?:lmctl|lmc)$/i,"")}function $e(t){let e=Zg(t,"utf-8"),r=Ui(tr(t)),n=Hi(e,Xr(t),{baseDir:r,sourcePath:tr(t)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=tr(r,s.sessiondir));return n}function Hi(t,e,r={}){let n=[],s=[];r.sourcePath,r.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
3
|
+
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=fc(i)}catch(l){if(l instanceof We)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
4
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(s_(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(i_(c)||!n_(c))continue;let d=r_(c);for(let h of Object.keys(d))if(!hc.includes(h))throw new Error(`line ${u}: unknown key "${h}" on _MEMBER_ line: ${c.trim()}
|
|
5
|
+
allowed keys: ${hc.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!d.alias){s.push(`line ${u}: member line missing required alias: ${c.trim()}`);continue}let m={alias:d.alias,provider:d.provider||"",extra:{}};d.sessionid&&(m.session=d.sessionid),Object.prototype.hasOwnProperty.call(d,"sessiondir")&&(m.sessiondir=d.sessiondir),d.teamfile&&(m.teamfile=d.teamfile),d.model&&(m.model=d.model),d.effort&&(m.effort=d.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function Bi(t,e){let r=[];for(let i of t.parseErrors)r.push({field:"session",message:i});let n=t.members.filter(i=>i.alias.toLowerCase()===ji.toLowerCase());n.length>1&&r.push({field:ji,message:`${n.length} alias=Lead found (max 1)`});let s=new Set;for(let i of t.members){let o=i.alias.toLowerCase();if(s.has(o)&&r.push({field:i.alias,message:`Duplicate alias "${i.alias}" (case-insensitive)`}),s.add(o),i.teamfile){let a=e?tr(e,i.teamfile):tr(i.teamfile);if(!gc(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=$e(a),c=rr(l);c?c.session||r.push({field:i.alias,message:`Team at ${i.teamfile} lead has no session ID. Run: lmctl seed`}):r.push({field:i.alias,message:`Team at ${i.teamfile} has no lead session`})}}else t_.has(i.provider)||r.push({field:i.alias,message:`Invalid provider "${i.provider}"`});i.sessiondir!==void 0&&i.sessiondir===""&&r.push({field:i.alias,message:"sessiondir is empty"})}return r}function rr(t){return t.members.find(e=>e.alias.toLowerCase()===ji.toLowerCase())}function Wi(t,e,r,n={}){let s=n.requireSession??!0;if(!t.teamfile)throw new Error(`Member "${t.alias}" is not a team reference`);let i=tr(e,t.teamfile),o=r??new Set;if(o.has(i))throw new Error(`Circular team reference: ${t.alias} \u2192 ${i} (already visited: ${[...o].join(" \u2192 ")})`);if(o.add(i),!gc(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=$e(i),l=rr(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return Wi(l,Ui(i),o,n);if(s&&!l.session)throw new Error(`Team at ${i} lead has no session ID. Run: lmctl seed`);return{provider:l.provider,session:l.session??"",sessiondir:l.sessiondir||Ui(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function _c(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var ji,t_,hc,et=A(()=>{"use strict";pc();ji="Lead",t_=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"]);hc=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as o_}from"node:crypto";import{existsSync as yc,readFileSync as Ec,realpathSync as a_}from"node:fs";import{dirname as l_,resolve as Tc}from"node:path";function Xe(t,e){let r=Tc(t);if(yc(r))return a_(r);if(e!==void 0){let n=d_(t,r,e);if(n!==null)return n}return r}function Jn(t,e){let r=l_(e),n=Hi(t,Xr(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Tc(r,s.sessiondir));return n}function nr(t,e,r=n=>{process.stderr.write(`warning: ${n}
|
|
6
|
+
`)}){let n=Xe(t,c_(e)?e:void 0);if(yc(n)){let i=Ec(n,"utf8"),o=Jn(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&&u_(o)&&f_(e,n,o,i,r),o}let s=e?.getRootTeam(n)??null;throw s!==null?new Error(`teamfile missing on disk: ${n} (registered ${s.registered_at}; the file was renamed or deleted \u2014 seed the team at its new path)`):new Error(`teamfile not found: ${t}`)}function c_(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function d_(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);return n===null?null:n.teamfile_path}function u_(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=Xi)}function qi(t,e,r){let n=Xe(e),s=r.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=Xi);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=Xe(i.teamfile_path),o===n)continue;a=Ec(o,"utf8")}catch(c){if(m_(c))continue;throw c}let l=Jn(a,o);for(let c of s){let u=l.members.find(d=>d.teamfile===void 0&&d.session===c.session&&(d.session?.length??0)>=Xi);if(u!==void 0)throw new Gn(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${u.alias} both use sessionid "${c.session}"`)}}}function m_(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function f_(t,e,r,n,s){try{qi(t,e,r)}catch(o){if(!(o instanceof Gn))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:o_("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var Xi,Gn,qr=A(()=>{"use strict";et();Xi=5,Gn=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{randomUUID as p_}from"node:crypto";import{closeSync as h_,openSync as g_,readFileSync as Sc,statSync as __,unlinkSync as Gi,writeFileSync as y_}from"node:fs";function vc(t,e){return`${t}.seed-${e.toLowerCase()}.lock`}function bc(t){let e;try{e=JSON.parse(Sc(t,"utf8"))}catch(n){return n.code==="ENOENT"?!1:wc(t)}let r=typeof e=="object"&&e!==null&&"pid"in e?e.pid:void 0;if(typeof r!="number"||!Number.isInteger(r)||r<=0)return wc(t);try{return process.kill(r,0),!0}catch(n){return n.code!=="ESRCH"}}function wc(t){try{return Date.now()-__(t).mtimeMs<3e5}catch{return!1}}function Ji(t,e){return bc(vc(t,e))}function Ic(t,e){let r=vc(t,e),n=JSON.stringify({pid:process.pid,token:p_()});for(let s=0;s<2;s+=1)try{let i=g_(r,"wx");try{y_(i,n)}catch(o){throw Gi(r),o}finally{h_(i)}return()=>{try{Sc(r,"utf8")===n&&Gi(r)}catch(o){if(o.code!=="ENOENT")throw o}}}catch(i){if(i.code!=="EEXIST")throw i;if(bc(r))throw new Error(`${e}: seed already in progress; wait for it to finish`);try{Gi(r)}catch(o){if(o.code!=="ENOENT")throw o}}throw new Error(`${e}: could not acquire seed marker`)}var Ki=A(()=>{"use strict"});import{existsSync as E_}from"node:fs";import{dirname as xc}from"node:path";function v_(t){return T_.test(t)||w_.test(t)||S_.test(t)}function Ac(t){return Kn.test(t)}function Vn(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!qn(r)||!Kn.test(n)?null:{teamfile:r,alias:n}}function tt(t,e,r){if(!qn(t))throw new he(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl or .lmc extension).`);if(!Ac(e))throw new he(`lmctl: "${e}" is not a valid alias (must match ${Kn.source}).`);let n=Xe(t,r);if(r===void 0&&!E_(n))throw new he(`lmctl: teamfile not found: ${t}`);let s;try{s=nr(n,r)}catch(o){throw new he(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new he(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=_c(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new he(`lmctl: alias "${e}" not found in ${t}.
|
|
7
|
+
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=Wi(i,xc(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(Ji(n,i.alias))throw new he(`lmctl: alias "${i.alias}" is being seeded. Wait for the seed to finish, then retry this prompt.`);if(i.session===void 0)throw s.members.some(o=>Ji(n,o.alias))?new he(`lmctl: alias "${i.alias}" has no session ID yet, and a seed is currently in progress for this team. Wait for the seed to finish, then retry this prompt.`):new he(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
8
|
+
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??xc(n),isLead:rr(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function kc(t,e){let{target:r,alias:n,flags:s}=e;if(s.run!==void 0||s.project!==void 0||s.workflow!==void 0){if(r!==void 0)return{mode:"error",message:`lmctl ${t.name}: --run/--project/--workflow (managed mode) are mutually exclusive with a positional target "${r}" \u2014 pick one form.`};let o={mode:"managed"};return s.run!==void 0&&(o.run=s.run),s.project!==void 0&&(o.project=s.project),s.workflow!==void 0&&(o.workflow=s.workflow),o}if(r!==void 0){let o=Vn(r);if(o!==null)return n!==void 0&&n!==o.alias?{mode:"error",message:`lmctl ${t.name}: got "${r}" AND second positional "${n}" \u2014 pick one form.`}:{mode:"ai-team",teamfile:o.teamfile,alias:o.alias};if(qn(r))return n!==void 0?Ac(n)?{mode:"ai-team",teamfile:r,alias:n}:{mode:"error",message:`lmctl ${t.name}: "${n}" is not a valid alias (must match ${Kn.source}).`}:t.allowsBareTeamfile?{mode:"ai-team",teamfile:r}:{mode:"error",message:`lmctl ${t.name}: alias required.
|
|
9
|
+
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(v_(r)){if(n!==void 0)return{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.`};if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: "${r}" is a bare sessionid, but ${t.name} is teamfile-only (a sessionid carries no provider resume incantation).`};let a={mode:"ai-team-raw",sessionid:r};return s.provider!==void 0&&(a.provider=s.provider),a}return n!==void 0?{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.
|
|
10
10
|
Either drop the second arg, or pass <teamfile>.lmctl as the first arg.`}:{mode:"error",message:`lmctl ${t.name}: can't infer target type from "${r}".
|
|
11
11
|
Expected one of: <path>.lmctl, <path>.lmctl:<alias>, <sessionid>.`}}if(s.session!==void 0){if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: --session (raw mode) is not supported by ${t.name}.`};let o={mode:"ai-team-raw",sessionid:s.session};return s.provider!==void 0&&(o.provider=s.provider),o}return{mode:"error",message:`lmctl ${t.name}: a target is required.
|
|
12
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var he,
|
|
13
|
-
`)}catch{}}function
|
|
14
|
-
`)){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
|
|
15
|
-
`,"utf8"),Ce.renameSync(r,t)}catch(n){try{Ce.unlinkSync(r)}catch{}throw n}}function
|
|
16
|
-
`)),N({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Rc(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function F_(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=Dc(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=P_(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==zn&&c[1]!==Qn)continue;let u=e.get(c[1])??{};if(c[2]==="command"){let d=Mc(l);if(d===null)return null;u.command=d}else if(c[2]==="args"){let d=U_(l);if(d===null)return null;u.args=d}e.set(c[1],u)}let n=new Set;for(let[s,i]of e.entries())s===zn&&Pc(i.command,i.args)&&n.add(s),s===Qn&&$c(i.command,i.args)&&n.add(s);return n}function P_(t,e){if(t.startsWith("mcp_servers"))return Zn(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=Zn(t);return r===null?null:[...e,...r]}function Dc(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:Zn(e[1])}function $_(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 Zn(r)}function Zn(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 Mc(t){let e=Fc(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 U_(t){let e=Fc(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=>Mc(s.trim()));return n.some(s=>s===null)?null:n}function Fc(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 j_(t){return nr(t)?t.type==="stdio"&&typeof t.command=="string"&&Pc(t.command,t.args):!1}function H_(t){return!nr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&jc(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"&&Uc(t.command[0],[t.command[1],t.command[2]])}function B_(t){return nr(t)?t.type==="stdio"&&$c(t.command,t.args):!1}function W_(t){return!nr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Hc(t.command[0])&&t.command[1]==="mcp"}function Pc(t,e){return jc(t)&&Bc(e)||Uc(t,e)}function $c(t,e){return Hc(t)&&Bc(e)}function Uc(t,e){return X_(t)&&Array.isArray(e)&&e.length===2&&q_(e[0])&&e[1]==="mcp"}function jc(t){return typeof t=="string"&&Ki(t)==="lmctl"}function Hc(t){return typeof t=="string"&&Ki(t)==="lmctl0"}function X_(t){if(typeof t!="string")return!1;let e=Ki(t).toLowerCase();return e==="node"||e==="node.exe"}function q_(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 Ki(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function Bc(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function nr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var zn,Qn,R_,Ce,Vi,es=A(()=>{"use strict";z();zn="lmctl",Qn="lmctl0",R_={existsSync:v_,mkdirSync:b_,readFileSync:I_,writeFileSync:k_,renameSync:x_,unlinkSync:A_},Ce=R_});import{basename as G_}from"node:path";function Vc(t,e){let r=new Date(e.now.getTime()-mt()).toISOString(),n=zc(t,r).filter(h=>!h.sender.teamfile.startsWith("prompt:")),s=Y_(e.sender,n),i=z_(e.sender,n);i!==null&&i.teamfile===e.root&&!Jc(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(h=>Jc(h,o)),c=l.map(h=>h.at).filter(h=>h!==null).sort((h,_)=>_-h)[0]??null,u=c!==null&&e.now.getTime()-c<J_,d=Yi(e.sender,n).length;return{stop:l.length>=1&&u&&d>=V_,chain:Q_(a)}}function Kc(t,e){let r=new Date(e.now.getTime()-mt()).toISOString(),n=zc(t,r),s=Yi(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 mt(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Gc;let r=Number(e);return!Number.isFinite(r)||r<=0?Gc:r}function Yc(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function K_(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 zc(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(K_).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function Y_(t,e,r={}){let n=new Map;for(let a of e)n.set(Ct(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([Ct(t)]);for(let a=0;a<64;a+=1){let l=n.get(Ct(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 u=Ct(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function Yi(t,e){let r=Ct(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=Ct(l.sender),u=Ct(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(u)||(n.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function z_(t,e){let r=Yi(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Jc(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function Ct(t){return`${t.teamfile}\0${t.alias}`}function Q_(t){return t.map(e=>`${G_(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var J_,V_,Gc,ts=A(()=>{"use strict";J_=6e4,V_=2,Gc=8*60*60*1e3});import{existsSync as Z_}from"node:fs";import{createRequire as ey}from"node:module";function ty(){return zi===null&&(zi=ey(import.meta.url)("node:sqlite").DatabaseSync),zi}function Qi(t){return t.length===1&&ry(t[0])?[t[0]]:t}function ry(t){if(!to(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function to(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var zi,Zi,or,eo,rs=A(()=>{"use strict";zi=null;Zi=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!Z_(e))throw new Error("unable to open database file");this.name=e,this.handle=new(ty())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new eo(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)}}},or=Zi,eo=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...Qi(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...Qi(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...Qi(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&to(e)?Object.values(e):to(e)?{...e}:e}}});import{createHash as ny}from"node:crypto";function sy(t,e,r){return ny("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function be(t,e,r){let n=sy(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)
|
|
12
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var he,T_,w_,S_,Kn,Lt=A(()=>{"use strict";et();et();qr();Ki();he=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},T_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,w_=/^ses_[A-Za-z0-9_-]+$/,S_=/^session_[A-Za-z0-9_-]+$/,Kn=/^[A-Za-z][A-Za-z0-9_-]*$/});import{readFileSync as Lc,appendFileSync as b_,mkdirSync as I_,existsSync as Kk,readdirSync as Vk,unlinkSync as Yk}from"node:fs";import{join as zn,dirname as x_}from"node:path";import{homedir as A_}from"node:os";function Vi(){return zn(A_(),".lmctl")}function te(){if(Cc||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-Rc>=k_&&(Nc=L_(),Rc=t),Nc}function N_(){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 _e(t,e){if(e?.verbose){if(!Cc)return}else if(!e?.always&&!te())return;try{R_();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};b_(Yn,JSON.stringify(r)+`
|
|
13
|
+
`)}catch{}}function R_(){if(!Yn){let e=N_().slice(0,13).replace("T","-");Yn=zn(Vi(),`debug-${e}.log`)}I_(x_(Yn),{recursive:!0})}function xe(...t){_e({event:"legacy",msg:t.join(" ")})}function ce(...t){_e({event:"legacy",msg:t.join(" ")},{verbose:!0})}function N(t){_e(t,{always:!0})}function L_(){return C_()||O_()}function C_(){try{let t=Lc(zn(Vi(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
14
|
+
`)){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 O_(){try{let t=Lc(zn(Vi(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Cc,Nc,Rc,k_,Yn,z=A(()=>{"use strict";Cc=!1,Nc=!1,Rc=0,k_=5e3;Yn=null});import{existsSync as D_,mkdirSync as M_,readFileSync as F_,renameSync as P_,unlinkSync as $_,writeFileSync as U_}from"node:fs";import{homedir as Dc}from"node:os";import{dirname as Gr,join as ye,resolve as j_}from"node:path";function ir(t,e,r){let n=Gr(j_(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())qe(ye(o,".mcp.json"),"mcpServers",[dt(),ut()]),a.has("opencode")&&qe(ye(o,".opencode","opencode.json"),"mcp",[Mc(),Fc()]),a.has("kimi")&&qe(ye(o,".kimi-code","mcp.json"),"mcpServers",[dt(),ut()]);for(let o of s)q_(o)}function B_(t=Yi??Dc()){return ye(t,".copilot","mcp-config.json")}function W_(t,e){Ce.mkdirSync(Gr(t),{recursive:!0});let r=ye(Gr(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Ce.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
15
|
+
`,"utf8"),Ce.renameSync(r,t)}catch(n){try{Ce.unlinkSync(r)}catch{}throw n}}function X_(t,e){Ce.mkdirSync(Gr(t),{recursive:!0});let r=ye(Gr(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Ce.writeFileSync(r,e,"utf8"),Ce.renameSync(r,t)}catch(n){try{Ce.unlinkSync(r)}catch{}throw n}}function qe(t,e,r){try{if(!Ce.existsSync(t))return;let n=JSON.parse(Ce.readFileSync(t,"utf8"));if(!sr(n)||!sr(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,W_(t,n),N({event:"mcp_cleanup",path:t,removed:i})}catch{}}function dt(){return{name:Zn,shouldRemove:Z_}}function Mc(){return{name:Zn,shouldRemove:ey}}function ut(){return{name:Qn,shouldRemove:z_}}function Fc(){return{name:Qn,shouldRemove:Q_}}function q_(t){let e=Yi??Dc();switch(t){case"copilot":qe(B_(e),"mcpServers",[dt(),ut()]);return;case"claude":qe(ye(e,".claude.json"),"mcpServers",[dt(),ut()]);return;case"gemini":qe(ye(e,".gemini","settings.json"),"mcpServers",[dt(),ut()]);return;case"qwen":qe(ye(e,".qwen","settings.json"),"mcpServers",[dt(),ut()]);return;case"agy":qe(ye(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[dt(),ut()]);return;case"opencode":qe(ye(e,".config","opencode","opencode.json"),"mcp",[Mc(),Fc()]);return;case"kimi":qe(ye(Yi===void 0?process.env.KIMI_CODE_HOME??ye(e,".kimi-code"):ye(e,".kimi-code"),"mcp.json"),"mcpServers",[dt(),ut()]);return;case"codex":G_(ye(e,".codex","config.toml"));return;default:return}}function G_(t){try{if(!Ce.existsSync(t))return;let e=Ce.readFileSync(t,"utf8"),r=J_(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=Pc(l);if(c===null)return;if(c!==void 0){if(Oc(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 u=V_(l);if(u===null)return;if(u!==void 0&&Oc(u,r)){i.add(u[1]);continue}s.push(l)}if(i.size===0)return;X_(t,s.join(`
|
|
16
|
+
`)),N({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Oc(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function J_(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=Pc(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=K_(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Qn&&c[1]!==Zn)continue;let u=e.get(c[1])??{};if(c[2]==="command"){let d=$c(l);if(d===null)return null;u.command=d}else if(c[2]==="args"){let d=Y_(l);if(d===null)return null;u.args=d}e.set(c[1],u)}let n=new Set;for(let[s,i]of e.entries())s===Qn&&jc(i.command,i.args)&&n.add(s),s===Zn&&Hc(i.command,i.args)&&n.add(s);return n}function K_(t,e){if(t.startsWith("mcp_servers"))return es(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=es(t);return r===null?null:[...e,...r]}function Pc(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:es(e[1])}function V_(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 es(r)}function es(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 $c(t){let e=Uc(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 Y_(t){let e=Uc(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=>$c(s.trim()));return n.some(s=>s===null)?null:n}function Uc(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 z_(t){return sr(t)?t.type==="stdio"&&typeof t.command=="string"&&jc(t.command,t.args):!1}function Q_(t){return!sr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Wc(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"&&Bc(t.command[0],[t.command[1],t.command[2]])}function Z_(t){return sr(t)?t.type==="stdio"&&Hc(t.command,t.args):!1}function ey(t){return!sr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Xc(t.command[0])&&t.command[1]==="mcp"}function jc(t,e){return Wc(t)&&qc(e)||Bc(t,e)}function Hc(t,e){return Xc(t)&&qc(e)}function Bc(t,e){return ty(t)&&Array.isArray(e)&&e.length===2&&ry(e[0])&&e[1]==="mcp"}function Wc(t){return typeof t=="string"&&zi(t)==="lmctl"}function Xc(t){return typeof t=="string"&&zi(t)==="lmctl0"}function ty(t){if(typeof t!="string")return!1;let e=zi(t).toLowerCase();return e==="node"||e==="node.exe"}function ry(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 zi(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function qc(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function sr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Qn,Zn,H_,Ce,Yi,ts=A(()=>{"use strict";z();Qn="lmctl",Zn="lmctl0",H_={existsSync:D_,mkdirSync:M_,readFileSync:F_,writeFileSync:U_,renameSync:P_,unlinkSync:$_},Ce=H_});import{basename as ny}from"node:path";function zc(t,e){let r=new Date(e.now.getTime()-mt()).toISOString(),n=ed(t,r).filter(h=>!h.sender.teamfile.startsWith("prompt:")),s=ay(e.sender,n),i=ly(e.sender,n);i!==null&&i.teamfile===e.root&&!Yc(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(h=>Yc(h,o)),c=l.map(h=>h.at).filter(h=>h!==null).sort((h,_)=>_-h)[0]??null,u=c!==null&&e.now.getTime()-c<sy,d=Qi(e.sender,n).length;return{stop:l.length>=1&&u&&d>=iy,chain:cy(a)}}function Qc(t,e){let r=new Date(e.now.getTime()-mt()).toISOString(),n=ed(t,r),s=Qi(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 mt(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Vc;let r=Number(e);return!Number.isFinite(r)||r<=0?Vc:r}function Zc(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function oy(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 ed(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(oy).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function ay(t,e,r={}){let n=new Map;for(let a of e)n.set(Ct(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([Ct(t)]);for(let a=0;a<64;a+=1){let l=n.get(Ct(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 u=Ct(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function Qi(t,e){let r=Ct(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=Ct(l.sender),u=Ct(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(u)||(n.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function ly(t,e){let r=Qi(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Yc(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function Ct(t){return`${t.teamfile}\0${t.alias}`}function cy(t){return t.map(e=>`${ny(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var sy,iy,Vc,rs=A(()=>{"use strict";sy=6e4,iy=2,Vc=8*60*60*1e3});import{existsSync as dy}from"node:fs";import{createRequire as uy}from"node:module";function my(){return Zi===null&&(Zi=uy(import.meta.url)("node:sqlite").DatabaseSync),Zi}function hy(t){let e=py[t];if(e!==void 0)return e;let r=fy[t&255];return r!==void 0?r:`SQLITE_UNKNOWN_${t}`}function Ot(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=hy(t.errcode)),t}function gy(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function _y(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function eo(t){return t.length===1&&yy(t[0])?[t[0]]:t}function yy(t){if(!no(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function no(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Zi,fy,py,to,ar,ro,ns=A(()=>{"use strict";Zi=null;fy={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",25:"SQLITE_RANGE",26:"SQLITE_NOTADB"},py={275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE",261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB"};to=class{name;handle;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!dy(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(my())(e,{readOnly:r.readonly===!0})}catch(n){Ot(n)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${r.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new ro(this.handle.prepare(e))}catch(r){Ot(r)}}exec(e){try{this.handle.exec(e)}catch(r){Ot(r)}}pragma(e,r){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}if(r?.simple===!0){let s=this.prepare(n).get();return s===void 0?void 0:Object.values(s)[0]}return this.prepare(n).all()}transaction(e){let r=(...n)=>this.runTransaction("BEGIN",e,n);return r.immediate=(...n)=>this.runTransaction("BEGIN IMMEDIATE",e,n),r}get inTransaction(){return this.handle.isTransaction}close(){try{this.handle.close()}catch(e){Ot(e)}}runTransaction(e,r,n){if(!this.inTransaction){this.exec(e);try{let i=r(...n);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!gy(o))throw o}throw i}}let s=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=r(...n);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!_y(o))throw o}throw i}}};ar=to,ro=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){try{let r=this.handle.get(...eo(e));return this.normalizeRow(r)}catch(r){Ot(r)}}all(...e){try{return this.handle.all(...eo(e)).map(r=>this.normalizeRow(r))}catch(r){Ot(r)}}run(...e){try{let r=this.handle.run(...eo(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}catch(r){Ot(r)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&no(e)?Object.values(e):no(e)?{...e}:e}}});import{createHash as Ey}from"node:crypto";function Ty(t,e,r){return Ey("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function be(t,e,r){let n=Ty(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)
|
|
17
17
|
VALUES (?, ?, ?, ?, ?)
|
|
18
|
-
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
|
|
18
|
+
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 ss=A(()=>{"use strict"});import{createHash as wy}from"node:crypto";function Dt(t,e){return t==null?null:{teamfile:t,alias:e??""}}function Sy(t,e,r){return`lease_${wy("sha256").update(`${t}\0${e}\0${r}`).digest("hex").slice(0,16)}`}function is(t,e,r,n){r.forEach((s,i)=>{be(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 vy(t){let e=`msg_tcl_${t.id}`,r=Dt(t.sender_teamfile,t.sender_alias),n=Dt(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:G.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:G.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 by(t){let e=`msg_mbx_${t.id}`,r=Dt(t.sender_teamfile,t.sender_alias),n=Dt(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:G.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:G.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:G.RESPONSE_DELIVERED,ts:t.delivered_at,payload:{...i,message_type:"response",receipt:t.receipt}}),{streamId:e,events:o}}return o.push({event_type:G.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.payload,correlation_status:"legacy-unavailable"}}),o.push({event_type:G.ENQUEUE,ts:t.created_at,payload:{...i,message_type:"request"}}),t.waited_at!==null&&o.push({event_type:G.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:G.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:G.DELIVERED,ts:t.delivered_at,payload:{...i,receipt:t.receipt}}),{streamId:e,events:o}}function Iy(t){let e=`inv_${t.id}`,r=Dt(t.target_teamfile,t.target_alias),n={table:"tracked_invocation",id:t.id},s=[{event_type:G.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:G.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:G.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 xy(t){let e=Sy(t.receiver_teamfile,t.receiver_alias,t.started_at),r=Dt(t.receiver_teamfile,t.receiver_alias),n=Dt(t.sender_teamfile,t.sender_alias);return{streamId:e,events:[{event_type:G.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 os(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function td(t){let e={appended:0,skipped:0},r={team_chat_log:0,agent_mailbox:0,tracked_invocation:0,agent_inflight:0};t.transaction(()=>{if(os(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}=vy(i);is(t,a,l,e),r.team_chat_log+=e.appended+e.skipped-o}if(os(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}=by(i);is(t,a,l,e),r.agent_mailbox+=e.appended+e.skipped-o}if(os(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}=Iy(i);is(t,a,l,e),r.tracked_invocation+=e.appended+e.skipped-o}if(os(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}=xy(i);is(t,a,l,e),r.agent_inflight+=e.appended+e.skipped-o}Ay(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 Ay(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);ky(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 ky(t,e,r,n,s){switch(n){case G.ENQUEUE:case G.RESPONSE_ENQUEUE:{let i=n===G.RESPONSE_ENQUEUE;t.prepare(`INSERT INTO message_pending
|
|
19
19
|
(message_id, message_type, in_reply_to, sender_teamfile, sender_alias,
|
|
20
20
|
receiver_teamfile, receiver_alias, lifecycle_state, created_seq, last_seq)
|
|
21
21
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)
|
|
@@ -39,7 +39,7 @@ var wg=Object.create;var Ri=Object.defineProperty;var Sg=Object.getOwnPropertyDe
|
|
|
39
39
|
cwd, command, request_message_id, request_payload, holder_pid, holder_host, status, started_at, last_seq)
|
|
40
40
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)
|
|
41
41
|
ON CONFLICT(invocation_id) DO NOTHING`).run(r,s.kind??"chat",s.origin??"unknown",s.launch_source??"",s.from_identity??"",ie(s,"target","teamfile"),ie(s,"target","alias"),s.root_teamfile??null,s.cwd??null,s.command??null,s.request_message_id??null,s.request_payload??null,s.holder_pid??null,s.holder_host??null,s.started_at??"",e);break;case G.INVOCATION_FINISH:t.prepare(`UPDATE invocation_state SET status=?, ended_at=?, result_summary=?, error=?, last_seq=?
|
|
42
|
-
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case G.INVOCATION_NOTIFY_CLAIM:t.prepare("UPDATE invocation_state SET notified_by=?, notified_at=?, last_seq=? WHERE invocation_id=?").run(s.notified_by??null,s.notified_at??null,e,r);break;default:break}}var G,
|
|
42
|
+
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case G.INVOCATION_NOTIFY_CLAIM:t.prepare("UPDATE invocation_state SET notified_by=?, notified_at=?, last_seq=? WHERE invocation_id=?").run(s.notified_by??null,s.notified_at??null,e,r);break;default:break}}var G,rd=A(()=>{"use strict";ss();G={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"}});import{existsSync as Ny,mkdirSync as Ry,readFileSync as id}from"node:fs";import{randomUUID as Ly}from"node:crypto";import{homedir as Cy}from"node:os";import{dirname as od,join as Oy,resolve as ad}from"node:path";import{fileURLToPath as Dy,pathToFileURL as My}from"node:url";function as(t){t.dbPath!==":memory:"&&Ry(od(t.dbPath),{recursive:!0});let e=new ar(t.dbPath);try{e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=dd(e),n=t.buildVersionForTests??pt;if(r===0)e.exec(id(cd,"utf8")),e.pragma(`user_version = ${pt}`);else if(r>n){let s=Uy(e,r);if(Hy={dbVersion:r,buildVersion:n},s>n&&!t.allowSchemaSkew)throw e.close(),new Jr(t.dbPath,r,n);return jy(t.dbPath,r,n),e}return Py(e,r),$y(e),e}catch(r){try{e.close()}catch{}throw r}}function Py(t,e){let r=e;if(r<2&&r!==0&&(t.exec(`
|
|
43
43
|
CREATE TABLE IF NOT EXISTS session_size (
|
|
44
44
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
45
45
|
team_name TEXT NOT NULL,
|
|
@@ -578,7 +578,7 @@ var wg=Object.create;var Ri=Object.defineProperty;var Sg=Object.getOwnPropertyDe
|
|
|
578
578
|
ON agent_mailbox(sender_teamfile, sender_alias, created_at);
|
|
579
579
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_created
|
|
580
580
|
ON agent_mailbox(created_at);
|
|
581
|
-
`),t.pragma("user_version = 45"),r=45),r<46&&r!==0&&(Ue(t,"team_chat_log")?
|
|
581
|
+
`),t.pragma("user_version = 45"),r=45),r<46&&r!==0&&(Ue(t,"team_chat_log")?nd(t):t.exec(`
|
|
582
582
|
CREATE TABLE IF NOT EXISTS team_chat_log (
|
|
583
583
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
584
584
|
root_teamfile TEXT NOT NULL,
|
|
@@ -597,7 +597,7 @@ var wg=Object.create;var Ri=Object.defineProperty;var Sg=Object.getOwnPropertyDe
|
|
|
597
597
|
`),t.exec(`
|
|
598
598
|
CREATE INDEX IF NOT EXISTS idx_team_chat_log_root_time
|
|
599
599
|
ON team_chat_log(root_teamfile, created_at);
|
|
600
|
-
`),t.pragma("user_version = 46"),r=46),r>=46&&Ue(t,"team_chat_log")&&!W(t,"team_chat_log").has("origin")&&
|
|
600
|
+
`),t.pragma("user_version = 46"),r=46),r>=46&&Ue(t,"team_chat_log")&&!W(t,"team_chat_log").has("origin")&&nd(t),r<47&&r!==0){if(ft(t,"tracked_invocation"),Ue(t,"agent_mailbox")){let s=W(t,"agent_mailbox");s.has("delivered_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivered_at TEXT;"),s.has("receipt")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN receipt TEXT;")}let n=W(t,"tracked_invocation");n.has("notified_by")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_by TEXT;"),n.has("notified_at")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_at TEXT;"),t.pragma("user_version = 47"),r=47}if(r<48&&r!==0){if(Ue(t,"agent_mailbox")){let n=W(t,"agent_mailbox");n.has("delivering_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivering_at TEXT;"),n.has("delivery_holder_pid")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_pid INTEGER;"),n.has("delivery_holder_host")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_host TEXT;"),n.has("waited_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_at TEXT;"),n.has("waited_by")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_by TEXT;"),t.exec(`
|
|
601
601
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_sender_delivery_wait
|
|
602
602
|
ON agent_mailbox(sender_teamfile, sender_alias, delivered_at, waited_at, id);
|
|
603
603
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_lane_delivery
|
|
@@ -760,7 +760,7 @@ var wg=Object.create;var Ri=Object.defineProperty;var Sg=Object.getOwnPropertyDe
|
|
|
760
760
|
ON tracked_invocation(scope_teamfile, status, started_at);
|
|
761
761
|
CREATE INDEX IF NOT EXISTS idx_tracked_invocation_status_ended
|
|
762
762
|
ON tracked_invocation(status, ended_at);
|
|
763
|
-
`),t.pragma("user_version = 56"),r=56),r<57&&r!==0&&(Ue(t,"agent_mailbox")&&
|
|
763
|
+
`),t.pragma("user_version = 56"),r=56),r<57&&r!==0&&(Ue(t,"agent_mailbox")&&td(t),t.exec("DROP TABLE IF EXISTS agent_mailbox;"),t.pragma("user_version = 57"),r=57),r<58&&r!==0&&(ft(t,"tracked_invocation"),W(t,"tracked_invocation").has("parent_invocation_id")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN parent_invocation_id INTEGER;"),t.pragma("user_version = 58"),r=58),r<59&&r!==0&&(t.exec(`
|
|
764
764
|
CREATE TABLE IF NOT EXISTS state_ledger_identity (
|
|
765
765
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
766
766
|
instance_id TEXT NOT NULL,
|
|
@@ -849,7 +849,7 @@ CREATE TABLE IF NOT EXISTS prompt_task_reassignments(
|
|
|
849
849
|
);
|
|
850
850
|
|
|
851
851
|
CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_reassignments(prompt_id);
|
|
852
|
-
`),t.exec("INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '61')"),t.pragma("user_version = 62"),r=62),
|
|
852
|
+
`),t.exec("INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '61')"),t.pragma("user_version = 62"),r=62),Ny(Fy)}function $y(t){t.prepare("SELECT instance_id FROM state_ledger_identity WHERE singleton = 1").get()===void 0&&t.prepare("INSERT OR IGNORE INTO state_ledger_identity (singleton, instance_id, created_at) VALUES (1, ?, ?)").run(Ly(),new Date().toISOString())}function W(t,e){let r=t.prepare(`PRAGMA table_info(${e})`).all();return new Set(r.map(n=>n.name))}function Ue(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ft(t,e){if(!Ue(t,e)&&(t.exec(id(cd,"utf8")),!Ue(t,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function nd(t){let e=W(t,"team_chat_log");t.pragma("foreign_keys = OFF");try{t.exec(`
|
|
853
853
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
854
854
|
CREATE TABLE team_chat_log_v46 (
|
|
855
855
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -878,10 +878,10 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
878
878
|
FROM team_chat_log;
|
|
879
879
|
DROP TABLE team_chat_log;
|
|
880
880
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
881
|
-
`)}finally{t.pragma("foreign_keys = ON")}}function
|
|
881
|
+
`)}finally{t.pragma("foreign_keys = ON")}}function dd(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function Uy(t,e){try{if(!Ue(t,"schema_meta"))return e;let r=t.prepare("SELECT value FROM schema_meta WHERE key = 'min_reader_version'").get();if(r===void 0)return e;let n=Number.parseInt(r.value,10);return Number.isInteger(n)&&n>0?n:e}catch{return e}}function jy(t,e,r=pt){sd||(sd=!0,process.stderr.write(`warning: ${t}: state.db is v${e}; this build understands v${r} -- some newer data or features may not be visible, proceeding best-effort. Update: npm install -g @lmctl-ai/lmctl@latest
|
|
882
882
|
`),process.argv.includes("--json")&&process.stderr.write(`${JSON.stringify({schema_skew:{db_version:e,build_version:r,mode:"best_effort"}})}
|
|
883
|
-
`))}function
|
|
884
|
-
`)}finally{t.close()}}});function
|
|
883
|
+
`))}function By(){return process.env.LMCTL_DB??Oy(Cy(),".lmctl","state.db")}var ld,cd,Fy,pt,Jr,sd,Hy,ud=A(()=>{"use strict";ns();rd();ld=od(Dy(import.meta.url)),cd=ad(ld,"schema.sql"),Fy=ad(ld,"migrations"),pt=62,Jr=class extends Error{dbPath;dbVersion;buildVersion;constructor(e,r,n=pt){super(`${e}: state.db is v${r}; this build understands v${n} -- refusing to proceed rather than risk misreading newer data or corrupting it. Update: npm install -g @lmctl-ai/lmctl@latest -- or, only if you must run THIS exact build against this db right now, re-run with --allow-schema-skew (best-effort; newer data/features may be invisible).`),this.name="SchemaSkewError",this.dbPath=e,this.dbVersion=r,this.buildVersion=n}};sd=!1;Hy=null;if(process.argv[1]&&(process.argv[1].endsWith("migrate.ts")||process.argv[1].endsWith("migrate.js"))&&import.meta.url===My(process.argv[1]).href){let t=as({dbPath:process.argv[2]??By()});try{process.stdout.write(`migrated user_version=${dd(t)}
|
|
884
|
+
`)}finally{t.close()}}});function md(t){return{getAgentInflight:t.prepare("SELECT * FROM agent_inflight WHERE receiver_teamfile = ? AND receiver_alias = ?"),listAgentInflight:t.prepare("SELECT * FROM agent_inflight ORDER BY started_at ASC, receiver_teamfile ASC, receiver_alias ASC"),acquireAgentInflight:t.prepare(`
|
|
885
885
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
886
886
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
887
887
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
@@ -1017,7 +1017,7 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1017
1017
|
AND sender_teamfile = ?
|
|
1018
1018
|
AND sender_alias = ?
|
|
1019
1019
|
AND active_count > 1
|
|
1020
|
-
`),clearAgentInflightOlderThan:t.prepare("DELETE FROM agent_inflight WHERE started_at < ?")}}var
|
|
1020
|
+
`),clearAgentInflightOlderThan:t.prepare("DELETE FROM agent_inflight WHERE started_at < ?")}}var fd=A(()=>{"use strict"});function hd(t){return{insertTrackedInvocation:t.prepare(`
|
|
1021
1021
|
INSERT INTO tracked_invocation (
|
|
1022
1022
|
kind, origin, scope_teamfile, from_identity, target_teamfile, target_alias,
|
|
1023
1023
|
root_teamfile, cwd, command, status, started_at, holder_pid, holder_host,
|
|
@@ -1097,37 +1097,37 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1097
1097
|
AND holder_host IS ?
|
|
1098
1098
|
AND started_at = ?
|
|
1099
1099
|
AND last_heartbeat_at IS ?
|
|
1100
|
-
`)}}function Oe(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(
|
|
1101
|
-
...[truncated]`});function
|
|
1100
|
+
`)}}function Oe(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(pd,"utf8"),n=Math.max(0,65536-r),s=Buffer.from(t,"utf8"),i=n;for(;i>0&&(s[i]&192)===128;)i-=1;return`${s.subarray(0,i).toString("utf8")}${pd}`}var pd,gd=A(()=>{"use strict";pd=`
|
|
1101
|
+
...[truncated]`});function Yr(t,e){return JSON.stringify([t,e])}function _d(t){try{let e=JSON.parse(t);return typeof e.lock_id!="string"||typeof e.teamfile!="string"||typeof e.alias!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||!Array.isArray(e.holder_ips)||!e.holder_ips.every(r=>typeof r=="string")||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,teamfile:e.teamfile,alias:e.alias,holder_pid:e.holder_pid,holder_host:e.holder_host,holder_ips:e.holder_ips,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}var Kr,Vr,yd=A(()=>{"use strict";Kr="terminal_lock",Vr="member"});function Ee(t){if(!Number.isInteger(t)||(t??0)<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}var Mt=A(()=>{"use strict"});import{hostname as lr}from"node:os";function ls(t,e={}){let r=setInterval(()=>{Promise.resolve().then(()=>t(new Date().toISOString())).then(n=>{n||clearInterval(r)}).catch(n=>e.onError?.(n))},e.intervalMs??Wy);return r.unref?.(),r}function cr(t,e){let r=new Date().toISOString(),n=new Date(Date.now()-e.ttlMs).toISOString(),s={receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,started_at:r},i=t.getAgentInflight(e.receiver_teamfile,e.receiver_alias),o=i===null||i.holder_pid===null,a=t.tryAcquireAgentInflight(s,{...o?{stale_before:n}:{},force:e.force,reclaim_reason:e.reclaimReason});if(a.acquired){let c=i===null?null:e.force===!0?e.reclaimReason??"force":i.holder_pid===null&&i.started_at<n?"stale":null;return{acquired:!0,lease:a.current??s,leaseId:a.lease_id,previous:i,reclaimReason:c}}if(!ds(a.current,n))return{acquired:!1,current:a.current};let l=t.tryAcquireAgentInflight(s,a.current.holder_pid===null?{stale_before:n}:{reclaim_observed:{sender_teamfile:a.current.sender_teamfile,sender_alias:a.current.sender_alias,started_at:a.current.started_at,holder_pid:a.current.holder_pid},reclaim_reason:"dead-pid"});return l.acquired?{acquired:!0,lease:l.current??s,leaseId:l.lease_id,previous:a.current,reclaimReason:a.current.holder_pid===null?"stale":"dead-pid"}:{acquired:!1,current:l.current}}function wd(t){return t.status!=="running"?null:t.holder_host===lr()&&t.holder_pid!==null&&t.holder_pid>0?Ee(t.holder_pid)?"live":"dead":"unknown"}function cs(t,e,r){let n,s=t.getTerminalLock(e,r);if(s!==null){if(Xy(s))return{busy:!0,reason:"terminal-held",source:"terminal-lock",terminalLock:s};n??={source:"terminal-lock",holder_pid:s.holder_pid,holder_host:s.holder_host,reason:s.holder_host===lr()?"dead-pid":"stale"}}let i=qy(t,e,r);if(i!==null){if(Gy(i))return{busy:!0,reason:"terminal-held",source:"terminal-invocation",terminalInvocation:i};n??={source:"terminal-invocation",holder_pid:i.holder_pid,holder_host:i.holder_host,reason:i.holder_pid!==null&&(i.holder_host===null||i.holder_host===lr())?"dead-pid":"stale"}}let o=t.getAgentInflight(e,r);if(o!==null){let a=new Date(Date.now()-dr()).toISOString();if(!ds(o,a))return{busy:!0,reason:"in-flight",inFlight:o};n??={source:"in-flight",holder_pid:o.holder_pid,holder_host:o.holder_pid===null?null:lr(),reason:o.holder_pid===null?"stale":"dead-pid"}}return n===void 0?{busy:!1}:{busy:!1,reclaimable:n}}function Xy(t){if(t.holder_host===lr())return Ee(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=Ky():!1}function qy(t,e,r){return t.query(`SELECT id, started_at, last_heartbeat_at, holder_pid, holder_host
|
|
1102
1102
|
FROM tracked_invocation
|
|
1103
1103
|
WHERE target_teamfile = ?
|
|
1104
1104
|
AND target_alias = ?
|
|
1105
1105
|
AND status = 'running'
|
|
1106
1106
|
AND launch_source = 'terminal'
|
|
1107
1107
|
ORDER BY started_at DESC, id DESC
|
|
1108
|
-
LIMIT 1`,e,r)[0]??null}function
|
|
1108
|
+
LIMIT 1`,e,r)[0]??null}function Gy(t){return t.holder_pid!==null&&(t.holder_host===null||t.holder_host===lr())?Ee(t.holder_pid):Jy(t)}function Jy(t){let e=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(e)?Date.now()-e<=dr():!1}function ds(t,e){return t.holder_pid===null?t.started_at<e:!Ee(t.holder_pid)}function dr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Ed;let r=Number(e);return!Number.isFinite(r)||r<=0?Ed:r}function Ky(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return Td;let r=Number(e);return!Number.isFinite(r)||r<=0?Td:r}var Ed,Td,Wy,Ft=A(()=>{"use strict";Mt();Ed=8*60*60*1e3,Td=12e4,Wy=3e4});import{randomUUID as Vy}from"node:crypto";import{hostname as Yy}from"node:os";function ht(t,e){return{teamfile:t,alias:e}}function Sd(t,e,r={}){return{teamfile:t,alias:e,...r.provider===void 0||r.provider===null?{}:{provider:r.provider},...r.sessionId===void 0||r.sessionId===null?{}:{session_id:r.sessionId}}}function so(t,e){return t===null?null:ht(t,e??"")}function rt(t){return`msg_tcl_${t}`}function Pt(t){return`inv_${t}`}function ur(t,e,r){return t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias,
|
|
1109
1109
|
holder_pid, holder_host, started_at, terminal_lock_id,
|
|
1110
1110
|
terminal_invocation_id, currently_handling_message_id,
|
|
1111
1111
|
currently_handling_since, last_seq
|
|
1112
1112
|
FROM agent_state
|
|
1113
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function
|
|
1113
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function Qy(t,e,r){if(e===null||r===null)return null;let n=t.prepare(`SELECT currently_handling_message_id, currently_handling_since
|
|
1114
1114
|
FROM agent_state
|
|
1115
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r);if(n?.currently_handling_message_id===null||n?.currently_handling_message_id===void 0||n.currently_handling_since===null)return null;let s=Date.parse(n.currently_handling_since);return!Number.isFinite(s)||Date.now()-s>
|
|
1115
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r);if(n?.currently_handling_message_id===null||n?.currently_handling_message_id===void 0||n.currently_handling_since===null)return null;let s=Date.parse(n.currently_handling_since);return!Number.isFinite(s)||Date.now()-s>zy?null:n.currently_handling_message_id}function Zy(t,e,r){let n=Qy(t,e,r);return n===null?{}:{causation:{request_message_id:n}}}function io(t,e,r,n,s=new Date().toISOString()){t.prepare(`INSERT INTO agent_state
|
|
1116
1116
|
(receiver_teamfile, receiver_alias, currently_handling_message_id,
|
|
1117
1117
|
currently_handling_since, last_seq)
|
|
1118
1118
|
VALUES (?, ?, ?, ?, 0)
|
|
1119
1119
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
1120
1120
|
currently_handling_message_id = excluded.currently_handling_message_id,
|
|
1121
|
-
currently_handling_since = excluded.currently_handling_since`).run(e,r,n,s)}function
|
|
1121
|
+
currently_handling_since = excluded.currently_handling_since`).run(e,r,n,s)}function oo(t,e,r,n){return t.prepare(`UPDATE agent_state
|
|
1122
1122
|
SET currently_handling_message_id = NULL,
|
|
1123
1123
|
currently_handling_since = NULL
|
|
1124
1124
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1125
|
-
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function
|
|
1125
|
+
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function eE(t,e){let r=e??new Date(Date.now()-dr()).toISOString();return ds({holder_pid:t.holder_pid,started_at:t.started_at??""},r)}function tE(t,e,r){return e==="force"||e==="session-idle"?e:r?"force":t.holder_pid!==null&&!Ee(t.holder_pid)?"dead-pid":"stale"}function rE(t){return{sender:so(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:t.holder_host,started_at:t.started_at}}function mr(t,e){if(t!==1)throw new Error(`event projection CAS failed during ${e}`)}function ao(t,e,r){let n=rt(e),s=so(r.sender_teamfile,r.sender_alias),i=Sd(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 be(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,...Zy(t,r.sender_teamfile,r.sender_alias)}},()=>{io(t,r.receiver_teamfile,r.receiver_alias,n,r.created_at)}),n}function us(t,e,r){let n=rt(e),s={message_id:n,message_type:"request",sender:so(r.sender_teamfile,r.sender_alias),receiver:Sd(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 be(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}},()=>{oo(t,r.receiver_teamfile,r.receiver_alias,n)}),n}function nE(t){return{sender:ht(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at}}function vd(t,e,r,n){let s=t.prepare(`UPDATE agent_state
|
|
1126
1126
|
SET lease_id = NULL, sender_teamfile = NULL, sender_alias = NULL,
|
|
1127
1127
|
holder_pid = NULL, holder_host = NULL, started_at = NULL,
|
|
1128
1128
|
last_heartbeat_at = NULL, last_seq = ?
|
|
1129
1129
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1130
|
-
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);
|
|
1130
|
+
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);mr(s.changes,n)}function bd(t,e,r,n,s=null,i=!1){let o=Yy();if(r!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=ur(t,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||eE(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let d=tE(a,n,i),m=rE(a),h=a.lease_id;be(t,{stream_id:h,event_type:"INFLIGHT_RECLAIM",observedLastSeq:a.last_seq,ts:e.started_at,payload:{receiver:ht(e.receiver_teamfile,e.receiver_alias),reason:d,previous_holder:m}},_=>vd(t,a,_,"INFLIGHT_RECLAIM")),a=ur(t,e.receiver_teamfile,e.receiver_alias)}let l=a?.last_seq??0,c=`lease_${Vy()}`;return be(t,{stream_id:c,event_type:"INFLIGHT_TAKE",observedLastSeq:l,ts:e.started_at,payload:{lease_id:c,receiver:ht(e.receiver_teamfile,e.receiver_alias),sender:ht(e.sender_teamfile,e.sender_alias),holder_pid:e.holder_pid,holder_host:o,started_at:e.started_at}},u=>{if(a===null){t.prepare(`INSERT INTO agent_state
|
|
1131
1131
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile,
|
|
1132
1132
|
sender_alias, holder_pid, holder_host, started_at,
|
|
1133
1133
|
last_heartbeat_at, last_seq)
|
|
@@ -1136,18 +1136,18 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1136
1136
|
holder_pid = ?, holder_host = ?, started_at = ?,
|
|
1137
1137
|
last_heartbeat_at = ?, last_seq = ?
|
|
1138
1138
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1139
|
-
AND lease_id IS NULL AND last_seq = ?`).run(c,e.sender_teamfile,e.sender_alias,e.holder_pid,o,e.started_at,e.started_at,u,e.receiver_teamfile,e.receiver_alias,a.last_seq);
|
|
1139
|
+
AND lease_id IS NULL AND last_seq = ?`).run(c,e.sender_teamfile,e.sender_alias,e.holder_pid,o,e.started_at,e.started_at,u,e.receiver_teamfile,e.receiver_alias,a.last_seq);mr(d.changes,"INFLIGHT_TAKE")}),c}function Id(t,e,r,n){return t.prepare(`UPDATE agent_state
|
|
1140
1140
|
SET last_heartbeat_at = ?
|
|
1141
1141
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1142
1142
|
AND lease_id = ?
|
|
1143
1143
|
AND sender_teamfile = ? AND sender_alias = ?
|
|
1144
|
-
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
|
|
1144
|
+
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 zr(t,e,r,n){let s=ur(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||be(t,{stream_id:s.lease_id,event_type:r,observedLastSeq:s.last_seq,payload:{receiver:ht(e.receiver_teamfile,e.receiver_alias),...r==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:nE(e)}:{lease_id:s.lease_id}}},i=>vd(t,s,i,r))}function xd(t,e){let r=ur(t,e.teamfile,e.alias),n=r?.last_seq??0;be(t,{stream_id:e.lock_id,event_type:"TERMINAL_LOCK_TAKE",observedLastSeq:n,ts:e.started_at,payload:{receiver:ht(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
|
|
1145
1145
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
1146
1146
|
VALUES (?, ?, ?, ?)`).run(e.teamfile,e.alias,e.lock_id,s);return}let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = ?, last_seq = ?
|
|
1147
1147
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1148
|
-
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);
|
|
1148
|
+
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);mr(i.changes,"TERMINAL_LOCK_TAKE")})}function lo(t,e,r=!1){let n=ur(t,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||be(t,{stream_id:e.lock_id,event_type:r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE",observedLastSeq:n.last_seq,payload:{receiver:ht(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 = ?
|
|
1149
1149
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1150
|
-
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);
|
|
1150
|
+
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);mr(i.changes,r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE")})}function Ad(t,e,r){let n=ur(t,r.targetTeamfile,r.targetAlias);if(n===null){t.prepare(`INSERT INTO agent_state
|
|
1151
1151
|
(receiver_teamfile, receiver_alias, terminal_invocation_id,
|
|
1152
1152
|
terminal_invocation_pid, terminal_invocation_host,
|
|
1153
1153
|
terminal_invocation_heartbeat_at, last_seq)
|
|
@@ -1156,24 +1156,24 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1156
1156
|
terminal_invocation_host = ?,
|
|
1157
1157
|
terminal_invocation_heartbeat_at = ?, last_seq = ?
|
|
1158
1158
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1159
|
-
AND terminal_invocation_id IS NULL AND last_seq = ?`).run(r.invocationId,r.holderPid,r.holderHost,r.heartbeatAt,e,r.targetTeamfile,r.targetAlias,n.last_seq);
|
|
1159
|
+
AND terminal_invocation_id IS NULL AND last_seq = ?`).run(r.invocationId,r.holderPid,r.holderHost,r.heartbeatAt,e,r.targetTeamfile,r.targetAlias,n.last_seq);mr(s.changes,"terminal INVOCATION_START")}function kd(t,e,r){return t.prepare(`UPDATE agent_state
|
|
1160
1160
|
SET terminal_invocation_heartbeat_at = ?
|
|
1161
|
-
WHERE terminal_invocation_id = ?`).run(r,e).changes===1}function
|
|
1161
|
+
WHERE terminal_invocation_id = ?`).run(r,e).changes===1}function Nd(t,e,r){let n=t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, terminal_lock_id,
|
|
1162
1162
|
terminal_invocation_id, last_seq
|
|
1163
1163
|
FROM agent_state WHERE terminal_invocation_id = ?`).get(r);if(n===void 0)return;let s=t.prepare(`UPDATE agent_state
|
|
1164
1164
|
SET terminal_invocation_id = NULL, terminal_invocation_pid = NULL,
|
|
1165
1165
|
terminal_invocation_host = NULL,
|
|
1166
1166
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1167
1167
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1168
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);
|
|
1168
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);mr(s.changes,"terminal INVOCATION_FINISH")}var zy,ms=A(()=>{"use strict";ss();Ft();Mt();zy=60*60*1e3});function Rd(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function co(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function Ld(t,e){let r=Pt(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;be(t,{stream_id:r,event_type:sE,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
|
|
1169
1169
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1170
1170
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1171
1171
|
status, started_at, last_heartbeat_at, last_seq)
|
|
1172
|
-
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),
|
|
1172
|
+
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),co(e)&&Ad(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function fs(t,e){let r=Pt(e.id),n=Rd(t,r);return n===null?!1:(be(t,{stream_id:r,event_type:iE,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
|
|
1173
1173
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1174
|
-
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}`);
|
|
1174
|
+
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}`);co(e)&&Nd(t,s,r)}),!0)}function Cd(t,e,r,n){let s=Pt(e.id),i=Rd(t,s);return i===null?!1:(be(t,{stream_id:s,event_type:oE,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 Od(t,e,r){let n=Pt(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),co(e)&&kd(t,n,r)}function Dd(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,Pt(e))}function Md(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,Pt(e))}var sE,iE,oE,Fd=A(()=>{"use strict";ss();ms();sE="INVOCATION_START",iE="INVOCATION_FINISH",oE="INVOCATION_NOTIFY_CLAIM"});var aE,lE,jN,Pd,$d,Ud,jd=A(()=>{"use strict";aE="other",lE=["not_enough_information","dont_know","other_work"],jN=new Set([aE,...lE]),Pd="@abort",$d="invalid_decision",Ud="workflow_escalation"});import{randomUUID as Hd}from"node:crypto";import{existsSync as Gd,mkdirSync as cE,renameSync as dE,rmdirSync as uE}from"node:fs";import{hostname as uo}from"node:os";function mo(t){return t.provider_resolved??t.provider}function F(){return new Date().toISOString()}function mE(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!Gd(t))return e;let r;try{r=new ar(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 fE(t){if(t===":memory:"||!Gd(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let r of["","-wal","-shm"]){let n=`${t}${r}`;try{dE(n,`${e}${r}`)}catch{}}return e}function Bd(t,e){let r=e instanceof Error?e.message:String(e);try{let n=mE(t),s=fE(t),i=new ps(as({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${pt} (${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}.
|
|
1175
1175
|
`:`
|
|
1176
|
-
`)),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
|
|
1176
|
+
`)),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 Wd(t,e){let r;try{return r=as({dbPath:t,allowSchemaSkew:e}),{dal:new ps(r)}}catch(n){if(n instanceof Jr)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}}}function _E(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function yE(t){if(t===":memory:")return!0;try{return cE(`${t}${Jd}`),!0}catch{return!1}}function EE(t){if(t!==":memory:")try{uE(`${t}${Jd}`)}catch{}}function $t(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",r={};for(let n=0;n<pE;n+=1)if(r=Wd(t.path,e),r.dal!==void 0)return r.dal;if(r.dbVersion!==void 0&&r.dbVersion>pt){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${pt}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<hE;n+=1){if(yE(t.path))try{return Bd(t.path,r.cause)}finally{EE(t.path)}_E(gE);let s=Wd(t.path,e);if(s.dal!==void 0)return s.dal}return Bd(t.path,r.cause)}function Xd(t,e,r){let n=qd(e);if(n.length===0)return;let s=new Set,i=[],o=l=>{if(l===t)return n;let c=r(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return qd(c.definition)},a=l=>{let c=i.indexOf(l);if(c>=0)throw new Error(`cycle detected: ${[...i.slice(c),l].join(" -> ")}`);if(!s.has(l)){i.push(l);try{for(let u of o(l))a(u)}finally{i.pop()}s.add(l)}};a(t)}function qd(t){let e=TE(t),r=e===null?null:wE(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))hs(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function TE(t){try{let e=JSON.parse(t);return hs(e)?e:null}catch{return null}}function wE(t,e){let r=t[e];return hs(r)?r:null}function hs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function SE(t){try{let e=JSON.parse(t);return!hs(e)||typeof e.lock_id!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}function vE(t,e){return t===null?!0:t.holder_host===uo()?!Ee(t.holder_pid):t.last_heartbeat<e}function bE(t){return{getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
1177
1177
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
1178
1178
|
VALUES (?, ?, ?, ?, ?)
|
|
1179
1179
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1580,118 +1580,118 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1580
1580
|
response = NULL
|
|
1581
1581
|
WHERE id = ?
|
|
1582
1582
|
AND status = 'running'
|
|
1583
|
-
`),...md(t),...cd(t)}}function cE(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Qy,Xd,Zy,eE,fs,mr=A(()=>{"use strict";rs();ld();dd();fd();hd();Dt();us();Od();Pd();Qy=3,Xd=".recovery.lock",Zy=20,eE=50;fs=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=lE(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,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id: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 _=this.getJob(a.id);return{claimed:!1,reason:_?.locked_until!==null&&_?.locked_until!==void 0&&_.locked_until>=i?"locked":"not_claimable",job_id:r,status:_?.status??a.status,locked_by:_?.locked_by??a.locked_by,locked_until:_?.locked_until??a.locked_until}}let h=this.getJob(a.id);return h===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:h}}),this.resumeRunTxn=e.transaction((r,n,s)=>cE("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!==Fd)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Dd&&!a.includes(n))return{resumed:!1,reason:Md};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,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=wd(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){Hd(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,F()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,F());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){Hd(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,F());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,F())}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,F());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,F()),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,F(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(F(),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,F());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,F());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,F(),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,F());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",F());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,F());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=F(),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,F(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,F(),e)??null}closeIssue(e,r,n){let s=F(),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,F(),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,F(),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=F();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,F(),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,F(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=$d(),s=F();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=F(),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,F())}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??F(),e.dedupe_key??null,e.concurrency_key??null,F());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=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=F(),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:F();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,F()),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,F()),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??F(),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,F());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=F(),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,F(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(F(),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 io(this.db,n,e),ds(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 io(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}`);ds(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{no(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>so(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??F(),n=e.holder_host??lo(),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,Oe(e.command),r,e.holder_pid??null,n,s,Oe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return kd(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(`
|
|
1583
|
+
`),...hd(t),...md(t)}}function IE(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var pE,Jd,hE,gE,ps,fr=A(()=>{"use strict";ns();ud();fd();gd();yd();Mt();ms();Fd();jd();pE=3,Jd=".recovery.lock",hE=20,gE=50;ps=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=bE(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,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id: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 _=this.getJob(a.id);return{claimed:!1,reason:_?.locked_until!==null&&_?.locked_until!==void 0&&_.locked_until>=i?"locked":"not_claimable",job_id:r,status:_?.status??a.status,locked_by:_?.locked_by??a.locked_by,locked_until:_?.locked_until??a.locked_until}}let h=this.getJob(a.id);return h===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:h}}),this.resumeRunTxn=e.transaction((r,n,s)=>IE("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!==Ud)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Pd&&!a.includes(n))return{resumed:!1,reason:$d};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,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=bd(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){Xd(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,F()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,F());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){Xd(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,F());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,F())}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,F());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,F()),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,F(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(F(),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,F());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,F());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,F(),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,F());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",F());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,F());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=F(),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,F(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,F(),e)??null}closeIssue(e,r,n){let s=F(),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,F(),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,F(),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=F();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,F(),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,F(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Hd(),s=F();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=F(),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,F())}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??F(),e.dedupe_key??null,e.concurrency_key??null,F());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=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=F(),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:F();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,F()),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,F()),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??F(),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,F());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=F(),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,F(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(F(),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 ao(this.db,n,e),us(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 ao(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}`);us(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{io(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>oo(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??F(),n=e.holder_host??uo(),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,Oe(e.command),r,e.holder_pid??null,n,s,Oe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Ld(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(`
|
|
1584
1584
|
SELECT * FROM tracked_invocation
|
|
1585
1585
|
WHERE parent_invocation_id IN (${n})
|
|
1586
1586
|
AND ended_at IS NOT NULL
|
|
1587
1587
|
AND ended_at >= ?
|
|
1588
1588
|
ORDER BY started_at ASC, id ASC
|
|
1589
|
-
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??F();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Oe(r.result_summary),Oe(r.error),r.team_chat_log_id??null,Oe(r.meta),Oe(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return
|
|
1590
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&Yr(this.db,n,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(Yr(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(Jr,Kr(e,r),Vr);return n===void 0?null:pd(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&oo(this.db,n,!0),this.stmts.upsertRuntimeState.run(Jr,Kr(e.teamfile,e.alias),Vr,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&vd(this.db,e)})()}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(Jr,Kr(e,r),Vr,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Jr,Kr(e,r),Vr);return i.changes===1&&oo(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:oE(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=F()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!aE(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:$d(),holder_pid:process.pid,holder_host:lo(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,F(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,F())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,F());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,F(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??F(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,F());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,F()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,F()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,F());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(F(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=F();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??F());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,F())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,F())}}});var fo=xg(Te=>{"use strict";function fr(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 Gd(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left", "right", or "decimal" per column');return t.map(e=>{if(e!=="left"&&e!=="right"&&e!=="decimal")throw new TypeError('align entries must be "left", "right", or "decimal"');return e})}function nt(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 uo(t,e,r){let n=" ".repeat(Math.max(0,e-nt(t)));return r?n+t:t+n}function Jd(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 dE(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 uE(t,e,r="\u2026"){if(nt(t)<=e)return t;let n=nt(r)>e?"\u2026":r,s=nt(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=nt(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function mE(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 Vd(t){let e=/^(?:[+-]?\$?|\$[+-]?)(?:\d+|\d{1,3}(?:,\d{3})+|(?=\.))(?:\.(\d+))?$/.exec(t);return!e||!/\d/.test(t)?null:{places:e[1]?.length??0}}function fE(t){if(t!==void 0){if(!Array.isArray(t)||t.some(e=>!Number.isInteger(e)||e<0))throw new TypeError("decimalPlaces must be an array of nonnegative integers");return t}}function Kd(t){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let e=[];for(let r of t){let n=Jd(r);n.headers!==void 0&&fr(n.headers);for(let s of n.rows.map(fr))s.forEach((i,o)=>{e[o]=Math.max(e[o]??0,Vd(i)?.places??0)})}return e}Te.measureDecimalPlaces=Kd;function Yd(t,e,r){let n=fE(r)??[],s=e.includes("decimal")?Kd(t):[];return Array.from({length:Math.max(n.length,s.length)},(i,o)=>Math.max(n[o]??0,s[o]??0))}function zd(t,e){let r=Vd(t);if(!r)return null;let n=r.places?r.places+1:0,s=e?e+1:0;return t+" ".repeat(Math.max(0,s-n))}function Qd(t,{max:e,align:r,decimalPlaces:n}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let s=mE(e),i=Gd(r),o=Yd(t,i,n),a=[],l=(c,u)=>{a[c]=Math.max(a[c]??0,u)};for(let c of t){let u=Jd(c);u.headers!==void 0&&fr(u.headers).forEach((d,m)=>{l(m,nt(d))});for(let d of u.rows.map(fr))d.forEach((m,h)=>{let _=i[h]==="decimal"?zd(m,o[h]??0)??m:m;l(h,nt(_))})}return a.map((c,u)=>{let d=s[u];return d===void 0?c:Math.min(c,d)})}Te.measureColumns=Qd;function pE(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 Zd(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l,decimalPlaces:c}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let u=pE(o),d=Gd(n),m=dE(l),h=Yd([t],d,c),_=e??Qd([{rows:t,headers:r}],{max:a,align:d,decimalPlaces:h}),T=t.map(fr);r!==void 0&&T.unshift(fr(r));let p=T.map((f,y)=>{let g=f.length-1;for(;g>=0&&f[g]==="";)g--;return f.slice(0,g+1).map((E,v)=>{let w=_[v]||0,b=s&&w>0&&(v!==g||i)?uE(E,w,m):E;if(d[v]==="decimal"){let S=r!==void 0&&y===0?null:zd(E,h[v]??0),I=uo(S!==null&&nt(S)<=w?S:b,w,!0);return v===g&&S!==null?I.trimEnd():I}return d[v]==="right"?uo(b,w,!0):v===g?b:uo(b,w,!1)}).join(" ")}).join(`
|
|
1589
|
+
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??F();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Oe(r.result_summary),Oe(r.error),r.team_chat_log_id??null,Oe(r.meta),Oe(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return fs(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??F();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Oe(n.result_summary),Oe(n.error),n.team_chat_log_id??null,Oe(n.meta),Oe(n.config_warnings),s,e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return fs(this.db,o),o})()}heartbeatTrackedInvocation(e,r=F()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return Od(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(Dd(this.db,e,r),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,r){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(r,e).changes!==1?null:(Md(this.db,e,rt(r)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,r,n){return this.db.transaction(()=>{let s=F();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Oe(n),e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return fs(this.db,o),o.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(o.team_chat_log_id,n),o})()}terminalizeLinkedChatMessage(e,r){let n=this.stmts.getTeamChatLogById.get(e);n===void 0||n.status!=="running"||this.stmts.terminalizeTeamChatLogIfRunning.run("error",r,e).changes!==1||us(this.db,e,{root_teamfile:n.root_teamfile,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,message:n.message,response:null,origin:n.origin,status:"error",error_detail:r,truncated:n.truncated,created_at:F()})}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled', 'aborted')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return n.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${r.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...n)}claimTrackedInvocationNotification(e,r,n=F()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Cd(this.db,i,r,n),i})()}listTrackedInvocations(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.kind!==void 0&&(r.push("kind = ?"),n.push(e.kind)),e.origin!==void 0&&(r.push("origin = ?"),n.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));n.push(s);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}updateTeamChatLogResponse(e,r){this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e)}getAgentInflight(e,r){return this.stmts.getAgentInflight.get(e,r)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,r){return this.tryAcquireAgentInflightTxn(e,r)}heartbeatAgentInflight(e,r,n=F()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:Id(this.db,s,r,n)})()}clearAgentInflight(e,r){this.db.transaction(()=>{let s=this.getAgentInflight(e,r);if(s===null)return;this.stmts.clearAgentInflight.run(e,r).changes===1&&zr(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,r,n){return this.db.transaction(()=>{let i=this.getAgentInflight(e,r),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:r,observed_sender_teamfile:n.sender_teamfile,observed_sender_alias:n.sender_alias,observed_started_at:n.started_at,observed_holder_pid:n.holder_pid});return o.changes===1&&i!==null&&zr(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,r){this.db.exec("BEGIN IMMEDIATE");try{let n=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(n===null||n.sender_teamfile!==e.sender_teamfile||n.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(r!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
1590
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&zr(this.db,n,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(zr(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(Kr,Yr(e,r),Vr);return n===void 0?null:_d(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&lo(this.db,n,!0),this.stmts.upsertRuntimeState.run(Kr,Yr(e.teamfile,e.alias),Vr,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&xd(this.db,e)})()}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(Kr,Yr(e,r),Vr,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Kr,Yr(e,r),Vr);return i.changes===1&&lo(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:SE(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=F()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!vE(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Hd(),holder_pid:process.pid,holder_host:uo(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,F(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,F())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,F());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,F(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??F(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,F());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,F()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,F()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,F());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(F(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=F();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??F());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,F())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,F())}}});var ho=Pg(Te=>{"use strict";function pr(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 Vd(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left", "right", or "decimal" per column');return t.map(e=>{if(e!=="left"&&e!=="right"&&e!=="decimal")throw new TypeError('align entries must be "left", "right", or "decimal"');return e})}function nt(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 fo(t,e,r){let n=" ".repeat(Math.max(0,e-nt(t)));return r?n+t:t+n}function Yd(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 xE(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 AE(t,e,r="\u2026"){if(nt(t)<=e)return t;let n=nt(r)>e?"\u2026":r,s=nt(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=nt(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function kE(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 zd(t){let e=/^(?:[+-]?\$?|\$[+-]?)(?:\d+|\d{1,3}(?:,\d{3})+|(?=\.))(?:\.(\d+))?$/.exec(t);return!e||!/\d/.test(t)?null:{places:e[1]?.length??0}}function NE(t){if(t!==void 0){if(!Array.isArray(t)||t.some(e=>!Number.isInteger(e)||e<0))throw new TypeError("decimalPlaces must be an array of nonnegative integers");return t}}function Qd(t){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let e=[];for(let r of t){let n=Yd(r);n.headers!==void 0&&pr(n.headers);for(let s of n.rows.map(pr))s.forEach((i,o)=>{e[o]=Math.max(e[o]??0,zd(i)?.places??0)})}return e}Te.measureDecimalPlaces=Qd;function Zd(t,e,r){let n=NE(r)??[],s=e.includes("decimal")?Qd(t):[];return Array.from({length:Math.max(n.length,s.length)},(i,o)=>Math.max(n[o]??0,s[o]??0))}function eu(t,e){let r=zd(t);if(!r)return null;let n=r.places?r.places+1:0,s=e?e+1:0;return t+" ".repeat(Math.max(0,s-n))}function tu(t,{max:e,align:r,decimalPlaces:n}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let s=kE(e),i=Vd(r),o=Zd(t,i,n),a=[],l=(c,u)=>{a[c]=Math.max(a[c]??0,u)};for(let c of t){let u=Yd(c);u.headers!==void 0&&pr(u.headers).forEach((d,m)=>{l(m,nt(d))});for(let d of u.rows.map(pr))d.forEach((m,h)=>{let _=i[h]==="decimal"?eu(m,o[h]??0)??m:m;l(h,nt(_))})}return a.map((c,u)=>{let d=s[u];return d===void 0?c:Math.min(c,d)})}Te.measureColumns=tu;function RE(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 ru(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l,decimalPlaces:c}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let u=RE(o),d=Vd(n),m=xE(l),h=Zd([t],d,c),_=e??tu([{rows:t,headers:r}],{max:a,align:d,decimalPlaces:h}),T=t.map(pr);r!==void 0&&T.unshift(pr(r));let p=T.map((f,y)=>{let g=f.length-1;for(;g>=0&&f[g]==="";)g--;return f.slice(0,g+1).map((E,v)=>{let w=_[v]||0,b=s&&w>0&&(v!==g||i)?AE(E,w,m):E;if(d[v]==="decimal"){let S=r!==void 0&&y===0?null:eu(E,h[v]??0),I=fo(S!==null&&nt(S)<=w?S:b,w,!0);return v===g&&S!==null?I.trimEnd():I}return d[v]==="right"?fo(b,w,!0):v===g?b:fo(b,w,!1)}).join(" ")}).join(`
|
|
1591
1591
|
`);return p===""||u===""?p:`${u}${p.split(`
|
|
1592
1592
|
`).join(`
|
|
1593
|
-
${u}`)}`}Te.renderGrid=
|
|
1594
|
-
`)}Te.formatTable=
|
|
1595
|
-
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}Te.escapeCell=
|
|
1593
|
+
${u}`)}`}Te.renderGrid=ru;function nu(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l}={}){return ru(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l})}function LE(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l,stream:c=process.stdout}={}){let u=nu(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l});u&&c.write(`${u}
|
|
1594
|
+
`)}Te.formatTable=nu;Te.printTable=LE;function Kd(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function CE(t,{now:e=Date.now()}={}){let r=Kd(e);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=Kd(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":""}`}Te.formatRelativeTime=CE;function OE(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`}Te.formatCount=OE;var po=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function DE(t,{maxUnit:e="w",style:r="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let n=po.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=po.slice(n).filter(([d])=>d!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,u=!1;for(let[d,m]of a){let h=Math.floor(c/m);if(c-=h*m,h>0&&!u){let _=d==="d"||d==="w"?`${h}${d}`:`${Ge(h)}${d}`;l.push({text:_,zero:!1}),u=!0}else u&&l.push({text:`${Ge(h)}${d}`,zero:h===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(d=>d.text).join("")}let i=s,o=[];for(let[a,l]of po.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(" ")}Te.formatDuration=DE;function su(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function Ge(t){return String(t).padStart(2,"0")}function iu(t){let e=su(t);return Number.isNaN(e.getTime())?"unknown":`${Ge(e.getHours())}:${Ge(e.getMinutes())}:${Ge(e.getSeconds())}`}Te.formatClock=iu;function ME(t){let e=su(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${Ge(e.getMonth()+1)}-${Ge(e.getDate())}`} ${iu(e)}`}Te.formatLocalTimestamp=ME;function FE(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}Te.formatPercent=FE;function PE(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)||nt(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)}`}Te.formatBar=PE;function $E(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=`${Ge(n)}:${Ge(s)}:${Ge(e)}`;return r>0?`${r}d ${i}`:i}Te.formatTimer=$E;function UE(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
|
|
1595
|
+
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}Te.escapeCell=UE});import{homedir as jE}from"node:os";import{join as ou}from"node:path";function WE(){let t=process.env.LMCTL_HOME;return t!==void 0&&t.length>0?t:ou(jE(),HE)}function XE(){return ou(WE(),BE)}function st(t){return t!==void 0&&t.length>0?t:process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?process.env.LMCTL_DB:XE()}function au(t){return process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}var HE,BE,Qr=A(()=>{"use strict";HE=".lmctl",BE="state.db"});function hr(t){return(t.env??process.env).LMCTL_NON_INTERACTIVE==="1"}async function j(t,e){if(t.dal!==void 0)return e(t.dal);let r=$t({path:st()});try{return await e(r)}finally{r.close()}}function go(t,e,r=["--json"]){let n=new Set(e),s=new Set(r),i=[],o={};for(let a=0;a<t.length;a+=1){let l=t[a];if(!l.startsWith("--")){i.push(l);continue}if(s.has(l)){o[l]=!0;continue}if(!n.has(l))return{positionals:i,flags:o,error:`unknown flag: ${l}`};let c=t[a+1];if(c===void 0||c.startsWith("--"))return{positionals:i,flags:o,error:`missing value for ${l}`};o[l]=c,a+=1}return{positionals:i,flags:o}}function gt(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function Ut(t,e){return t.flags[e]===!0}function _o(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1596
1596
|
`)}function B(t,e){return t.stderr.write(`error: ${e}
|
|
1597
|
-
`),1}function _t(){return(0,
|
|
1598
|
-
`),2}function
|
|
1599
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function De(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var H,me=A(()=>{"use strict";H=
|
|
1600
|
-
`):"";E&&!/^<(?:command-name>|local-command-|task-notification>\s*<|system-reminder>)/u.test(E.trimStart())&&!E.trimStart().startsWith("lmctl seed initial connection only.")&&T.push(E)}if(typeof g=="string"){let E=g.trim();if(E.includes("<command-name>")||E.includes("<local-command-")||/^<task-notification>\s*</u.test(E)||E.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(E))continue;u||(u=$(g.trim(),80)),d=$(g.trim(),80),_=void 0,s.push({role:"user",timestamp:y,content:Y(g.trim())})}else if(Array.isArray(g)){for(let E of g)if(E.type==="tool_result"){let v=typeof E.content=="string"?Y(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:y,content:v,toolCallId:E.tool_use_id})}}}if(f.type==="assistant"&&f.message){f.message.stop_reason===null||f.message.stop_reason==="tool_use"?_="in_progress":typeof f.message.stop_reason=="string"&&(_="complete"),f.message.model&&(l=f.message.model);let y=new Date(f.timestamp||0),g=f.message.content;if(Array.isArray(g))for(let E of g)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:y,content:Y(E.text),model:f.message.model,...typeof f.message.stop_reason=="string"?{stopReason:f.message.stop_reason}:{}}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:y,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolInputData:E.input,toolCallId:E.id,model:f.message.model,...typeof f.message.stop_reason=="string"?{stopReason:f.message.stop_reason}:{}}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:y,content:E.thinking})}}if(!i)return null;
|
|
1601
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let m=d.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=m}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=
|
|
1602
|
-
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)n({success:!0});else{let u=
|
|
1597
|
+
`),1}function _t(){return(0,lu.formatClock)()}function gr(t,e,r=5e3){let n=Date.now(),s=n,i=setInterval(()=>{let o=Date.now();o-s<r||t.stderr.write(e(Math.round((o-n)/1e3)))},r);return i.unref(),{poke:()=>{s=Date.now()},stop:()=>clearInterval(i)}}function gs(t,e){let r=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${r}
|
|
1598
|
+
`),2}function _r(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var lu,yr=A(()=>{"use strict";fr();lu=zl(ho(),1);Qr()});import{realpathSync as GE}from"node:fs";import{resolve as JE}from"node:path";function yo(t){let e=JE(t);try{return GE(e)}catch{return e}}var cu=A(()=>{"use strict"});import{platform as du}from"node:os";function yt(t){let e=new Zr;for(let r of t)e.registerAdapter(r);return e}var Zr,Eo=A(()=>{"use strict";cu();Zr=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=yo(e.workspace);i=i.filter(a=>yo(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=du()==="darwin"||du()==="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 uu}from"node:fs";import{createInterface as mu}from"node:readline";import{stat as KE}from"node:fs/promises";import{homedir as VE}from"node:os";function fu(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*ne(t){let e=uu(t,{encoding:"utf-8"}),r=mu({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(!s)continue;let i=fu(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function Ae(t,e){let r=[],n=uu(t,{encoding:"utf-8"}),s=mu({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=fu(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 KE(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function Y(t){return t.replace(/\\n/g,`
|
|
1599
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function $(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function De(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var H,me=A(()=>{"use strict";H=VE()});import{readdir as ys,stat as pu,unlink as YE}from"node:fs/promises";import{join as Er,basename as hu}from"node:path";function zE(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function QE(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return Y(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 gu(t){let e=0,r=0,n=0,s=0,i=0,o=0,a,l;for await(let c of ne(t))if(!c.isSidechain){if(c.type==="user"&&!c.isMeta&&c.message){let u=c.message.content;if(typeof u=="string"){if(u.includes("<command-name>")||u.includes("<local-command-"))continue;e++,l=$(u.trim(),80)}}else if(c.type==="assistant"&&c.message){let u=c.message.content;if(Array.isArray(u))for(let m of u)m.type==="text"&&e++;let d=c.message.usage;if(d){let m=d.input_tokens||0,h=d.cache_creation_input_tokens||0,_=d.cache_read_input_tokens||0,T=d.output_tokens||0;r+=m+h+_,n+=_,s+=h,i+=T;let p=m+h+_;p&&(o=p),a={inputTokens:m,cacheWriteInputTokens:h,cachedInputTokens:_,outputTokens:T}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function ZE(t){let e=eT(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 eT(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 Es,_u=A(()=>{"use strict";me();Es=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Er(H,".claude"),this.projectsDir=Er(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await ys(this.projectsDir)}catch{return e}for(let n of r){let s=Er(this.projectsDir,n);if(!(await pu(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await ys(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=hu(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Er(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,r){let n=await Ae(e,50),s=await se(e),i="",o,a,l,c,u,d;for(let h of n)if(!zE(h.type)&&(!i&&h.cwd&&(i=h.cwd),!o&&h.slug&&(o=h.slug),!a&&h.version&&(a=h.version),!d&&h.timestamp&&(d=new Date(h.timestamp)),h.type==="assistant"&&h.message?.model&&(l=h.message.model),h.type==="user"&&!h.isMeta&&h.message)){let _=h.message.content;if(typeof _=="string"){if(_.includes("<command-name>")||_.includes("<local-command-"))continue;c||(c=$(_.trim(),80)),u=$(_.trim(),80)}}if(!i)return null;let m=await gu(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:m.lastUserMessage??u,messageCount:m.messageCount,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:m.totalCacheWriteInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await se(r),s=[],i="",o,a,l,c,u,d,m,h=e,_,T=[];for await(let f of ne(r))if(f.type!=="file-history-snapshot"&&!f.isSidechain){if(!i&&f.cwd&&(i=f.cwd),!o&&f.slug&&(o=f.slug),!a&&f.version&&(a=f.version),!c&&f.gitBranch&&(c=f.gitBranch),!m&&f.timestamp&&(m=new Date(f.timestamp)),f.sessionId&&(h=f.sessionId),f.type==="system"||f.type==="progress"||f.type==="queue-operation"){s.push({role:"system",timestamp:new Date(f.timestamp||0),content:QE(f)});continue}if(f.type==="user"&&f.message){if(f.isMeta)continue;let y=new Date(f.timestamp||0),g=f.message.content;if(f.isCompactSummary!==!0&&f.isVisibleInTranscriptOnly!==!0&&f.promptSource!=="system"&&f.toolUseResult===void 0&&f.origin?.kind!=="task-notification"&&f.interruptedMessageId===void 0&&f.interruptedByShutdown!==!0&&f.scheduledTaskId===void 0&&f.scheduledFireId===void 0&&!(Array.isArray(g)&&g.some(E=>E.type==="tool_result"))){let E=typeof g=="string"?g:Array.isArray(g)?g.filter(v=>v.type==="text"&&typeof v.text=="string").map(v=>v.text).join(`
|
|
1600
|
+
`):"";E&&!/^<(?:command-name>|local-command-|task-notification>\s*<|system-reminder>)/u.test(E.trimStart())&&!E.trimStart().startsWith("lmctl seed initial connection only.")&&T.push(E)}if(typeof g=="string"){let E=g.trim();if(E.includes("<command-name>")||E.includes("<local-command-")||/^<task-notification>\s*</u.test(E)||E.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(E))continue;u||(u=$(g.trim(),80)),d=$(g.trim(),80),_=void 0,s.push({role:"user",timestamp:y,content:Y(g.trim())})}else if(Array.isArray(g)){for(let E of g)if(E.type==="tool_result"){let v=typeof E.content=="string"?Y(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:y,content:v,toolCallId:E.tool_use_id})}}}if(f.type==="assistant"&&f.message){f.message.stop_reason===null||f.message.stop_reason==="tool_use"?_="in_progress":typeof f.message.stop_reason=="string"&&(_="complete"),f.message.model&&(l=f.message.model);let y=new Date(f.timestamp||0),g=f.message.content;if(Array.isArray(g))for(let E of g)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:y,content:Y(E.text),model:f.message.model,...typeof f.message.stop_reason=="string"?{stopReason:f.message.stop_reason}:{}}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:y,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolInputData:E.input,toolCallId:E.id,model:f.message.model,...typeof f.message.stop_reason=="string"?{stopReason:f.message.stop_reason}:{}}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:y,content:E.thinking})}}if(!i)return null;ZE(s);let p=await gu(r);return{provider:"claude",sessionId:h,slug:o,cwd:i,createdAt:m||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:_,firstUserMessage:u,lastUserMessage:d,messageCount:p.messageCount,filePath:r,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:p.totalCacheWriteInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,lastInputTokens:p.lastInputTokens||void 0,lastTokenUsage:p.lastTokenUsage,messages:s,userPrompts:T}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await YE(r),!0):!1}async resolveSessionFile(e){let r;try{r=await ys(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Er(this.projectsDir,o);if(!(await pu(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await ys(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=hu(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&n.push({filePath:Er(a,u),fileSessionId:d})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await Ae(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as tT,writeFileSync as kR,mkdirSync as NR}from"node:fs";import{join as rT,dirname as LR}from"node:path";import{homedir as nT}from"node:os";function iT(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function oT(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=iT(t.slice(e+1).trim());return r?{key:r,value:n}:null}function aT(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Ts(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function lT(){return rT(nT(),".lmctl","config.toml")}function Eu(t){let e=t??lT(),r;try{r=tT(e,"utf-8")}catch{return{tools:{}}}return cT(r)}function yu(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 cT(t){let e={},r={},n=t.split(`
|
|
1601
|
+
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let m=d.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=m}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=yu(i.min);m!==null&&(d.min=m)}if(i.max!==void 0){let m=yu(i.max);m!==null&&(d.max=m)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=d):r.global=d}i={}}for(let d of n){let m=d.trim();if(!m||m.startsWith("#"))continue;let h=aT(m);if(h!==null){if(o=!0,l(),h.startsWith("tool.")){let T=".profile.",p=h.indexOf(T);p!==-1?s={kind:"tool",tool:h.slice(5,p),profile:h.slice(p+T.length)}:s={kind:"tool",tool:h.slice(5),profile:null}}else h==="compact"?s={kind:"compact",provider:null}:h.startsWith("compact.")?s={kind:"compact",provider:h.slice(8)}:s={kind:"none"};continue}let _=oT(m);_&&s.kind!=="none"?i[_.key]=_.value:_&&!o&&(a[_.key]=_.value)}l();let c={tools:e};(r.global||r.providers)&&(c.compact=r);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function dT(t,e,r){if(!r)return"";let n=t.tools[e]??To[e],s=n?.profiles?.[r]?.flags??To[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 Tu(t,e){return!!t.tools[e]}function wu(t,e,r,n,s){let i=t.tools[e]??To[e],o;if(i?.agent){let l=Ts(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=sT[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let u=c.map(Ts).join(" ");o=`printf '%s\\n' ${Ts(n)} | ${u}`}else o=c.map(Ts).join(" ")}let a=dT(t,e,s);return a&&(o+=" "+a),o}var To,sT,wo=A(()=>{"use strict";To={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:""}}}},sT={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 Su(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 vu=A(()=>{"use strict"});var uT,X,ws,we=A(()=>{"use strict";uT="ACK: waiting for explicit lmctl task.",X=`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: ${uT}`,ws=`send this exact lmctl seed instruction: "${X}"`});import{existsSync as mT}from"node:fs";function bu(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&&!mT(e);if(!r&&!n)return t;N({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 Tr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function pT(t,e){return e===void 0||e.length===0?t:{...t??process.env,[So]:e}}function de(t,e,r,n="chat"){return{...pT(Tr(t,e),r),[fT]:n}}var So,fT,Je=A(()=>{"use strict";z();So="LMCTL_SELF_SESSIONID",fT="LMCTL_LAUNCH_SOURCE"});function en(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var vo=A(()=>{"use strict"});import{spawn as Iu}from"node:child_process";import{mkdirSync as hT}from"node:fs";var bo,Q,ke=A(()=>{"use strict";wo();vu();we();Je();vo();bo=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},Q=class t{name;capabilities;injection;provider;binary;seedArgs;seedTimeoutMs;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.seedTimeoutMs=e.seedTimeoutMs??6e4,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===X?r:n)}turnOptsFor(e){return e}seed(e,r){return hT(e,{recursive:!0}),new Promise(n=>{let s;try{s=Iu(this.binary,this.seedArgsFor(r),{cwd:e,env:Tr(void 0,e),stdio:["pipe","pipe","pipe"],timeout:this.seedTimeoutMs})}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}
|
|
1602
|
+
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)n({success:!0});else{let u=en(o).trim(),d=en(i).trim();n({success:!1,error:(u||d).slice(0,500)||(c?`terminated by ${c}`:`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:ws,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&&Tu(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),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:_=>{a+=_,c(),n.onDelta?.(_)},onProgress:_=>{_.kind!=="api_retry"&&c(),n.onProgress?.(_)}},m=this.transportFn(r,d).then(_=>(u(),{..._,status:_.status??"ok"})).catch(_=>{throw u(),o==="external"?new bo("Turn cancelled","external"):_}),h=new Promise(_=>{l=_});return Promise.race([m,h])}runOneShotAgent(e,r,n){let s=wu(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=r.timeoutMs!==void 0&&r.timeoutMs<=0?0:Su(r.env),c=Iu(s,{shell:!0,cwd:r.cwd,env:de(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m=l>0?setTimeout(()=>{d=!0,c.kill()},l):void 0,h="",_="";if(c.stdout?.on("data",T=>{let p=T.toString();h+=p,r.onDelta?.(p)}),c.stderr?.on("data",T=>{_+=T.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(m),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",T=>{if(u)return;u=!0,clearTimeout(m);let p=Date.now()-i;d?a(new Error(`Agent command timed out after ${l}ms`)):T===0||T===null?o({text:h.trim(),sessionId:r.sessionId,durationMs:p}):a(new Error(_.trim().slice(0,200)||`Agent command exited with code ${T}`))}),c.on("error",T=>{u||(u=!0,clearTimeout(m),a(T))})})}}});function nn(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new rn(t,r,e)}var Et,Z,tn,Ss,rn,jt=A(()=>{"use strict";Et=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},Z=class extends Et{},tn=class extends Et{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},Ss=class extends Et{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},rn=class extends Et{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as xo from"node:child_process";function _T(t){if(typeof xo.spawnSync=="function")try{xo.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function xu(t){return t.exitCode!==null||t.signalCode!==null}function Io(t,e){return xu(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 ee(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??_T;if(xu(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Io(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 Io(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Io(t,gT)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var gT,sn=A(()=>{"use strict";gT=1e3});function Au(t){te()&&_e({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function Tt(t,e){let r=ET[t];if(r)return r[e]??r.yolo}function wT(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 fe(t,e,r="yolo"){if(TT.has(t)){Au(`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"?Tt(t,"plan"):yT[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 N({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new Z(s)}if(!wT(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 N({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new Z(i)}Au(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var yT,ET,TT,it=A(()=>{"use strict";jt();z();yT={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},ET={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"]}};TT=new Set(["codex","opencode","kimi","dsh","hermes","pi"])});async function bs(t,e,r){if(typeof t=="boolean")return t;let n,s;try{return await Promise.race([t,new Promise(i=>{n=setTimeout(()=>i(Ao),e),n.unref?.(),r!==void 0&&(s=()=>i(Ao),r.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&r?.removeEventListener("abort",s)}}function wt(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();xT(t,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function xT(t,e,r,n){let s=t.pollMs??ST,i=t.maxHoldMs??vs,o=t.settleMs??vT,a=t.backgroundGraceMs??bT,l=!1,c=null,u=d=>n({startedMs:r,held:l,reason:d});for(;;){if(e.isAborted())return u("aborted");if(e.hasChildExited())return u("child-exited");let d=i-(Date.now()-r);if(d<=0)return u("max-hold");let m;try{m=await bs(t.hasOutstandingWork(),d,e.signal)}catch{return u("check-error")}if(m===Ao)return u(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(m)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-r<a){let T=a-(Date.now()-r);await new Promise(p=>setTimeout(p,Math.max(0,Math.min(s,IT,T))).unref?.());continue}if(!l||o<=0)return u("cleared");c===null&&(c=Date.now(),ce(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let _=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-_>=o)return u("cleared")}if(l||(l=!0,t.onHold?.(),ce(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-r>=i)return N({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-r}),u("max-hold");let h=Math.max(0,Math.min(s,i-(Date.now()-r)));await new Promise(_=>setTimeout(_,h).unref?.())}}var ST,vs,vT,bT,IT,Ao,Is=A(()=>{"use strict";z();ST=2e3,vs=8*60*60*1e3,vT=5e3,bT=1e3,IT=50,Ao=Symbol("check-timed-out")});function ku(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(`
|
|
1603
1603
|
|
|
1604
1604
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
1605
1605
|
|
|
1606
|
-
`+t[r]);return e.join("")}function
|
|
1606
|
+
`+t[r]);return e.join("")}function xs(t={}){let e=[],r="",n=!1;return{processLine(s){if(!s.trim())return;let i;try{i=JSON.parse(s)}catch{return}t.onEvent?.(i);let o=i.type;if(o==="system"&&i.subtype==="init"&&(r=i.session_id||r),o==="assistant"){let l=i.message?.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&t.onText?.(c.text)}o==="result"&&(n=!0,e.push(i))},sawResult(){return n},finalize(){if(!n)return null;let s=Nu(e),i=ku(s.resultTexts);return{result:i,sessionId:s.sessionId||r,durationMs:s.durationMs,numTurns:s.numTurns,isError:s.isError&&i.trim().length===0,errorMessage:s.errorMessage}}}}function Nu(t){let e=[],r=0,n=0,s="",i=!1,o;for(let a of t){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(r+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(n=c);let u=a.session_id;if(typeof u=="string"&&u&&(s=u),a.is_error===!0){i=!0;let d=a.errors,m=Array.isArray(d)?d.filter(_=>typeof _=="string").join("; "):void 0,h=typeof a.subtype=="string"?a.subtype:"unknown";o=m&&m.length>0?m:`result subtype=${h} (no error detail provided)`}}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s,isError:i,errorMessage:o}}var ko=A(()=>{"use strict"});import{spawn as Lu}from"node:child_process";import{existsSync as Cu}from"node:fs";import{join as As}from"node:path";import{readdir as AT}from"node:fs/promises";function Ou(){let t=process.env.LMCTL_RESULT_GRACE_TIMEOUT_MS;if(t===void 0||t.trim().length===0)return 12e4;let e=Number(t);return Number.isFinite(e)&&e>0?e:12e4}function Du(){let t=process.env.LMCTL_TOOL_USE_GRACE_TIMEOUT_MS;if(t===void 0||t.trim().length===0)return 27e5;let e=Number(t);return Number.isFinite(e)&&e>0?e:27e5}function Mu(t){let r=t.message?.content;return Array.isArray(r)?r.some(n=>n?.type==="tool_use"):!1}function NT(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} exited with code ${t.exitCode} before returning a final result event.
|
|
1607
1607
|
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:
|
|
1608
1608
|
${e}
|
|
1609
1609
|
|
|
1610
|
-
${r}`:r}function
|
|
1611
|
-
`);d=J.pop()||"";for(let
|
|
1612
|
-
`),ce(`stream-json: prompt sent (${t.length} chars)`)})}function
|
|
1613
|
-
`);O=U.pop()||"";for(let oe of U)
|
|
1614
|
-
`),ce(`stream-json bundle: prompt sent (${L.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(L=>{wt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),L()},label:e})}):i.stdin?.end(),!a.exited)){let L=t.closeTimeoutMs??2e3;await Promise.race([S(),
|
|
1610
|
+
${r}`:r}function Fu(t){let e=t.tool||"claude",r=t.binaryPath||kT[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=Tt(e,s)??RT[e]??["--dangerously-skip-permissions"];if(n.push(...i),fe(e,n,s),t.cwd&&!Cu(t.cwd))throw N({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new Z(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=de(t.env,t.cwd,t.sessionId);return{tool:e,binary:r,args:n,spawnEnv:e==="claude"?bu(o):o}}function Pu(t,e){return new Promise((r,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=Fu(e))}catch(O){return n(O instanceof Error?O:new Error(String(O)))}let c=Lu(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",O=>{ce(`stream-json: stdin pipe error, ignored (exit handler reports): ${O.message}`)});let u=!1;if(e.signal){if(e.signal.aborted)return u=!0,N({event:"transport_abort",provider:i,phase:"pre_spawn"}),ee(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,N({event:"transport_abort",provider:i}),ee(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let d="",m=!1,h=!1,_=0,T=!1,p="",f="",y,g,E=null,v=null,w=!1,b=!1,S=Ou(),I=Du();function x(){y!==void 0&&(clearTimeout(y),y=void 0)}function R(){g!==void 0&&(clearTimeout(g),g=void 0)}let P=null;function k(){return m||u||ue.sawResult()}function C(O){return O==="text_done"?S:I}async function q(O){if(O==="text_done"?y=void 0:g=void 0,k()||E!==null)return;P??=Date.now();let J=C(O);if(e.holdOpen){let Pr=(e.holdOpen.maxHoldMs??vs)-(Date.now()-P),Ri=Pr>0?await bs(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),Pr,e.signal):!1;if(k()||(O==="text_done"?y!==void 0:g!==void 0))return;if(Ri===!0){N({event:"transport_stall_grace_deferred",provider:i,grace_kind:O,grace_ms:J,reason:"outstanding_dispatched_work"}),K(O);return}}v=O,E=O==="text_done"?`${i} finished responding but never emitted its closing result event (${J}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${J}ms of silence)`,N({event:"transport_stall_grace_fired",provider:i,grace_kind:O,grace_ms:J}),ee(c).catch(()=>{})}function K(O){let J=setTimeout(()=>{q(O)},C(O));J.unref?.(),O==="text_done"?(x(),y=J):(R(),g=J)}let ue=xs({onEvent:O=>{_=Date.now(),T=O.type!=="result",O.type==="system"&&O.subtype==="init"&&(f=O.session_id||f),O.type==="assistant"?(w=!Mu(O),b=w&&O.message?.stop_reason==="pause_turn"):(O.type==="result"||O.type==="user")&&(w=!1,b=!1),x(),i==="claude"&&w&&!b&&!ue.sawResult()&&K("text_done"),R(),i==="claude"&&!ue.sawResult()&&K("tool_use_silence"),e.onEvent?.(O)},onText:O=>{p+=O,e.onText?.(O)}});function le(){h||(h=!0,wt(e.holdOpen,{isAborted:()=>u,hasChildExited:()=>m,isTurnInFlight:()=>T,lastEventAtMs:()=>_,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function Nt(O){let J=ue.sawResult();ue.processLine(O),!J&&ue.sawResult()&&le()}c.stdout?.on("data",O=>{d+=O.toString();let J=d.split(`
|
|
1611
|
+
`);d=J.pop()||"";for(let Fn of J)Nt(Fn)});let Qe="";c.stderr?.on("data",O=>{Qe+=O.toString()}),c.on("error",O=>{N({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:O.message}),n(new Z(`Failed to spawn ${o}: ${O.message}`,{cause:O}))}),c.on("exit",O=>{if(m=!0,x(),R(),u)return;d.trim()&&Nt(d);let J=ue.finalize();J?.isError?(N({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:J.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${J.errorMessage??"unknown error"}`))):J?(ce(`stream-json: result ${J.result.slice(0,80)}${J.result.length>80?"...":""} (${J.durationMs}ms)`),r({result:J.result,sessionId:J.sessionId,durationMs:J.durationMs,numTurns:J.numTurns,exitCode:O})):E!==null&&v==="text_done"&&p.trim().length>0?(N({event:"transport_stall_finalized",provider:i,reason:E,text_len:p.length}),r({result:p,sessionId:f||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:O,warnings:[E]})):E!==null&&v==="tool_use_silence"?(N({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:O,stderr_tail:Qe.slice(0,500)}),n(new Error(`${E} \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})`:"")))):(N({event:"transport_error",provider:i,error_class:"Error",reason:E!==null?"provider_stalled_no_content":"provider_no_result",exit_code:O,stderr_tail:Qe.slice(0,500)}),n(new Error(E!==null?`${E} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):NT({tool:i,exitCode:O,stderr:Qe}))))});let V=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(V+`
|
|
1612
|
+
`),ce(`stream-json: prompt sent (${t.length} chars)`)})}function LT(t){return t==="qwen"?[As(H,".qwen","projects")]:[As(H,".claude","projects")]}async function Ru(t,e,r){let n=r??LT(t),s=null;for(let a of n){let l;try{l=await AT(a)}catch{continue}for(let c of l){for(let u of[As(a,c,`${e}.jsonl`),As(a,c,"chats",`${e}.jsonl`)])if(Cu(u)){s=u;break}if(s!==null)break}if(s!==null)break}if(s===null)throw new Error(`stream-json bundle: no session file for session "${e}" under ${n.join(", ")} \u2014 the session must exist on disk before a bundle can resume it`);let o=(await Ae(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 $u(t){let{tool:e,binary:r,args:n,spawnEnv:s}=Fu(t),i=Lu(r,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",L=>{ce(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${L.message}`)});let a={exited:!1,exitCode:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=null,u="";i.stderr?.on("data",L=>{u+=L.toString()});let d="",m="",h=!1,_=!1,T=null,p=null,f=null,y,g,E=Ou(),v=Du(),w=null,b=[],S=()=>a.exited?Promise.resolve():new Promise(L=>{b.push(L)}),I=()=>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 x(){y!==void 0&&(clearTimeout(y),y=void 0)}function R(){g!==void 0&&(clearTimeout(g),g=void 0)}function P(){return a.exited||w===null||w.aborted||w.processor.sawResult()}function k(L){return L==="text_done"?E:v}async function C(L){if(L==="text_done"?y=void 0:g=void 0,P()||T!==null)return;f??=Date.now();let U=k(L);if(t.holdOpen){let Qt=(t.holdOpen.maxHoldMs??vs)-(Date.now()-f),Pn=Qt>0?await bs(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),Qt,void 0):!1;if(P()||(L==="text_done"?y!==void 0:g!==void 0))return;if(Pn===!0){N({event:"transport_stall_grace_deferred",provider:e,grace_kind:L,grace_ms:U,reason:"outstanding_dispatched_work"}),q(L);return}}p=L,T=L==="text_done"?`${e} finished responding but never emitted its closing result event (${U}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${U}ms of silence)`,N({event:"transport_stall_grace_fired",provider:e,grace_kind:L,grace_ms:U}),ee(i).catch(()=>{})}function q(L){let U=setTimeout(()=>{C(L)},k(L));U.unref?.(),L==="text_done"?(x(),y=U):(R(),g=U)}let K=!1,ue,le,Nt=new Promise((L,U)=>{ue=L,le=U});Nt.catch(()=>{});let Qe=setTimeout(()=>{K||(K=!0,le(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);Qe.unref?.();function V(L){K||(K=!0,clearTimeout(Qe),L?le(L):ue())}let O="";function J(L){if(a.lastEventAtMs=Date.now(),L.type==="system"&&L.subtype==="init"){if(m=L.session_id||m,t.sessionId&&typeof L.session_id=="string"&&L.session_id.length>0&&L.session_id!==t.sessionId){let oe=new Error(`stream-json bundle: provider resumed a different session (init reported "${L.session_id}", expected "${t.sessionId}")`);V(oe),ee(i).catch(()=>{});return}V()}let U=w?.processor.sawResult()??!0;L.type==="assistant"?(h=!Mu(L),_=h&&L.message?.stop_reason==="pause_turn"):(L.type==="result"||L.type==="user")&&(h=!1,_=!1),x(),e==="claude"&&a.turnActive&&h&&!_&&!U&&q("text_done"),R(),e==="claude"&&a.turnActive&&!U&&q("tool_use_silence")}function Fn(){let L=w;if(L===null)return;let U=L.processor.finalize();if(U!==null){if(w=null,a.turnActive=!1,x(),R(),U.isError){N({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:U.errorMessage}),L.reject(new Error(`${e} reported an error for this turn (no assistant output)`+(t.sessionId?` \u2014 session=${t.sessionId}`:"")+`: ${U.errorMessage??"unknown error"}`));return}a.completedTurns+=1,l=U.sessionId||l,ce(`stream-json bundle: result ${U.result.slice(0,80)}${U.result.length>80?"...":""} (${U.durationMs}ms)`),L.resolve({result:U.result,sessionId:U.sessionId||l,durationMs:U.durationMs,numTurns:U.numTurns})}}function Pr(L){if(!L.trim())return;let U;try{U=JSON.parse(L)}catch{return}J(U);let oe=w;if(oe!==null){let Qt=oe.processor.sawResult();oe.processor.processLine(L),oe.onEventForward?.(U),!Qt&&oe.processor.sawResult()&&Fn()}}i.stdout?.on("data",L=>{O+=L.toString();let U=O.split(`
|
|
1613
|
+
`);O=U.pop()||"";for(let oe of U)Pr(oe)}),i.on("error",L=>{if(c=new Z(`Failed to spawn ${r}: ${L.message}`,{cause:L}),N({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:L.message}),V(c),w!==null){let U=w;w=null,a.turnActive=!1,U.reject(c)}}),i.on("exit",L=>{a.exited=!0,a.exitCode=L,x(),R(),O.trim()&&Pr(O),V(a.exited&&!K?new Error(`stream-json bundle: ${e} exited (code ${String(L)}) before its init event`):void 0);let U=w;U!==null&&(w=null,a.turnActive=!1,U.aborted||(T!==null&&p==="text_done"&&d.trim().length>0?(N({event:"transport_stall_finalized",provider:e,reason:T,text_len:d.length}),U.resolve({result:d,sessionId:m||t.sessionId||"",durationMs:Date.now()-U.startMs,numTurns:1,warnings:[T]})):T!==null&&p==="tool_use_silence"?(N({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:L,stderr_tail:u.slice(0,500)}),U.reject(new Error(`${T} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(t.sessionId?` (session=${t.sessionId})`:"")))):(N({event:"transport_error",provider:e,error_class:"Error",reason:T!==null?"provider_stalled_no_content":"provider_no_result",exit_code:L,stderr_tail:u.slice(0,500)}),U.reject(I()))));for(let oe of b.splice(0))oe()});try{t.sessionId&&await Ru(e,t.sessionId,t.sessionFileRoots),await Nt}catch(L){let U=c??(L instanceof Error?L:new Error(String(L))),oe=t.closeTimeoutMs??2e3;throw await ee(i,{softDelayMs:Math.min(1e3,oe),killDelayMs:Math.min(1e3,oe)}).catch(()=>{}),U}let Ri=L=>new Promise(U=>{setTimeout(U,L).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(L,U={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw I();if(w!==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,ee(i).catch(()=>{}),new Error("Aborted"));if(U.signal?.aborted)throw oe();if(t.sessionId&&(await Ru(e,t.sessionId,t.sessionFileRoots),a.exited))throw I();if(U.signal?.aborted)throw oe();return d="",h=!1,_=!1,T=null,p=null,f=null,new Promise((Qt,Pn)=>{let Li={processor:xs({onText:Vl=>{d+=Vl,U.onText?.(Vl)}}),resolve:Qt,reject:Pn,startMs:Date.now(),aborted:!1,onEventForward:U.onEvent};w=Li,a.turnActive=!0;let Rg=()=>{Li.aborted=!0,N({event:"transport_abort",provider:e}),a.closed=!0,ee(i).catch(()=>{}),w===Li&&(w=null,a.turnActive=!1),Pn(new Error("Aborted"))};U.signal?.addEventListener("abort",Rg,{once:!0});let Lg=JSON.stringify({type:"user",message:{role:"user",content:L}});i.stdin?.write(`${Lg}
|
|
1614
|
+
`),ce(`stream-json bundle: prompt sent (${L.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(L=>{wt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),L()},label:e})}):i.stdin?.end(),!a.exited)){let L=t.closeTimeoutMs??2e3;await Promise.race([S(),Ri(L)]),a.exited||await ee(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,L),killDelayMs:Math.min(1e3,L)}).catch(()=>{})}})()),a.closing}}}var kT,RT,No=A(()=>{"use strict";jt();sn();it();z();Is();Je();ko();me();ko();kT={claude:"claude",qwen:"qwen"};RT={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function ks(t={}){return[]}var Ro=A(()=>{"use strict"});function Lo(t){return t==="plan"?"read-only":"danger-full-access"}function Uu(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function Ns(){return{agentItems:new Map,resultText:""}}function wr(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,u=typeof i?.turnId=="string"?i.turnId:void 0;n({itemId:o.id,threadId:c,turnId:u,expectedFromItemText:o.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(o.id)}return!0}return!1}return!1}function Rs(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function ju(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 Ls(){return{pendingCodexError:null}}function Cs(t,e){let r=ju(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function Os(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 Co=A(()=>{"use strict"});import{spawn as Hu}from"node:child_process";import{createInterface as Bu}from"node:readline";import{existsSync as CT,readFileSync as OT}from"node:fs";import{fileURLToPath as DT}from"node:url";function Wu(){return Uu(MT)}function St(t,e){ce(`[codex:${t}] ${JSON.stringify(e)}`)}function FT(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
1615
1615
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1616
1616
|
${e}
|
|
1617
1617
|
|
|
1618
|
-
${r}`:r}function
|
|
1618
|
+
${r}`:r}function Xu(t){let e=t.binaryPath||"codex",r=["app-server","--listen","stdio://"];t.model&&r.push("-c",`model=${JSON.stringify(t.model)}`);let n=t.isLead??t.alias?.toLowerCase()==="lead",s=n?ks():[];r.push(...s),te()&&xe(JSON.stringify({event:"codex_mcp_inject",alias:t.alias??null,isLead:n,injected:s.length>0}));let i=t.permissionMode??"yolo",o=Lo(i);if(fe("codex",r,i),t.cwd&&!CT(t.cwd))throw N({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`}),new Z(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:e,codexArgs:r,sandbox:o,permissionMode:i,spawnEnv:de(t.env,t.cwd,t.threadId)}}function qu(t,e){return new Promise((r,n)=>{let s,i,o;try{({binary:s,codexArgs:i,sandbox:o}=Xu(e))}catch(w){return n(w instanceof Error?w:new Error(String(w)))}let a=Hu(s,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:de(e.env,e.cwd,e.threadId)}),l=!1;if(e.signal){if(e.signal.aborted)return l=!0,N({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),ee(a).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{l=!0,N({event:"transport_abort",provider:"codex"}),ee(a).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let c=Bu({input:a.stdout}),u=new Map,d=1,m=e.threadId||"",h="",_=!1,T=!1,p=Date.now(),f=Ns(),y=Ls();function g(w,b={}){return new Promise((S,I)=>{let x=d++;u.set(x,{resolve:S,reject:I});let R=JSON.stringify({jsonrpc:"2.0",id:x,method:w,params:b});a.stdin?.write(R+`
|
|
1619
1619
|
`)})}function E(w,b={}){let S=JSON.stringify({jsonrpc:"2.0",method:w,params:b});a.stdin?.write(S+`
|
|
1620
|
-
`)}c.on("line",w=>{let b;try{b=JSON.parse(w)}catch{return}if(typeof b.id=="number"&&u.has(b.id)){let x=u.get(b.id);if(u.delete(b.id),b.error){let R=b.error,P=typeof R?.message=="string"&&R.message.length>0?R.message:JSON.stringify(b.error);x.reject(
|
|
1621
|
-
`),N({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:w instanceof Error?w.message:String(w)});let S=(await g("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;S?.id&&(m=S.id)}else{let b=(await g("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;b?.id&&(m=b.id)}await g("turn/start",{threadId:m,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(w){ee(a).catch(()=>{}),n(w instanceof Error?w:new Error(String(w)))}})()})}async function
|
|
1620
|
+
`)}c.on("line",w=>{let b;try{b=JSON.parse(w)}catch{return}if(typeof b.id=="number"&&u.has(b.id)){let x=u.get(b.id);if(u.delete(b.id),b.error){let R=b.error,P=typeof R?.message=="string"&&R.message.length>0?R.message:JSON.stringify(b.error);x.reject(nn(`codex app-server error: ${P}`,R))}else x.resolve(b);e.onEvent?.(b);return}let S=b.method;if(!S){e.onEvent?.(b);return}if(S==="thread/started"){let R=b.params?.thread;R?.id&&(m=R.id)}let I=te()?x=>{St("item.text/buffer-mismatch",{itemId:x.itemId,threadId:x.threadId??null,turnId:x.turnId??null,expectedFromItemText:x.expectedFromItemText,gotFromBuffer:x.gotFromBuffer,expectedLen:x.expectedFromItemText.length,gotLen:x.gotFromBuffer.length})}:void 0;if(S==="turn/started"){let x=b.params,R=x?.turn;R?.id&&(h=R.id),wr(b,f,e.onDelta,I),te()&&St("turn/started",{params:x??null})}if(te()&&(S==="item/started"||S==="item/completed")){let x=b.params;x?.item?.type==="agentMessage"&&St(S,{params:x??null})}if(S==="item/started"||S==="item/agentMessage/delta"||S==="item/completed"){if(S==="item/agentMessage/delta"){let x=b.params;te()&&St("agentMessage/delta",{params:x??null})}wr(b,f,e.onDelta,I)}if(S==="turn/completed"){let x=b.params;if(te())for(let[P,k]of f.agentItems.entries())k.buffer&&St("turn/completed/unflushed-item",{itemId:P,phase:k.phase,bufferLen:k.buffer.length});Rs(f),te()&&St("turn/completed",{params:x??null});let R=Os(b,y);R.shouldReject?(te()&&St("turn/completed/terminal-reject",{message:R.turnError.message}),T=!0,_=!0,a.stdin?.end(),n(R.turnError)):(_=!0,a.stdin?.end())}if(S==="error"){let x=Cs(b,y);if(te()){let R=b.params,P=R?.error,k=typeof P?.message=="string"?P.message:"(no message)";St(x.willRetry?"error/retry":"error/terminal-deferred",{message:k,willRetry:x.willRetry,params:R??null})}}e.onEvent?.(b)});let v="";a.stderr?.on("data",w=>{v+=w.toString()}),a.on("error",w=>{N({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:w.message}),n(new Z(`Failed to spawn codex app-server: ${w.message}`,{cause:w}))}),a.on("exit",w=>{if(!l&&!T){if(_){r({result:f.resultText,threadId:m,turnId:h,durationMs:Date.now()-p,exitCode:w});return}if(y.pendingCodexError){n(y.pendingCodexError);return}N({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:w,stderr_tail:v.slice(0,500)}),n(new Error(FT({exitCode:w,stderr:v})))}}),(async()=>{try{if(await g("initialize",Wu()),E("initialized",{}),e.threadId)try{let w=g("thread/resume",{threadId:e.threadId,sandbox:o,approvalPolicy:"never",...e.model?{model:e.model}:{}}),b=new Promise((S,I)=>setTimeout(()=>I(new Error("resume timeout")),3e4));await Promise.race([w,b]),m=e.threadId}catch(w){process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1621
|
+
`),N({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:w instanceof Error?w.message:String(w)});let S=(await g("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;S?.id&&(m=S.id)}else{let b=(await g("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;b?.id&&(m=b.id)}await g("turn/start",{threadId:m,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(w){ee(a).catch(()=>{}),n(w instanceof Error?w:new Error(String(w)))}})()})}async function Gu(t){let{binary:e,codexArgs:r,sandbox:n}=Xu(t),s=Hu(e,r,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:de(t.env,t.cwd,t.threadId)}),i=Date.now(),o={exited:!1,exitCode:null,completedTurns:0,closed:!1,closing:null},a=t.threadId||"",l=null,c="";s.stderr?.on("data",v=>{c+=v.toString()});let u=Bu({input:s.stdout}),d=new Map,m=1;function h(v,w={}){return new Promise((b,S)=>{let I=m++;d.set(I,{resolve:b,reject:S});let x=JSON.stringify({jsonrpc:"2.0",id:I,method:v,params:w});s.stdin?.write(x+`
|
|
1622
1622
|
`)})}function _(v,w={}){let b=JSON.stringify({jsonrpc:"2.0",method:v,params:w});s.stdin?.write(b+`
|
|
1623
|
-
`)}let T=[],p=()=>o.exited?Promise.resolve():new Promise(v=>{T.push(v)}),f=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),y=null;function g(v){let w=y;w===null||w.settled||(w.settled=!0,y=null,v&&w.reject(v))}u.on("line",v=>{let w;try{w=JSON.parse(v)}catch{return}if(typeof w.id=="number"&&d.has(w.id)){let I=d.get(w.id);if(d.delete(w.id),w.error){let x=w.error,R=typeof x?.message=="string"&&x.message.length>0?x.message:JSON.stringify(w.error);I.reject(
|
|
1623
|
+
`)}let T=[],p=()=>o.exited?Promise.resolve():new Promise(v=>{T.push(v)}),f=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),y=null;function g(v){let w=y;w===null||w.settled||(w.settled=!0,y=null,v&&w.reject(v))}u.on("line",v=>{let w;try{w=JSON.parse(v)}catch{return}if(typeof w.id=="number"&&d.has(w.id)){let I=d.get(w.id);if(d.delete(w.id),w.error){let x=w.error,R=typeof x?.message=="string"&&x.message.length>0?x.message:JSON.stringify(w.error);I.reject(nn(`codex app-server error: ${R}`,x))}else I.resolve(w);y?.onEvent?.(w);return}let b=w.method;if(!b){y?.onEvent?.(w);return}if(b==="thread/started"){let x=w.params?.thread;x?.id&&(a=x.id)}let S=y;if(b==="turn/started"&&S!==null){let x=w.params?.turn;x?.id&&(S.turnId=x.id),wr(w,S.agentState,S.onDelta,void 0)}if(S!==null&&(b==="item/started"||b==="item/agentMessage/delta"||b==="item/completed")&&wr(w,S.agentState,S.onDelta,void 0),b==="turn/completed"&&S!==null&&!S.settled){Rs(S.agentState);let I=Os(w,S.turnState);S.settled=!0,y=null,I.shouldReject?S.reject(I.turnError):(o.completedTurns+=1,S.resolve({text:S.agentState.resultText,sessionId:a,turnId:S.turnId,durationMs:Date.now()-S.startMs}))}b==="error"&&S!==null&&Cs(w,S.turnState),S?.onEvent?.(w)}),s.on("error",v=>{l=new Z(`Failed to spawn codex app-server: ${v.message}`,{cause:v}),N({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:v.message});for(let w of d.values())w.reject(l);d.clear(),g(l)}),s.on("exit",v=>{o.exited=!0,o.exitCode=v;let w=f();for(let S of d.values())S.reject(w);d.clear();let b=y;b!==null&&!b.settled&&(b.settled=!0,y=null,b.turnState.pendingCodexError?b.reject(b.turnState.pendingCodexError):(N({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:v,stderr_tail:c.slice(0,500)}),b.reject(w)));for(let S of T.splice(0))S()});try{if(await h("initialize",Wu()),_("initialized",{}),t.threadId){let v;try{v=await h("thread/resume",{threadId:t.threadId,sandbox:n,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(b){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${b instanceof Error?b.message:String(b)} (the thread/start fallback is disabled in bundle mode)`)}let w=v.result?.thread;if(typeof w?.id=="string"&&w.id.length>0){if(w.id!==t.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${t.threadId}", received "${w.id}"`);a=w.id}}else{let w=(await h("thread/start",{cwd:t.cwd,approvalPolicy:"never",sandbox:n,...t.model?{model:t.model}:{}})).result?.thread;w?.id&&(a=w.id)}}catch(v){let w=l??(v instanceof Error?v:new Error(String(v))),b=t.closeTimeoutMs??2e3;throw await ee(s,{softDelayMs:Math.min(1e3,b),killDelayMs:Math.min(1e3,b)}).catch(()=>{}),w}let E=v=>new Promise(w=>{setTimeout(w,v).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(v,w={}){if(o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw f();if(y!==null)throw new Error("codex bundle session has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending");if(w.signal?.aborted)throw new Error("Aborted");return new Promise((b,S)=>{let I={agentState:Ns(),turnState:Ls(),resolve:b,reject:S,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};y=I;let x=()=>{I.settled||(I.settled=!0,y=null,I.turnId&&h("turn/interrupt",{threadId:a,turnId:I.turnId}).catch(()=>{}),S(new Error("Aborted")))};w.signal?.addEventListener("abort",x,{once:!0}),h("turn/start",{threadId:a,input:[{type:"text",text:v}],...t.model?{model:t.model}:{}}).catch(R=>{I.settled||(I.settled=!0,y=null,w.signal?.removeEventListener("abort",x),S(o.exited?f():R instanceof Error?R:new Error(String(R))))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,!o.exited&&(t.holdOpen!==void 0?await new Promise(v=>{wt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>y!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),v()},label:"codex"})}):s.stdin?.end(),!o.exited)){let v=t.closeTimeoutMs??2e3;await Promise.race([p(),E(v)]),o.exited||await ee(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,v),killDelayMs:Math.min(1e3,v)}).catch(()=>{})}})()),o.closing}}}var MT,Ju=A(()=>{"use strict";z();z();jt();sn();Is();it();Ro();z();Je();Co();Co();MT=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(OT(DT(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});function Ds(t){let e=[...t.matchAll(PT)];if(e.length>0){let r=e[e.length-1],n=(r.index??0)+r[0].length;return Ku(t.slice(n).trimStart())}return Ku(BT(t.replace($T,"")))}function BT(t){let e=UT.exec(t);if(e===null)return t;let r=t.slice(e[0].length),n=[...r.matchAll(jT)];if(n.length<2)return t;let s=n[0],i=(s.index??0)+s[0].length;return r.slice(i).trimStart()}function Ku(t){let e=[...t.matchAll(HT)];if(e.length===0)return t;let r=e[e.length-1],n=(r.index??0)+r[0].length;return t.slice(n).trimStart()}function vt(t,e=""){let r=t.result;return typeof r?.sessionId=="string"&&r.sessionId.length>0?r.sessionId:e}function Yu(t){let e=t.result;return typeof e?.stopReason=="string"?e.stopReason:""}function Ms(t={}){let e="",r="",n="",s=!1,i=!1,o=!1,a=t.isolateResult??(t.tool==="gemini"?Ds:void 0),l=()=>({result:a?a(r):r,sessionId:e,stopReason:n,sawActivity:o});return{setSessionId(c){e=c},beginTurn(){r="",n="",s=!1,i=!0,o=!1},completeTurn(c){return n=Yu(c),s=!0,i=!1,l()},cancelTurn(){r="",n="",i=!1},processMessage(c){if(c.method!=="session/update")return!1;let d=c.params?.update,m=d?.sessionUpdate;if(typeof m!="string"||(i&&WT.has(m)&&(o=!0),m!=="agent_message_chunk"))return!1;let h=d?.content,_=typeof h?.text=="string"?h.text:"";return _&&i&&(r+=_,t.onDelta?.(_)),!0},finalize(){return s?l():null}}}var Vu,PT,$T,UT,jT,HT,WT,on=A(()=>{"use strict";Vu="(?:png|jpe?g|webp|heic|pdf)",PT=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${Vu}\\s*`,"gi"),$T=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${Vu}\\s*`,"i"),UT=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,jT=/^STANCE:\s+\S+\s*$/gim,HT=/\[Thought:\s*true\]\s*/gi;WT=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"])});import{createInterface as XT}from"node:readline";function an(t,e){let r=XT({input:t.stdout}),n=new Map,s=(o,a={})=>new Promise((l,c)=>{let u=qT++;n.set(u,{resolve:l,reject:c});let d=JSON.stringify({jsonrpc:"2.0",id:u,method:o,params:a});_e({event:"acp_send",direction:"SEND",provider:e.provider,method:o,id:u,params:a}),t.stdin?.write(`${d}
|
|
1624
1624
|
`)}),i=(o,a={})=>{t.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:o,params:a})}
|
|
1625
|
-
`)};return r.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(_e({event:"acp_recv",direction:"RECV",provider:e.provider,id:typeof a.id=="number"?a.id:void 0,method:typeof a.method=="string"?a.method:void 0,preview:JSON.stringify(a).slice(0,300)}),e.onEvent?.(a),typeof a.id=="number"&&n.has(a.id)){let c=n.get(a.id);if(n.delete(a.id),a.error){let u=a.error,d=typeof u?.message=="string"&&u.message.length>0?u.message:JSON.stringify(a.error);c.reject(
|
|
1626
|
-
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new Z("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}var
|
|
1625
|
+
`)};return r.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(_e({event:"acp_recv",direction:"RECV",provider:e.provider,id:typeof a.id=="number"?a.id:void 0,method:typeof a.method=="string"?a.method:void 0,preview:JSON.stringify(a).slice(0,300)}),e.onEvent?.(a),typeof a.id=="number"&&n.has(a.id)){let c=n.get(a.id);if(n.delete(a.id),a.error){let u=a.error,d=typeof u?.message=="string"&&u.message.length>0?u.message:JSON.stringify(a.error);c.reject(nn(`ACP RPC error: ${d}`,u))}else c.resolve(a);return}let l=a.method;if(l){if(typeof a.id=="number"){N({event:"acp_unhandled_request",provider:e.provider,method:l,id:a.id,params:a.params});let c=JSON.stringify({jsonrpc:"2.0",id:a.id,error:{code:-32601,message:`Method not found: ${l} (lmctl does not implement server-side ACP methods)`}});_e({event:"acp_send",direction:"SEND",provider:e.provider,replyTo:a.id,error:"method not found"}),t.stdin?.write(`${c}
|
|
1626
|
+
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new Z("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}var qT,Oo=A(()=>{"use strict";z();jt();qT=1});import{readFileSync as GT,readdirSync as zu}from"node:fs";import{join as Fs}from"node:path";function Qu(t,e){let r=e.GEMINI_DIR??process.env.GEMINI_DIR??Fs(H,".gemini"),n=Fs(r,"tmp"),s;try{s=zu(n)}catch{throw new Error(`gemini bundle: cannot read the gemini session store at ${n} \u2014 cannot verify session "${t}"`)}let i=`"sessionId": "${t}"`,o=`"sessionId":"${t}"`;for(let a of s){let l=Fs(n,a,"chats"),c;try{c=zu(l)}catch{continue}for(let u of c){if(!u.endsWith(".json"))continue;let d;try{d=GT(Fs(l,u),"utf8").slice(0,8192)}catch{continue}if(d.includes(i)||d.includes(o))return}}throw new Error(`gemini bundle: no session "${t}" in the gemini chats store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var ln,Zu=A(()=>{"use strict";on();me();it();ln={name:"gemini",binary:"gemini",baseArgs:["--acp","-y","--skip-trust"],argv(t){let e=[...ln.baseArgs];if(t.permissionMode==="plan"){let r=Tt("gemini","plan"),n=Tt("gemini","yolo");e=e.filter(s=>!(n??[]).includes(s)),r&&e.push(...r)}return t.model&&e.push("--model",t.model),e},isolateResult:Ds,sessionIdentity:{verifyLoadedSession:t=>{Qu(t.requestedSessionId,t.env)},recheckSession:t=>{Qu(t.requestedSessionId,t.env)}}}});import{existsSync as JT,readFileSync as KT}from"node:fs";import{join as Do}from"node:path";function em(t,e){let r=e.COPILOT_HOME??process.env.COPILOT_HOME??Do(H,".copilot"),n=Do(r,"session-state",t),s=Do(n,"workspace.yaml");if(!JT(s))throw new Error(`copilot bundle: no session "${t}" in the copilot session store (${n}) \u2014 the session must exist on disk before a bundle can resume it`);let i;try{i=KT(s,"utf8").slice(0,4096)}catch(a){throw new Error(`copilot bundle: cannot read ${s} \u2014 cannot verify session "${t}": `+(a instanceof Error?a.message:String(a)))}let o=/^id:\s*(\S+)\s*$/m.exec(i);if(o===null||o[1]!==t)throw new Error(`copilot bundle: session store entry ${s} belongs to ${o?.[1]??"no recorded id"}, not "${t}"`)}var cn,tm=A(()=>{"use strict";z();me();cn={name:"copilot",binary:"copilot",baseArgs:["--acp","--yolo"],argv(t){return t.permissionMode==="plan"&&(process.stderr.write(`[acp] copilot has no plan-mode flag in --acp mode; --permission-mode plan is not honored (running yolo). See src/providers/yolo-contract.ts.
|
|
1627
1627
|
`),N({event:"acp_plan_mode_unsupported",provider:"copilot",requested_mode:"plan",effective_mode:"yolo"})),t.model&&(process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${t.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
1628
|
-
`),N({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...
|
|
1629
|
-
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function
|
|
1630
|
-
`,"utf-8"),!0}let s;try{s=JSON.parse(
|
|
1631
|
-
`,"utf-8"),i}var
|
|
1628
|
+
`),N({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...cn.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{em(t.requestedSessionId,t.env)},recheckSession:t=>{em(t.requestedSessionId,t.env)}}}});import{existsSync as sm,mkdirSync as VT,readFileSync as im,writeFileSync as rm}from"node:fs";import{join as dn,resolve as YT}from"node:path";function om(t){if(t==="allow")return!0;if(t&&typeof t=="object"&&!Array.isArray(t)){let e=Object.entries(t);if(e.length===1&&e[0][0]==="*"&&e[0][1]==="allow")return!0}return!1}function Mo(t,e,r={existsSync:sm,readFileSync:im}){let n=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let i=YT(e,s.sessiondir??e);for(let o of zT(i)){let a=QT(o,r);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(om(a.permission)||n.push(`[${s.alias}] ${o} sets a non-allow \`permission\`, which opencode merges over lmctl's YOLO (.opencode/opencode.json permission:"allow") \u2014 the member may hang on permission prompts. Set \`permission: "allow"\` in that file (or remove the key).`))}}return n}function zT(t){return[dn(t,".opencode","opencode.jsonc"),dn(t,"opencode.jsonc"),dn(t,"opencode.json")]}function QT(t,e){try{if(!e.existsSync(t))return;let r=e.readFileSync(t,"utf-8"),n=JSON.parse(ZT(r));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function ZT(t){let e="",r=!1,n="",s=!1;for(let i=0;i<t.length;i+=1){let o=t[i],a=t[i+1];if(r){e+=o,s?s=!1:o==="\\"?s=!0:o===n&&(r=!1,n="");continue}if(o==='"'||o==="'"){r=!0,n=o,e+=o;continue}if(o==="/"&&a==="/"){for(;i<t.length&&t[i]!==`
|
|
1629
|
+
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function am(t,e={}){let r=dn(t,".opencode"),n=dn(r,"opencode.json");if(!sm(n)){VT(r,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return rm(n,o+`
|
|
1630
|
+
`,"utf-8"),!0}let s;try{s=JSON.parse(im(n,"utf-8"))}catch{return console.log(nm.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(nm.yellow(` .opencode/opencode.json at ${n} is not an object \u2014 skipping opencode config install.`)),!1;let i=!1;return s.permission===void 0&&(s.permission="allow",i=!0),om(s.permission)||N({event:"opencode_yolo_override",provider:"opencode",config_path:n,user_permission:s.permission,message:`opencode.json has a user-set 'permission' value other than 'allow' \u2014 lmctl's YOLO contract is NOT in effect; turns may hang waiting on permission prompts. Set permission: "allow" or remove the key to restore YOLO.`}),i&&rm(n,JSON.stringify(s,null,2)+`
|
|
1631
|
+
`,"utf-8"),i}var nm,Fo=A(()=>{"use strict";z();nm={yellow:t=>t}});import{existsSync as $o,readdirSync as ew,statSync as lm}from"node:fs";import{join as bt}from"node:path";import{createRequire as tw}from"node:module";function Uo(){return Po===null&&(Po=tw(import.meta.url)("node:sqlite").DatabaseSync),Po}function cm(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalCacheWriteInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function dm(t,e){if(!e)return;t.observed=!0;let r=e.input??0,n=e.output??0,s=e.reasoning??0,i=e.cache?.read??0,o=e.cache?.write??0;if(t.totalInputTokens+=r,t.totalCachedInputTokens+=i,t.totalCacheWriteInputTokens+=o,t.totalOutputTokens+=n,t.totalReasoningOutputTokens+=s,r+n+s+i+o>0){let a=r+i+o;t.lastInputTokens=a,t.lastTokenUsage={inputTokens:r,cachedInputTokens:i,cacheWriteInputTokens:o,outputTokens:n,reasoningOutputTokens:s,totalTokens:a+n+s}}}function um(t){return t.observed?{totalInputTokens:t.totalInputTokens,totalCachedInputTokens:t.totalCachedInputTokens,totalCacheWriteInputTokens:t.totalCacheWriteInputTokens,totalOutputTokens:t.totalOutputTokens,totalReasoningOutputTokens:t.totalReasoningOutputTokens,lastInputTokens:t.lastInputTokens,lastTokenUsage:t.lastTokenUsage}:{}}function mm(){let t=process.env.XDG_DATA_HOME||bt(H,".local","share"),e=process.env.XDG_CONFIG_HOME||bt(H,".config");return[bt(t,"opencode","opencode.db"),bt(e,"opencode","opencode.db")]}function rw(){if(process.env.OPENCODE_DB)return[process.env.OPENCODE_DB];let t=process.env.XDG_DATA_HOME||bt(H,".local","share"),e=bt(t,"lmplayer"),r=bt(e,"opencode-local.db"),n=[r];try{let s=ew(e).filter(i=>/^opencode.*\.db$/u.test(i)).map(i=>bt(e,i)).filter(i=>i!==r).sort((i,o)=>{try{return lm(o).mtimeMs-lm(i).mtimeMs}catch{return 0}});n.push(...s)}catch{}return n}function nw(t){return t==="lmplayer"?rw():mm()}function jo(t,e){let r=e?.dbPath!==void 0?[e.dbPath]:mm();for(let n of r){if(!$o(n))continue;let s=new(Uo())(n,{open:!0,readOnly:!0});try{s.exec("PRAGMA busy_timeout = 5000");let i=s.prepare("SELECT directory FROM session WHERE id = ?").get(t);if(i!==void 0)return{directory:typeof i.directory=="string"?i.directory:""}}finally{s.close()}}return null}var Po,Sr,Ps=A(()=>{"use strict";me();z();Po=null;Sr=class{name;startCommand;dbPaths;busyTimeoutMs;constructor(e){this.name=e?.providerName??"opencode",this.startCommand=e?.startCommand??this.name,this.busyTimeoutMs=e?.busyTimeoutMs??5e3,e?.dbPath?this.dbPaths=[e.dbPath]:this.dbPaths=nw(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>$o(e))}openDb(e){if(!$o(e))return null;let r=new(Uo())(e,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),r}async discoverSessions(){let e=[];for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=new Map,i=n.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=n.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1632
1632
|
s.time_created, s.time_updated
|
|
1633
1633
|
FROM session s
|
|
1634
1634
|
ORDER BY s.time_updated DESC`).all();for(let a of o){let l=s.get(a.project_id),c=a.directory||l?.worktree||"(unknown)",u=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
1635
|
-
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),d=0,m,h,_,T=
|
|
1636
|
-
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,u,d,m,h=
|
|
1637
|
-
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(
|
|
1635
|
+
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),d=0,m,h,_,T=cm(),p=[];for(let y of u){let g;try{g=JSON.parse(y.data)}catch{continue}_||(_=g.model?.modelID||g.modelID),(g.role==="user"||g.role==="assistant")&&d++,g.role==="user"&&p.push(y.id),g.role==="assistant"&&dm(T,g.tokens)}let f=[...p.length>0?[p[0]]:[],...p.length>1?[p[p.length-1]]:[]];for(let y of f){let g=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(y),E=this.extractText(g);E&&(m||(m=$(E,80)),h=$(E,80))}e.push({provider:this.name,sessionId:a.id,slug:a.slug,cwd:c,createdAt:new Date(a.time_created),modifiedAt:new Date(a.time_updated),model:_,startCommand:this.startCommand,firstUserMessage:m,lastUserMessage:h,messageCount:d,filePath:r,...um(T)})}}catch(s){N({event:"opencode_discover_sessions_failed",provider:this.name,db_path:r,error_message:s instanceof Error?s.message:String(s)})}finally{n.close()}}return e.sort((r,n)=>n.modifiedAt.getTime()-r.modifiedAt.getTime())}async loadSession(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=this.findSessionRow(n,e);if(!s)continue;return this.buildSessionDetail(n,s,r)}catch{}finally{n.close()}}return null}buildSessionDetail(e,r,n){let s=e.prepare("SELECT id, worktree, name FROM project WHERE id = ?").get(r.project_id),i=r.directory||s?.worktree||"(unknown)",o=e.prepare(`SELECT id, session_id, time_created, time_updated, data
|
|
1636
|
+
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,u,d,m,h=cm();for(let _ of o){let T;try{T=JSON.parse(_.data)}catch{continue}u||(u=T.model?.modelID||T.modelID);let p=T.model?.modelID||T.modelID,f=new Date(T.time?.created||_.time_created),y=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(_.id);if(T.role==="user"){let g=this.extractText(y),E=this.extractText(y,!0);E&&l.push(E),g&&(d||(d=$(g,80)),m=$(g,80)),a.push({role:"user",timestamp:f,content:g||"(empty)"}),c++}else if(T.role==="assistant"){dm(h,T.tokens);for(let g of y){let E;try{E=JSON.parse(g.data)}catch{continue}E.type==="text"&&E.text?a.push({role:"assistant",timestamp:f,content:E.text,model:p}):E.type==="reasoning"&&E.text?a.push({role:"thinking",timestamp:f,content:E.text}):E.type==="tool"&&E.tool&&(a.push({role:"tool_use",timestamp:f,content:`${E.tool}`,toolName:E.tool,toolCallId:E.callID,toolInput:E.state?.input?JSON.stringify(E.state.input):void 0,toolInputData:De(E.state?.input)}),E.state&&(E.state.status==="completed"||E.state.status==="error"||E.state.output!==void 0||E.state.error!==void 0)&&a.push({role:"tool_result",timestamp:f,content:E.state.error??E.state.output??"",toolCallId:E.callID}))}c++}}return{provider:this.name,sessionId:r.id,slug:r.slug,cwd:i,createdAt:new Date(r.time_created),modifiedAt:new Date(r.time_updated),model:u,startCommand:this.startCommand,firstUserMessage:d,lastUserMessage:m,messageCount:c,filePath:n,...um(h),messages:a,userPrompts:l}}extractText(e,r=!1){let n=[];for(let s of e){let i;try{i=JSON.parse(s.data)}catch{continue}r&&(i.synthetic===!0||i.ignored===!0)||i.type==="text"&&i.text&&n.push(i.text)}return n.join(`
|
|
1637
|
+
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(Uo())(r,{open:!0});try{let s=this.findSessionRow(n,e);if(!s)continue;return n.prepare("DELETE FROM session WHERE id = ?").run(s.id).changes>0}catch{}finally{n.close()}}return!1}findSessionRow(e,r){let n=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1638
1638
|
s.time_created, s.time_updated
|
|
1639
1639
|
FROM session s WHERE s.id = ?`).get(r);if(n)return n;let s=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1640
1640
|
s.time_created, s.time_updated
|
|
1641
1641
|
FROM session s
|
|
1642
1642
|
WHERE s.id LIKE ?
|
|
1643
1643
|
ORDER BY s.time_updated DESC
|
|
1644
|
-
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function
|
|
1645
|
-
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var
|
|
1644
|
+
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function un(t){return{id:t.id,onFailure:"non-fatal",applies:e=>t.value(e)!==void 0,run:async e=>{await e.sendRpc("session/set_config_option",{sessionId:e.sessionId,configId:t.configId,value:t.value(e)})},describeFailure:(e,r)=>{let n=t.value(e),s=r instanceof Error?r.message:String(r);return{event:"acp_config_option_failed",fields:{config_id:t.configId,value:n,error_message:s},stderrLine:`[acp] set_config_option(${t.configId}=${n}) failed: ${s}
|
|
1645
|
+
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var Ho=A(()=>{"use strict"});import{spawn as sw}from"node:child_process";import{resolve as fm}from"node:path";function $s(t){let e;try{e=sw(t.binaryPath??Ht.binary,[...Ht.baseArgs],{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:de(t.env,t.cwd,void 0,"unknown")})}catch(s){return Promise.resolve({status:"unavailable",reason:"spawn",error:s instanceof Error?s.message:String(s)})}let r=an(e,{provider:"opencode"}),n=t.timeoutMs??5e3;return new Promise(s=>{let i=!1,o=(u,d=!0)=>{if(!i){if(i=!0,clearTimeout(c),e.removeListener("error",a),e.removeListener("exit",l),r.close(),!d){s(u);return}ee(e,{softDelayMs:100,killDelayMs:100}).finally(()=>s(u))}},a=u=>{o({status:"unavailable",reason:"spawn",error:u.message},!1)},l=(u,d)=>{o({status:"unavailable",reason:"handshake",error:`opencode ACP exited before verification (code=${String(u)}, signal=${String(d)})`},!1)};e.once("error",a),e.once("exit",l);let c=setTimeout(()=>{o({status:"unavailable",reason:"timeout"})},n);(async()=>{try{await r.sendRpc("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r.sendNotification("notifications/initialized");let u=await r.sendRpc("session/new",{cwd:t.cwd,mcpServers:[]}),d=vt(u);try{await r.sendRpc("session/set_config_option",{sessionId:d,configId:"model",value:t.model})}catch(m){o({status:"rejected",option:"model",value:t.model,error:m instanceof Error?m.message:String(m)});return}if(t.effort!==void 0)try{await r.sendRpc("session/set_config_option",{sessionId:d,configId:"effort",value:t.effort})}catch(m){o({status:"rejected",option:"effort",value:t.effort,error:m instanceof Error?m.message:String(m)});return}o({status:"verified"})}catch(u){o({status:"unavailable",reason:"handshake",error:u instanceof Error?u.message:String(u)})}})()})}var Ht,Bo=A(()=>{"use strict";z();Fo();Ps();on();Je();sn();Oo();Ho();Ht={name:"opencode",binary:"opencode",baseArgs:["acp"],argv:()=>[...Ht.baseArgs],preSpawn(t){try{am(t.cwd)}catch(e){N({event:"opencode_config_install_failed",cwd:t.cwd,error_message:e instanceof Error?e.message:String(e)})}},sessionSetup:[un({id:"model",provider:"opencode",configId:"model",value:t=>t.model}),un({id:"effort",provider:"opencode",configId:"effort",value:t=>t.effort})],probe:$s,sessionIdentity:{verifyLoadedSession:t=>{let e=jo(t.requestedSessionId,{...t.env.OPENCODE_DB!==void 0?{dbPath:t.env.OPENCODE_DB}:{}});if(e===null)throw new Error(`opencode bundle: no session "${t.requestedSessionId}" in the opencode session store \u2014 the session must exist on disk before a bundle can resume it`);if(fm(e.directory)!==fm(t.cwd))throw new Error(`opencode bundle: session "${t.requestedSessionId}" belongs to ${e.directory}, not ${t.cwd} \u2014 refusing to resume another workspace's session`)},recheckSession:t=>{if(jo(t.requestedSessionId,{...t.env.OPENCODE_DB!==void 0?{dbPath:t.env.OPENCODE_DB}:{}})===null)throw new Error(`opencode bundle: session "${t.requestedSessionId}" disappeared from the session store mid-bundle`)}}}});import{existsSync as iw}from"node:fs";import{readdir as ow}from"node:fs/promises";import{join as Wo,resolve as aw}from"node:path";function hm(t){let e=lw.exec(t);return e?e[0]:null}function cw(t){if(!t.includes("notifications/initialized"))return t;let e=t.split(/\r?\n/),r=[];for(let n=0;n<e.length;n++){let s=e[n];if(s.includes("Error handling notification")&&s.includes("notifications/initialized")){let i=[s],o=n;for(;o+1<e.length&&i.length<8&&(o++,i.push(e[o]),e[o].trim()!=="}"););let a=i.join(`
|
|
1646
1646
|
`);if(/\bcode:\s*-32601\b/.test(a)&&/Method not found[^]*notifications\/initialized/.test(a)){n=o;continue}}r.push(s)}return r.join(`
|
|
1647
|
-
`)}async function
|
|
1648
|
-
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function
|
|
1647
|
+
`)}async function pm(t,e){let r=aw(e.KIMI_CODE_HOME??process.env.KIMI_CODE_HOME??Wo(H,".kimi-code")),n=Wo(r,"sessions"),s;try{s=await ow(n,{withFileTypes:!0})}catch{throw new Error(`kimi bundle: cannot read the kimi session store at ${n} \u2014 cannot verify session "${t}"`)}for(let i of s)if(i.isDirectory()&&iw(Wo(n,i.name,t,"agents","main","wire.jsonl")))return;throw new Error(`kimi bundle: no session "${t}" in the kimi session store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var lw,Xo,mn,qo=A(()=>{"use strict";z();me();Ho();lw=/runtime\s+\S+\s+does not exist in workspace\s+\S+/;Xo=t=>t.permissionMode==="plan"?"plan":"auto";mn={name:"kimi",binary:"kimi",baseArgs:["acp"],argv:()=>[...mn.baseArgs],sessionSetup:[{id:"permission-mode",onFailure:"fail-closed",applies:()=>!0,run:async t=>{await t.sendRpc("session/set_config_option",{sessionId:t.sessionId,configId:"mode",value:Xo(t)})},describeFailure:(t,e)=>{let r=Xo(t),n=e instanceof Error?e.message:String(e);return{event:"acp_permission_mode_failed",fields:{config_id:"mode",value:r,error_message:n},message:`Cannot set Kimi ACP permission mode to ${r}: ${n}`}},successLog:t=>`acp: set_config_option(mode=${Xo(t)}) ok`},un({id:"model",provider:"kimi",configId:"model",value:t=>t.model})],onExitFinalization(t){let e=hm(t.result);e!==null&&N({event:"kimi_runtime_dead",provider:"kimi",session_id:t.sessionId,matched_text:e})},filterExpectedStderr:cw,sessionIdentity:{verifyLoadedSession:async t=>{await pm(t.requestedSessionId,t.env)},recheckSession:async t=>{await pm(t.requestedSessionId,t.env)}}}});var fn,gm=A(()=>{"use strict";fn={name:"hermes",binary:"hermes",baseArgs:["acp"],argv(t){if(t.permissionMode==="plan")throw new Error('provider "hermes" does not support --permission-mode plan');return[...fn.baseArgs]},preSpawn(t){t.permissionMode==="yolo"&&(t.env.HERMES_YOLO_MODE="1")},modeVocabulary:{known:["default","accept_edits","dont_ask"],selectable:["accept_edits","dont_ask"]},sessionSetup:[{id:"session-mode",onFailure:"fail-closed",applies:t=>t.acpMode!==void 0,run:async t=>{await t.sendRpc("session/set_mode",{sessionId:t.sessionId,modeId:t.acpMode})},describeFailure:(t,e)=>{let r=e instanceof Error?e.message:String(e);return{event:"acp_session_mode_failed",fields:{mode_id:t.acpMode,error_message:r},message:`Cannot set hermes ACP session mode to ${String(t.acpMode)}: ${r}`}},successLog:t=>`acp: set_mode(modeId=${String(t.acpMode)}) ok`},{id:"model",onFailure:"fail-closed",applies:t=>{if(t.model===void 0)return!1;let e=t.response.result?.models?.currentModelId;return t.model!==e},run:async t=>{await t.sendRpc("session/set_model",{sessionId:t.sessionId,modelId:t.model})},describeFailure:(t,e)=>{let r=e instanceof Error?e.message:String(e);return{event:"acp_config_option_failed",fields:{config_id:"model",value:t.model,error_message:r},stderrLine:`[acp] set_model(modelId=${String(t.model)}) failed: ${r}
|
|
1648
|
+
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function pn(t){return dw[t]}var dw,uw,_m=A(()=>{"use strict";Zu();tm();Bo();qo();gm();dw={gemini:ln,copilot:cn,opencode:Ht,kimi:mn,hermes:fn};uw={gemini:{binary:ln.binary,args:ln.baseArgs},copilot:{binary:cn.binary,args:cn.baseArgs},opencode:{binary:Ht.binary,args:Ht.baseArgs},kimi:{binary:mn.binary,args:mn.baseArgs},hermes:{binary:fn.binary,args:fn.baseArgs}}});import{spawn as ym}from"node:child_process";import{existsSync as mw}from"node:fs";function Em(t,e){let r=pn(t)?.modeVocabulary;if(!r)throw new Z(`ACP mode "${e}" requested for provider "${t}", which declares no ACP mode vocabulary. Add the provider's mode ids to its AcpProviderProfile modeVocabulary before setting a mode.`);if(!r.known.includes(e))throw new Z(`provider "${t}" has no ACP mode "${e}" (known: ${r.known.join(", ")}).`);if(!r.selectable.includes(e))throw new Z(`provider "${t}" ACP mode "${e}" is not selectable by lmctl (selectable: ${r.selectable.join(", ")}).`)}function fw(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} ACP process exited with code ${t.exitCode} before completing the prompt.
|
|
1649
1649
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1650
1650
|
${e}
|
|
1651
1651
|
|
|
1652
|
-
${r}`:r}function
|
|
1653
|
-
`),N({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let u=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=vt(u),s.setSessionId(o),{sessionId:o,sessionResponse:u}}if(i){let c=vt(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=vt(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=vt(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function wm(t,e){let r=fn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{gm(e.tool,e.acpMode)}catch(n){return Promise.reject(n)}return new Promise((n,s)=>{let i=e.permissionMode??"yolo",o=[],a={permissionMode:i,...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.acpMode!==void 0?{acpMode:e.acpMode}:{},purpose:"chat",warnings:{push:S=>{o.push(S)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=Em(r,e,a))}catch(S){return s(S instanceof Error?S:new Error(String(S)))}let d=hm(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),h=!1,_=!1,T=0,p=!1,f=!1;if(e.signal){if(e.signal.aborted)return h=!0,N({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ee(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{h=!0,N({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),ee(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let y=e.sessionId||"",g=Ds({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});g.setSessionId(y);let E=on(d,{provider:e.tool,onEvent:S=>{T=Date.now(),_m(S)&&(f=!0),e.onEvent?.(S)},onNotification:S=>{T=Date.now(),g.processMessage(S)}}),{sendRpc:v,sendNotification:w}=E,b="";d.stderr?.on("data",S=>{b+=S.toString()}),d.on("error",S=>{E.close(S),N({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-m}),s(new Z(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${S.message}`,{cause:S}))}),d.on("exit",S=>{if(_=!0,E.close(new Z(`ACP process exited with code ${String(S)}`)),h)return;let I=g.finalize();if(I!==null)r.onExitFinalization?.({...a,sessionId:I.sessionId,result:I.result,stopReason:I.stopReason,exitCode:S}),n({result:I.result,sessionId:I.sessionId,durationMs:Date.now()-m,stopReason:I.stopReason,exitCode:S,sawActivity:I.sawActivity,...o.length>0?{warnings:o}:{}});else{let x=QT(e.tool,b);N({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:x.slice(0,500),elapsed_ms:Date.now()-m}),s(new Error(zT({tool:e.tool,exitCode:S,stderr:x})))}}),(async()=>{try{let S=await Tm({sendRpc:v,sendNotification:w,opts:e,outputProcessor:g});y=S.sessionId;let I=S.sessionResponse;await ym(r,a,{sessionId:y,response:I},v),g.beginTurn(),p=!0,ce(`acp: prompt sent (${t.length} chars)`);let x=await v("session/prompt",{sessionId:y,prompt:[{type:"text",text:t}]}),R=g.completeTurn(x);p=!1,ce(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),wt(e.holdOpen,{isAborted:()=>h,hasChildExited:()=>_,isTurnInFlight:()=>p,lastEventAtMs:()=>T,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>f})}catch(S){ee(d).catch(()=>{}),s(S instanceof Error?S:new Error(String(S)))}})()})}async function Sm(t){let e=fn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&gm(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}=Em(e,t,i),c=hm(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m=t.sessionId||"",h=null,_="";c.stderr?.on("data",S=>{_+=S.toString()});let T,p,f=Ds({tool:t.tool,onDelta:S=>T?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});f.setSessionId(m);let y=on(c,{provider:t.tool,onEvent:S=>{d.lastEventAtMs=Date.now(),_m(S)&&(d.backgroundJobLaunched=!0),p?.(S)},onNotification:S=>{d.lastEventAtMs=Date.now(),f.processMessage(S)}}),g=()=>new Error(`ACP bundle process (${t.tool}) exited${d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`),E=[],v=()=>d.exited?Promise.resolve():new Promise(S=>{E.push(S)}),w=null;c.on("error",S=>{h=new Z(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),N({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-u}),y.close(S)}),c.on("exit",S=>{if(d.exited=!0,d.exitCode=S,y.close(new Z(`ACP process exited with code ${String(S)}`)),!d.telemetryFired){d.telemetryFired=!0;let I=f.finalize();I!==null&&e.onExitFinalization?.({...i,sessionId:I.sessionId,result:I.result,stopReason:I.stopReason,exitCode:S})}if(w!==null){let I=w;w=null,I(g())}for(let I of E.splice(0))I()});try{let S=await Tm({sendRpc:y.sendRpc,sendNotification:y.sendNotification,opts:t,outputProcessor:f,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async I=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:I,cwd:t.cwd,env:l})});m=S.sessionId,await ym(e,i,{sessionId:S.sessionId,response:S.sessionResponse},y.sendRpc)}catch(S){let I=h??(S instanceof Error?S:new Error(String(S)));throw ee(c).catch(()=>{}),I}let b=S=>new Promise(I=>{setTimeout(I,S).unref?.()});return{tool:t.tool,get sessionId(){return m},get completedTurns(){return d.completedTurns},async sendTurn(S,I={}){if(d.closed||d.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(d.exited)throw g();if(d.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(I.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:m,cwd:t.cwd,env:l}),d.exited)throw g();if(I.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,T=I.onDelta,p=I.onEvent;let x=Date.now();try{f.beginTurn(),ce(`acp: bundle prompt sent (${S.length} chars)`);let R=await new Promise((C,q)=>{w=q;let V=()=>{f.cancelTurn(),y.sendNotification("session/cancel",{sessionId:m}),q(new Error("Aborted"))},ue=I.signal;ue?.addEventListener("abort",V,{once:!0}),y.sendRpc("session/prompt",{sessionId:m,prompt:[{type:"text",text:S}]}).then(le=>{ue?.removeEventListener("abort",V),C(le)},le=>{ue?.removeEventListener("abort",V),q(le instanceof Error?le:new Error(String(le)))})});w=null;let P=f.completeTurn(R);d.turnInFlight=!1,d.completedTurns+=1,ce(`acp: bundle result received (${P.result.length} chars, stopReason=${P.stopReason})`);let k=s&&n.length>0?[...n]:void 0;return s=!1,{result:P.result,sessionId:P.sessionId,stopReason:P.stopReason,durationMs:Date.now()-x,sawActivity:P.sawActivity,...k!==void 0?{warnings:k}:{}}}catch(R){throw w=null,f.cancelTurn(),d.turnInFlight=!1,d.exited?g():R}finally{T=void 0,p=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(t.holdOpen!==void 0?await new Promise(I=>{wt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),I()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let S=t.closeTimeoutMs??2e3;await Promise.race([v(),b(S)]),d.exited||await ee(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),d.closing}}}var Xo=A(()=>{"use strict";z();Ut();nn();bs();it();z();Je();sn();Lo();pm();Wo();jo();sn()});function re(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function Im(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=ZT){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 ew(){let t=new Map;return(e,r)=>{tw(e,Im(t,r))}}function tw(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(re(a,60));let u=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:u});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(re(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:re(a),raw:i})}else if(o==="tool_use"){let a=i.name||"tool",l=typeof i.id=="string"?i.id:void 0,c=i.input,u="";c&&(typeof c.command=="string"?u=c.command:typeof c.file_path=="string"?u=c.file_path:typeof c.path=="string"?u=c.path:typeof c.pattern=="string"?u=c.pattern:typeof c.url=="string"?u=c.url:u=re(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:re(u),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:re(a),raw:i})}else if(o==="tool_result"){let l=i.is_error===!0?"error":"ok",c=typeof i.tool_use_id=="string"?i.tool_use_id:void 0,u,d=i.content;if(typeof d=="string")u=`${d.split(`
|
|
1652
|
+
${r}`:r}function pw(t,e){return pn(t)?.filterExpectedStderr?.(e)??e}function Tm(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 wm(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&&ce(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(N({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 Sm(t,e,r){let n=de(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(fe(e.tool,i,o),e.cwd&&!mw(e.cwd))throw N({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new Z(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:n}}async function vm(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
|
|
1653
|
+
`),N({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let u=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=vt(u),s.setSessionId(o),{sessionId:o,sessionResponse:u}}if(i){let c=vt(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=vt(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=vt(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function bm(t,e){let r=pn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{Em(e.tool,e.acpMode)}catch(n){return Promise.reject(n)}return new Promise((n,s)=>{let i=e.permissionMode??"yolo",o=[],a={permissionMode:i,...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.acpMode!==void 0?{acpMode:e.acpMode}:{},purpose:"chat",warnings:{push:S=>{o.push(S)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=Sm(r,e,a))}catch(S){return s(S instanceof Error?S:new Error(String(S)))}let d=ym(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),h=!1,_=!1,T=0,p=!1,f=!1;if(e.signal){if(e.signal.aborted)return h=!0,N({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ee(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{h=!0,N({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),ee(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let y=e.sessionId||"",g=Ms({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});g.setSessionId(y);let E=an(d,{provider:e.tool,onEvent:S=>{T=Date.now(),Tm(S)&&(f=!0),e.onEvent?.(S)},onNotification:S=>{T=Date.now(),g.processMessage(S)}}),{sendRpc:v,sendNotification:w}=E,b="";d.stderr?.on("data",S=>{b+=S.toString()}),d.on("error",S=>{E.close(S),N({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-m}),s(new Z(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${S.message}`,{cause:S}))}),d.on("exit",S=>{if(_=!0,E.close(new Z(`ACP process exited with code ${String(S)}`)),h)return;let I=g.finalize();if(I!==null)r.onExitFinalization?.({...a,sessionId:I.sessionId,result:I.result,stopReason:I.stopReason,exitCode:S}),n({result:I.result,sessionId:I.sessionId,durationMs:Date.now()-m,stopReason:I.stopReason,exitCode:S,sawActivity:I.sawActivity,...o.length>0?{warnings:o}:{}});else{let x=pw(e.tool,b);N({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:x.slice(0,500),elapsed_ms:Date.now()-m}),s(new Error(fw({tool:e.tool,exitCode:S,stderr:x})))}}),(async()=>{try{let S=await vm({sendRpc:v,sendNotification:w,opts:e,outputProcessor:g});y=S.sessionId;let I=S.sessionResponse;await wm(r,a,{sessionId:y,response:I},v),g.beginTurn(),p=!0,ce(`acp: prompt sent (${t.length} chars)`);let x=await v("session/prompt",{sessionId:y,prompt:[{type:"text",text:t}]}),R=g.completeTurn(x);p=!1,ce(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),wt(e.holdOpen,{isAborted:()=>h,hasChildExited:()=>_,isTurnInFlight:()=>p,lastEventAtMs:()=>T,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>f})}catch(S){ee(d).catch(()=>{}),s(S instanceof Error?S:new Error(String(S)))}})()})}async function Im(t){let e=pn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&Em(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}=Sm(e,t,i),c=ym(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m=t.sessionId||"",h=null,_="";c.stderr?.on("data",S=>{_+=S.toString()});let T,p,f=Ms({tool:t.tool,onDelta:S=>T?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});f.setSessionId(m);let y=an(c,{provider:t.tool,onEvent:S=>{d.lastEventAtMs=Date.now(),Tm(S)&&(d.backgroundJobLaunched=!0),p?.(S)},onNotification:S=>{d.lastEventAtMs=Date.now(),f.processMessage(S)}}),g=()=>new Error(`ACP bundle process (${t.tool}) exited${d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`),E=[],v=()=>d.exited?Promise.resolve():new Promise(S=>{E.push(S)}),w=null;c.on("error",S=>{h=new Z(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),N({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-u}),y.close(S)}),c.on("exit",S=>{if(d.exited=!0,d.exitCode=S,y.close(new Z(`ACP process exited with code ${String(S)}`)),!d.telemetryFired){d.telemetryFired=!0;let I=f.finalize();I!==null&&e.onExitFinalization?.({...i,sessionId:I.sessionId,result:I.result,stopReason:I.stopReason,exitCode:S})}if(w!==null){let I=w;w=null,I(g())}for(let I of E.splice(0))I()});try{let S=await vm({sendRpc:y.sendRpc,sendNotification:y.sendNotification,opts:t,outputProcessor:f,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async I=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:I,cwd:t.cwd,env:l})});m=S.sessionId,await wm(e,i,{sessionId:S.sessionId,response:S.sessionResponse},y.sendRpc)}catch(S){let I=h??(S instanceof Error?S:new Error(String(S)));throw ee(c).catch(()=>{}),I}let b=S=>new Promise(I=>{setTimeout(I,S).unref?.()});return{tool:t.tool,get sessionId(){return m},get completedTurns(){return d.completedTurns},async sendTurn(S,I={}){if(d.closed||d.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(d.exited)throw g();if(d.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(I.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:m,cwd:t.cwd,env:l}),d.exited)throw g();if(I.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,T=I.onDelta,p=I.onEvent;let x=Date.now();try{f.beginTurn(),ce(`acp: bundle prompt sent (${S.length} chars)`);let R=await new Promise((C,q)=>{w=q;let K=()=>{f.cancelTurn(),y.sendNotification("session/cancel",{sessionId:m}),q(new Error("Aborted"))},ue=I.signal;ue?.addEventListener("abort",K,{once:!0}),y.sendRpc("session/prompt",{sessionId:m,prompt:[{type:"text",text:S}]}).then(le=>{ue?.removeEventListener("abort",K),C(le)},le=>{ue?.removeEventListener("abort",K),q(le instanceof Error?le:new Error(String(le)))})});w=null;let P=f.completeTurn(R);d.turnInFlight=!1,d.completedTurns+=1,ce(`acp: bundle result received (${P.result.length} chars, stopReason=${P.stopReason})`);let k=s&&n.length>0?[...n]:void 0;return s=!1,{result:P.result,sessionId:P.sessionId,stopReason:P.stopReason,durationMs:Date.now()-x,sawActivity:P.sawActivity,...k!==void 0?{warnings:k}:{}}}catch(R){throw w=null,f.cancelTurn(),d.turnInFlight=!1,d.exited?g():R}finally{T=void 0,p=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(t.holdOpen!==void 0?await new Promise(I=>{wt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),I()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let S=t.closeTimeoutMs??2e3;await Promise.race([v(),b(S)]),d.exited||await ee(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),d.closing}}}var Go=A(()=>{"use strict";z();jt();sn();Is();it();z();Je();on();Oo();_m();qo();Bo();on()});function re(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function km(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=hw){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 gw(){let t=new Map;return(e,r)=>{_w(e,km(t,r))}}function _w(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(re(a,60));let u=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:u});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(re(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:re(a),raw:i})}else if(o==="tool_use"){let a=i.name||"tool",l=typeof i.id=="string"?i.id:void 0,c=i.input,u="";c&&(typeof c.command=="string"?u=c.command:typeof c.file_path=="string"?u=c.file_path:typeof c.path=="string"?u=c.path:typeof c.pattern=="string"?u=c.pattern:typeof c.url=="string"?u=c.url:u=re(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:re(u),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:re(a),raw:i})}else if(o==="tool_result"){let l=i.is_error===!0?"error":"ok",c=typeof i.tool_use_id=="string"?i.tool_use_id:void 0,u,d=i.content;if(typeof d=="string")u=`${d.split(`
|
|
1654
1654
|
`).length} lines, ${d.length} chars`;else if(Array.isArray(d)){let m=d.map(h=>typeof h=="object"&&h&&"text"in h?h.text:"").filter(Boolean).join("");m&&(u=`${m.split(`
|
|
1655
|
-
`).length} lines, ${m.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function
|
|
1655
|
+
`).length} lines, ${m.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function Us(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?gw():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 Pu(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 js(t){let e=t.binary==="qwen"?"qwen":"claude",r=await $u({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 yw(){let t=new Map;return(e,r)=>{Ew(e,km(t,r))}}function Ew(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:re(a)});return}if(i==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:re(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=re(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:re(l),id:a});return}if(i==="tool_call_update"){let o=s.status||"",a=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(o==="completed"||o==="failed")e({kind:"tool_result",summary:o,status:o==="failed"?"error":"ok",id:a});else if(o==="in_progress"){let l=s.content,c=typeof l=="string"?l:typeof l?.text=="string"?l.text:"",u=c?`running\u2026 ${re(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:i})}}function xm(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function Ke(t,e){let r=e.acpTool||e.binary,n=e.onProgress?yw():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,...xm(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";_e({event:"model_ignored",provider:r,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await bm(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,...xm(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function Ve(t){let e=t.acpTool||t.binary,r=await Im({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 Am(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: ${re(o,120)}`}:{kind:"other",summary:`codex error: ${re(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:re(c||"(command)"),id:a});else{let u=s.exitCode,d=s.status||"",m=typeof s.durationMs=="number"?s.durationMs:void 0,h=typeof u=="number"?`exit ${u}`:d||"done",_=[];typeof u=="number"?_.push(`exit ${u}`):d&&_.push(d),typeof m=="number"&&_.push(`${Math.round(m/1e3)}s`),e({kind:"tool_result",summary:_.join(", ")||"done",status:h,elapsedMs:m,id:a})}return}case"fileChange":{let a=typeof s.id=="string"?s.id:void 0;if(o){let l=s.changes,c=Array.isArray(l)?l.map(u=>u.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:re(c||"(edit)"),id:a})}else{let l=s.status||"done";e({kind:"tool_result",summary:l,status:l,id:a})}return}case"mcpToolCall":{let a=typeof s.id=="string"?s.id:void 0,l=s.server||"mcp",c=s.tool||"tool";if(o)e({kind:"tool_use",tool:`${l}/${c}`,summary:"",id:a});else{let u=s.status||"done";e({kind:"tool_result",summary:u,status:u,id:a})}return}case"webSearch":{let a=typeof s.id=="string"?s.id:void 0;e(o?{kind:"tool_use",tool:"WebSearch",summary:re(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:re(s)}:{kind:"text",summary:re(s)})}return}if(r==="item/reasoning/summaryTextDelta"||r==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:re(s)});return}if(r==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let i=s.split(`
|
|
1656
1656
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${re(o,60)}`:re(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(`
|
|
1657
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${re(o,60)}`:re(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
|
|
1658
|
-
`);try{return JSON.stringify(t)}catch{return String(t)}}function
|
|
1659
|
-
`);S.includes("user.text")&&I&&(!b.id||!p.has(b.id))&&(y(I,"metadata"),b.id&&p.add(b.id))}for(let I of b.content)if(I.type==="input_text"&&typeof I.text=="string"&&I.text){let x=I.text.trim();c||(c=$(x,80)),u=$(x,80),
|
|
1660
|
-
`);S.trim()&&
|
|
1661
|
-
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:
|
|
1662
|
-
`).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 u=c;if(typeof u.id=="string"){let d=o.get(u.id);d?
|
|
1657
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${re(o,60)}`:re(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 Nm(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=>Am(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await qu(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=>Am(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function Rm(t){let e=await Gu({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 hw,ot=A(()=>{"use strict";No();No();Ju();Go();z();hw=256});import{join as Lm}from"node:path";function Ko(t){return new Jo(t)}var Jo,Vo=A(()=>{"use strict";_u();ke();me();ot();we();Jo=class extends Q{claudeDir;constructor(e){super({provider:new Es(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",X,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:Us}),this.claudeDir=e?.claudeDir??Lm(H,".claude")}openSession(e){return js({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[Lm(this.claudeDir,"projects")]})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Tw,stat as Cm,unlink as ww}from"node:fs/promises";import{join as hn,basename as Sw}from"node:path";function vw(t,e,r){return`${t}|${e.toISOString()}|${r}`}function gn(t,e,r){let n=vw(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function Om(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function bw(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 vr(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 vr(r)}).filter(r=>r.length>0).join(`
|
|
1658
|
+
`);try{return JSON.stringify(t)}catch{return String(t)}}function Iw(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 xw(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 Dm(t){let e=0,r=0,n=0,s=0,i=0,o,a,l;for await(let c of ne(t)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let u=c.payload.message||c.payload.text;u&&(l=$(u.trim(),80))}if(c.type==="response_item"&&c.payload){let u=c.payload;if(u.type==="message"&&u.role==="user"&&u.content)for(let d of u.content)d.type==="input_text"&&typeof d.text=="string"&&d.text&&(e++,l=$(d.text.trim(),80));else if(u.type==="message"&&u.role==="assistant"&&u.content)for(let d of u.content)d.type==="output_text"&&typeof d.text=="string"&&d.text&&e++}if(c.payload&&typeof c.payload.model_context_window=="number"&&(a=c.payload.model_context_window),c.type==="event_msg"&&c.payload?.type==="token_count"&&c.payload.info?.total_token_usage){let u=c.payload.info.total_token_usage;r=u.input_tokens??r,n=u.cached_input_tokens??u.cache_read_input_tokens??n,s=u.output_tokens??s,i=u.reasoning_output_tokens??i;let d=bw(c.payload.info.last_token_usage);d&&(o=d),typeof c.payload.info.model_context_window=="number"&&(a=c.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:r,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:a,lastUserMessage:l}}var Hs,Mm=A(()=>{"use strict";me();Hs=class{name="codex";codexDirs;constructor(e={}){let r=[hn(H,".codex"),hn(H,".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:hn(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=hn(r,"sessions");try{await Cm(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 Tw(e)}catch{return r}for(let s of n){let i=hn(e,s),o=await Cm(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=Sw(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 Ae(e,30),n=await se(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,u,d,m;for(let _ of r){if(_.type==="session_meta"&&_.payload&&(_.payload.id&&(s=_.payload.id),_.payload.cwd&&(i=_.payload.cwd),_.payload.cli_version&&(o=_.payload.cli_version),_.payload.timestamp&&(l=new Date(_.payload.timestamp)),_.payload.originator&&(d=_.payload.originator),_.payload.source&&(m=_.payload.source)),_.type==="turn_context"&&_.payload&&(_.payload.model&&(a=_.payload.model),!i&&_.payload.cwd&&(i=_.payload.cwd)),_.type==="event_msg"&&_.payload?.type==="user_message"){let T=_.payload.message||_.payload.text;T&&(c||(c=$(T.trim(),80)),u=$(T.trim(),80))}if(_.type==="response_item"&&_.payload?.type==="message"&&_.payload.role==="user"&&_.payload.content){let T=_.payload.content.find(p=>p.type==="input_text"&&typeof p.text=="string"&&p.text);typeof T?.text=="string"&&(c||(c=$(T.text.trim(),80)),u=$(T.text.trim(),80))}}if(!i)return null;let h=await Dm(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:Om(d,m),firstUserMessage:c,lastUserMessage:h.lastUserMessage??u,messageCount:h.messageCount,filePath:e,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:h.lastTokenUsage,modelContextWindow:h.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await se(r),s=[],i="",o,a,l,c,u,d=e,m,h,_=new Set,T=[],p=new Set,f=[],y=(v,w)=>{let b=f.find(S=>!S.mirrored&&S.source!==w&&S.text===v);b?b.mirrored=!0:f.push({text:v,source:w,mirrored:!1})},g=()=>{T.push(...f.map(v=>v.text)),f=[]};for await(let v of ne(r)){let w=v.timestamp?new Date(v.timestamp):new Date;if(v.type==="session_meta"&&v.payload){v.payload.id&&(d=v.payload.id),v.payload.cwd&&(i=v.payload.cwd),v.payload.cli_version&&(o=v.payload.cli_version),v.payload.timestamp&&(l=new Date(v.payload.timestamp)),m=Om(v.payload.originator,v.payload.source);continue}if(v.type==="turn_context"&&v.payload){v.payload.model&&(a=v.payload.model),!i&&v.payload.cwd&&(i=v.payload.cwd);continue}if(v.type==="response_item"&&v.payload){let b=v.payload;if(b.type==="message"){if(b.role==="user"&&b.content){let S=b.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(S)){let I=b.content.filter((x,R)=>S[R]==="user.text"&&typeof x.text=="string").map(x=>x.text).join(`
|
|
1659
|
+
`);S.includes("user.text")&&I&&(!b.id||!p.has(b.id))&&(y(I,"metadata"),b.id&&p.add(b.id))}for(let I of b.content)if(I.type==="input_text"&&typeof I.text=="string"&&I.text){let x=I.text.trim();c||(c=$(x,80)),u=$(x,80),gn(s,_,{role:"user",timestamp:w,content:Y(x)})}continue}if(b.role==="assistant"&&b.content){for(let S of b.content)S.type==="output_text"&&typeof S.text=="string"&&S.text&&gn(s,_,{role:"assistant",timestamp:w,content:Y(S.text),model:a});continue}if(b.role!=="user"&&b.role!=="assistant"&&b.content){for(let S of b.content)(S.type==="input_text"||S.type==="output_text")&&typeof S.text=="string"&&S.text&&gn(s,_,{role:"system",timestamp:w,content:Y(S.text.trim())});continue}}if(b.type==="function_call"){s.push({role:"tool_use",timestamp:w,content:b.name||"unknown tool",toolName:b.name,toolInput:b.arguments!==void 0?Y(vr(b.arguments)):void 0,toolInputData:Iw(b.arguments),toolCallId:b.call_id});continue}if(b.type==="function_call_output"){s.push({role:"tool_result",timestamp:w,content:Y(vr(b.output)),toolCallId:b.call_id});continue}if(b.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:w,content:b.name||"unknown tool",toolName:b.name,toolInput:b.input!==void 0?Y(vr(b.input)):void 0,toolInputData:xw(b.name,b.input),toolCallId:b.call_id});continue}if(b.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:w,content:Y(vr(b.output)),toolCallId:b.call_id});continue}if(b.type==="reasoning"&&b.summary){let S=b.summary.map(I=>vr(I.text)).join(`
|
|
1660
|
+
`);S.trim()&&gn(s,_,{role:"thinking",timestamp:w,content:Y(S)});continue}}if(v.type==="event_msg"&&v.payload&&(v.payload.type==="task_started"?(g(),h="in_progress"):v.payload.type==="task_complete"?h="complete":v.payload.type==="turn_aborted"&&(h="aborted"),v.payload.type==="user_message"&&typeof v.payload.message=="string"&&y(v.payload.message,"event"),v.payload.type==="agent_reasoning")){let b=v.payload.message||v.payload.text;b&&gn(s,_,{role:"thinking",timestamp:w,content:Y(b)})}}if(!i)return null;g();let E=await Dm(r);return{provider:"codex",sessionId:d,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:m,turnStatus:h,firstUserMessage:c,lastUserMessage:u,messageCount:E.messageCount,filePath:r,totalInputTokens:E.totalInputTokens||void 0,totalCachedInputTokens:E.totalCachedInputTokens||void 0,totalOutputTokens:E.totalOutputTokens||void 0,totalReasoningOutputTokens:E.totalReasoningOutputTokens||void 0,lastInputTokens:E.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:E.lastTokenUsage,modelContextWindow:E.modelContextWindow,messages:s,userPrompts:T}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await ww(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 Ae(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 Qo(t){return new zo(t)}var Yo,zo,Zo=A(()=>{"use strict";Mm();ke();ot();we();Yo="gpt-5.6-sol",zo=class extends Q{constructor(e){super({provider:new Hs(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:`${X}
|
|
1661
|
+
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Nm})}openSession(e){return Rm({...e,model:e.model??Yo})}seedArgsFor(e){let r=super.seedArgsFor(e),n=e?.model??Yo;return[...r.slice(0,-1),"--model",n,r[r.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Yo}}}});function _n(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 Bs(t){let e=_n(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(`
|
|
1662
|
+
`).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 u=c;if(typeof u.id=="string"){let d=o.get(u.id);d?Aw(d,u):(i.push(u),o.set(u.id,u))}else i.push(u)}}return{sessionId:typeof s.sessionId=="string"?s.sessionId:void 0,projectHash:typeof s.projectHash=="string"?s.projectHash:void 0,startTime:typeof s.startTime=="string"?s.startTime:void 0,lastUpdated:typeof s.lastUpdated=="string"?s.lastUpdated:void 0,kind:typeof s.kind=="string"?s.kind:void 0,messages:i}}function Aw(t,e){for(let[r,n]of Object.entries(e))if(n!==void 0){if(r==="tokens"&&Fm(t.tokens)&&Fm(n)){t.tokens={...t.tokens,...n};continue}t[r]=n}}function Fm(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Pm(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(`
|
|
1663
1663
|
`)+`
|
|
1664
|
-
`}var
|
|
1665
|
-
`).trim();b&&i.push({role:"thinking",timestamp:
|
|
1666
|
-
`)}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:
|
|
1667
|
-
`)){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
|
|
1668
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${n.toolCallId}`;r.set(u,d),n.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function
|
|
1669
|
-
`).trim():""}function
|
|
1670
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return
|
|
1664
|
+
`}var ea=A(()=>{"use strict"});import{createHash as kw}from"node:crypto";import{readdir as yn,readFile as $m,stat as Ws,unlink as Nw}from"node:fs/promises";import{join as Ne,basename as Rw,dirname as Lw}from"node:path";import{cwd as Cw}from"node:process";function ta(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function Um(t){return t==="user"}function ra(t){return t==="gemini"||t==="assistant"}function Bt(t,e=new Date(0)){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Ow(t){return`${t.sessionId}\0${t.cwd}`}function Dw(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 Xs(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function jm(t){let e=0,r=0,n=0,s=0,i=0,o;for(let a of t){if(!ra(a.type)||!a.tokens)continue;let l=Xs(a.tokens.input),c=Xs(a.tokens.cached),u=Math.max(l-c,0),d=Xs(a.tokens.output),m=Xs(a.tokens.thoughts);e+=l,r+=c,n+=d,s+=m,i=l,o={inputTokens:u,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:d,reasoningOutputTokens:m,totalTokens:l+d+m}}return{totalInputTokens:e,totalCachedInputTokens:r,totalOutputTokens:n,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function Mw(t){return kw("sha256").update(t).digest("hex")}function En(t,e){let r=e;for(;r&&!t.has(r);){t.add(r);let n=Lw(r);if(n===r)break;r=n}}var qs,Hm=A(()=>{"use strict";me();ea();z();qs=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let r=e.geminiDir||Ne(H,".gemini");this.geminiProjectsFile=Ne(r,"projects.json"),this.geminiTmpDir=Ne(r,"tmp");let n=e.claudeDir||Ne(H,".claude");this.claudeProjectsDir=Ne(n,"projects");let s=[Ne(H,".codex"),Ne(H,".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=>Ne(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=Ow(s),o=r.get(i);r.set(i,o?Dw(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||"",u=await this.resolveWorkspace(c),d,m,h;for(let f of a){let y=Bt(f.timestamp),g=f.type,E=Y(ta(f.content));if(Um(g)){let w=ta(f.content);w&&o.push(w);let b=E.trim();b&&(d||(d=$(b,80)),m=$(b,80)),i.push({role:"user",timestamp:y,content:b||E});continue}if(ra(g)){f.model&&(h=f.model);for(let w of f.thoughts||[]){let b=[w.subject,w.description].filter(Boolean).join(`
|
|
1665
|
+
`).trim();b&&i.push({role:"thinking",timestamp:Bt(w.timestamp,y),content:Y(b)})}i.push({role:"assistant",timestamp:y,content:E,model:f.model});continue}let v=g?`[${g}] `:"";i.push({role:"system",timestamp:y,content:`${v}${E}`.trim()})}let _=Bt(n.startTime,s.createdAt),T=Bt(n.lastUpdated,s.modifiedAt),p=jm(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:_,modifiedAt:T,model:h,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:r,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCachedInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,totalReasoningOutputTokens:p.totalReasoningOutputTokens||void 0,lastInputTokens:p.lastInputTokens||void 0,lastTokenUsage:p.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,u,d=0;for(let h of s)if(Um(h.type)){d++;let _=ta(h.content).trim();_&&(l||(l=$(Y(_),80)),c=$(Y(_),80))}else ra(h.type)&&(d++,h.model&&(u=h.model));let m=jm(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Bt(r.startTime,n.createdAt),modifiedAt:Bt(r.lastUpdated,n.modifiedAt),model:u,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async readSessionFile(e){let r=await $m(e,"utf-8");if(_n(r)==="unknown")return N({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 Bs(r)}catch{return null}}extractSessionIdFromFilename(e){let r=Rw(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 yn(this.geminiTmpDir)}catch{return e}for(let n of r){let s=Ne(this.geminiTmpDir,n,"chats");if(!(await Ws(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await yn(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(Ne(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await Nw(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 u=await se(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:Bt(i?.lastUpdated,u.modifiedAt)})}return n.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),n[0]?.filePath??null}async resolveWorkspace(e){return e?(await this.getWorkspaceHashMap()).get(e)||`[hash:${e.slice(0,16)}]`:"(unknown workspace)"}async getWorkspaceHashMap(){if(this.workspaceHashMap)return this.workspaceHashMap;let e=new Set;En(e,Cw());for(let n of this.extraWorkspacePaths)En(e,n);for(let n of await this.collectGeminiProjectPaths())En(e,n);for(let n of await this.collectCodexCwds())En(e,n);for(let n of await this.collectClaudeCwds())En(e,n);let r=new Map;for(let n of e)r.set(Mw(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await $m(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 Ae(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await yn(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=Ne(this.claudeProjectsDir,n);if(!(await Ws(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await yn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Ne(s,a),u=(await Ae(l,1).catch(()=>[]))[0]?.cwd;u&&e.add(u)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await Ws(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await yn(e)}catch{return r}for(let i of s){let o=Ne(e,i),a=await Ws(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 Fw,writeFileSync as Pw,mkdirSync as $w}from"node:fs";import{join as Uw,dirname as jw}from"node:path";import{randomUUID as Hw}from"node:crypto";function sa(t){return new na(t)}var na,ia=A(()=>{"use strict";Hm();ke();ot();we();ea();na=class extends Q{geminiDir;constructor(e){super({provider:new qs(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",X,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(r,n)=>Ke(r,{...n,acpTool:"gemini"})}),this.geminiDir=e?.geminiDir}openSession(e){return Ve({...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(`
|
|
1666
|
+
`)}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:ws,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=Fw(n,"utf-8"),i=_n(s),o=Bs(s),a=Hw();o.sessionId=a,o.kind="main";let l=jw(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,m=Uw(l,d);return $w(l,{recursive:!0}),Pw(m,Pm(o,i),"utf-8"),{success:!0,sessionId:a,filePath:m}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}});import{readdir as Bm,readFile as Bw,rm as Ww,stat as br}from"node:fs/promises";import{basename as Xw,join as je}from"node:path";function qw(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 oa(){return{shutdownTotals:null,assistantOutputSum:0}}function Xm(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=qw(e.data?.modelMetrics);r&&(t.shutdownTotals=r)}}function Wm(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 Gw(t){let e={};for(let r of t.split(`
|
|
1667
|
+
`)){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 Wt(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function Jw(t){let e=0,r=oa(),n;for await(let s of ne(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=$(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;Xm(r,s)}return{messageCount:e,tokens:r,lastUserMessage:n}}function Kw(t){let e=Vw(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),u=[l?.content,l?.toolDetailedContent].filter(m=>typeof m=="string").join(`
|
|
1668
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${n.toolCallId}`;r.set(u,d),n.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function Vw(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 Gs,qm=A(()=>{"use strict";me();Gs=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||je(H,".copilot");this.sessionStateDir=je(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Bm(this.sessionStateDir)}catch{return e}for(let n of r){let s=je(this.sessionStateDir,n);if((await br(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=je(r,"events.jsonl"),i=await br(s).catch(()=>null),o=i?s:je(r,"workspace.yaml"),a=await se(i?s:r),l=[],c=[],u=n?.cwd||"(unknown workspace)",d,m,h,_,T,p,f=n?.id||Xw(r)||e,y=oa();if(i)for await(let g of ne(s)){let E=Wt(g.timestamp)||a.modifiedAt;if(Xm(y,g),g.type==="session.start"&&g.data){g.data.sessionId&&(f=g.data.sessionId),g.data.copilotVersion&&(m=g.data.copilotVersion),g.data.startTime&&(p=Wt(g.data.startTime)),g.data.selectedModel&&(d=g.data.selectedModel),g.data.context&&(g.data.context.cwd&&(u=g.data.context.cwd),g.data.context.branch&&(h=g.data.context.branch));continue}if(g.type==="session.model_change"&&g.data?.newModel){d=g.data.newModel;continue}if(g.type==="user.message"&&g.data){let v=g.data.content||"";v&&c.push(v);let w=v.trim();w&&(_||(_=$(w,80)),T=$(w,80)),l.push({role:"user",timestamp:E,content:Y(w||v)});continue}if(g.type==="assistant.message"&&g.data){let v=(g.data.content||"").trim();if(v&&l.push({role:"assistant",timestamp:E,content:Y(v),model:d}),g.data.toolRequests)for(let w of g.data.toolRequests)l.push({role:"tool_use",timestamp:E,content:w.name||"unknown tool",toolName:w.name,toolInput:w.arguments?JSON.stringify(w.arguments,null,2):void 0,toolInputData:De(w.arguments),toolCallId:w.toolCallId});continue}if(g.type==="tool.execution_complete"&&g.data){let v=g.data.result?.content||"",w=g.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:E,content:Y(v),toolDetailedContent:w?Y(w):void 0,toolCallId:g.data.toolCallId});continue}if(g.type==="assistant.reasoning"&&g.data?.content){l.push({role:"thinking",timestamp:E,content:Y(g.data.content)});continue}if(g.type==="session.error"||g.type==="session.warning"||g.type==="session.info"||g.type==="system.message"){let v=g.data?.message||"";v.trim()&&l.push({role:"system",timestamp:E,content:Y(v)});continue}}if(!_){let g=(n?.summary||"").trim();g&&(_=$(g,80))}return Kw(l),{provider:"copilot",sessionId:f,cwd:u,createdAt:p??Wt(n?.created_at)??a.createdAt,modifiedAt:Wt(n?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",gitBranch:h,firstUserMessage:_,lastUserMessage:T,messageCount:l.filter(g=>g.role==="user"||g.role==="assistant").length,filePath:o,...Wm(y),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=je(e,"events.jsonl"),i=await br(s).catch(()=>null),o=i?s:je(e,"workspace.yaml"),a=await se(i?s:e),l=i?await Ae(s,20):[],c=n?.id||r,u=n?.cwd||"(unknown workspace)",d,m,h,_,T;for(let f of l)if(f.type==="session.start"&&f.data&&(f.data.sessionId&&(c=f.data.sessionId),f.data.copilotVersion&&(m=f.data.copilotVersion),f.data.startTime&&(h=Wt(f.data.startTime)),f.data.selectedModel&&(d=f.data.selectedModel),f.data.context?.cwd&&(u=f.data.context.cwd)),f.type==="session.model_change"&&f.data?.newModel&&(d||(d=f.data.newModel)),f.type==="user.message"&&f.data){let y=(f.data.content||"").trim();y&&(_||(_=$(y,80)),T=$(y,80))}if(!_){let f=(n?.summary||"").trim();f&&(_=$(f,80))}let p=i?await Jw(s):{messageCount:0,tokens:oa()};return{provider:"copilot",sessionId:c,cwd:u,createdAt:h??Wt(n?.created_at)??a.createdAt,modifiedAt:Wt(n?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",firstUserMessage:_,lastUserMessage:p.lastUserMessage??T,messageCount:p.messageCount,filePath:o,...Wm(p.tokens)}}async readWorkspaceYaml(e){let r=je(e,"workspace.yaml");try{let n=await Bw(r,"utf-8");return Gw(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await Ww(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await Bm(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=je(this.sessionStateDir,e);if((await br(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=je(this.sessionStateDir,s);(await br(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=je(this.sessionStateDir,s);if(!(await br(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 la(t){return new aa(t)}var aa,ca=A(()=>{"use strict";qm();ke();ot();z();we();aa=class extends Q{copilotDir;constructor(e){super({provider:new Gs(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",X,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>Ke(r,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return Ve({...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 _e({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});function ua(){return new da}var da,ma=A(()=>{"use strict";Ps();ke();ot();we();da=class extends Q{constructor(){super({provider:new Sr,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",X],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>Ke(e,{...r,acpTool:"opencode"})})}openSession(e){return Ve({...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??X),r}}});import{appendFile as Yw,mkdir as zw,readFile as Gm,readdir as Jm,rm as Qw,stat as Km}from"node:fs/promises";import{basename as Zw,dirname as eS,isAbsolute as Vm,join as Xt,relative as tS,resolve as fa}from"node:path";function pa(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function iS(t){return typeof t=="number"?new Date(t):pa(t)??new Date(0)}function Ym(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(`
|
|
1669
|
+
`).trim():""}function zm(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function oS(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:zm(t)??""}function aS(t){let e=lS(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 lS(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 rS,nS,sS,Js,Qm=A(()=>{"use strict";me();rS="1.4",nS="1.5",sS=new Set([rS,nS]),Js=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=fa(e?.kimiHome??process.env.KIMI_CODE_HOME??Xt(H,".kimi-code")),this.sessionsDir=Xt(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 Qw(r.sessionDir,{recursive:!0,force:!0}),await zw(eS(this.indexPath()),{recursive:!0,mode:448}),await Yw(this.indexPath(),`${JSON.stringify({sessionId:r.sessionId,deleted:!0})}
|
|
1670
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return Xt(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 Jm(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=Xt(this.sessionsDir,s.name),o;try{o=await Jm(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=Xt(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Gm(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:fa(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:Xt(r,"state.json"),wirePath:Xt(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!Vm(e)||Zw(e)!==r)return!1;let n=tS(this.sessionsDir,fa(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Vm(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 Gm(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 Km(e.wirePath)}catch{return null}let s=await Km(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=pa(r.createdAt)??s.birthtime,a=pa(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?$(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,u=0,d=0,m=0,h=!1,_=0,T,p;for await(let f of ne(e)){let y=iS(f.time??f.created_at);if(i&&(i=!1,f.type==="metadata"&&!sS.has(f.protocol_version))){let E=`Kimi transcript wire protocol version ${JSON.stringify(f.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:y,content:E}],userPrompts:[],messageCount:1,firstUserMessage:E,lastUserMessage:E}}if((f.type==="config.update"||f.type==="profile.bind")&&f.modelAlias&&(o=f.modelAlias),f.type==="usage.record"){f.model&&(o=f.model),h||=f.usage!==void 0;let E=f.usage?.inputOther??0,v=f.usage?.inputCacheRead??0,w=f.usage?.inputCacheCreation??0,b=f.usage?.output??0;c+=E,u+=v,d+=w,m+=b,f.usageScope==="turn"&&(T=E+v+w,p={inputTokens:E,cachedInputTokens:v,cacheWriteInputTokens:w,outputTokens:b,totalTokens:T+b});continue}if(f.type==="turn.prompt"&&f.origin?.kind==="user"){let E=Ym(f.input);E&&((!f.promptId||!s.has(f.promptId))&&(n.push(E),f.promptId&&s.add(f.promptId)),a??=$(E,80),l=$(E,80),r.push({role:"user",timestamp:y,content:E}),_++);continue}if(f.type==="turn.steer"){let E=Ym(f.input);E&&(r.push({role:"system",timestamp:y,content:E}),_++);continue}if(f.type!=="context.append_loop_event"||!f.event)continue;let g=f.event;g.type==="content.part"&&g.part?.type==="text"&&g.part.text?(r.push({role:"assistant",timestamp:y,content:g.part.text,model:o}),_++):g.type==="content.part"&&g.part?.type==="think"&&g.part.think?r.push({role:"thinking",timestamp:y,content:g.part.think,model:o}):g.type==="tool.call"?r.push({role:"tool_use",timestamp:y,content:g.name??"tool",toolName:g.name,toolInput:zm(g.args),toolInputData:De(g.args),toolCallId:g.toolCallId,model:o}):g.type==="tool.result"&&r.push({role:"tool_result",timestamp:y,content:oS(g.result),toolCallId:g.toolCallId,model:o})}return aS(r),{messages:r,userPrompts:n,messageCount:_,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:h?c:void 0,totalCachedInputTokens:h?u:void 0,totalCacheWriteInputTokens:h?d:void 0,totalOutputTokens:h?m:void 0,lastInputTokens:T,lastTokenUsage:p}}}});function ga(t){return new ha(t)}var ha,_a=A(()=>{"use strict";Qm();ke();ot();we();ha=class extends Q{kimiHome;constructor(e){super({provider:new Js(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",X,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(r,n)=>Ke(r,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return Ve({...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??X,"--output-format","stream-json"),r}}});import{spawn as cS}from"node:child_process";import{mkdirSync as dS}from"node:fs";function Ea(t){return new ya(t)}async function uS(t,e){let r=Date.now(),n=Zm({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});fe("lmplayer",n,e.permissionMode??"yolo");let s=await tf(e.binary,n,{cwd:e.cwd,env:de(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(ef(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-r}}function Zm(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(...Tt("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function ef(t){if(t.error)return t.error;let e=en(t.stderr).trim();return e?e.slice(0,500):`exit code ${t.code}`}function tf(t,e,r){return new Promise((n,s)=>{let i;try{i=cS(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(T){s(T);return}let o="",a="",l="",c,u,d,m=[],h=!1,_=T=>{let p=T.trim();if(!p)return;let f;try{f=JSON.parse(p)}catch{m.push(T),r.onText?.(T);return}if(!Ir(f))return;let y=Ks(f,!1);c===void 0&&y!==void 0&&(c=y),u=Ks(f,!0)??u;let g=mS(f);g!==void 0&&(d=g);let E=rf(f);E&&(m.push(E),r.onText?.(E))};i.stdout?.on("data",T=>{let p=T.toString("utf8");o+=p,l+=p;let f=l.indexOf(`
|
|
1671
1671
|
`);for(;f>=0;){let y=l.slice(0,f);l=l.slice(f+1),_(y),f=l.indexOf(`
|
|
1672
|
-
`)}}),i.stderr?.on("data",T=>{a+=T.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",T=>{h||(h=!0,l.length>0&&_(l),n({code:T,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",T=>{h||(h=!0,s(T))})})}function
|
|
1672
|
+
`)}}),i.stderr?.on("data",T=>{a+=T.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",T=>{h||(h=!0,l.length>0&&_(l),n({code:T,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",T=>{h||(h=!0,s(T))})})}function mS(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(Ir(e)){let r=e.data;if(Ir(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 rf(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(Ir(r)){let n=rf(r);if(n)return n}}}function Ks(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(Ir(r)){let n=Ks(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(Ir(s)){let i=Ks(s,e);if(i!==void 0)return i}}}function Ir(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var ya,Ta=A(()=>{"use strict";Ps();ke();we();it();Je();vo();ya=class extends Q{constructor(e){super({provider:new Sr({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",X],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:uS})}seedArgsFor(e){return Zm({prompt:e?.prompt??X,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){dS(e,{recursive:!0});let n=this.seedArgsFor(r);fe("lmplayer",n);try{let s=await tf(this.binary,n,{cwd:e,env:Tr(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:ef(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 "${X}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as Vs,readFile as fS,rm as pS}from"node:fs/promises";import{basename as nf,join as It}from"node:path";function hS(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Tn(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function gS(t,e){if(!e)return;t.observed=!0;let r=Tn(e.promptTokenCount),n=Tn(e.cachedContentTokenCount),s=Tn(e.candidatesTokenCount),i=Tn(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:Tn(e.totalTokenCount)||r+s}}function _S(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 sf(t){return t.type==="user"||t.message?.role==="user"}function of(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function af(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(`
|
|
1673
1673
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
1674
|
-
`):"":""}function sf(t){return t.model||t.message?.model}function rS(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:af(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Tn(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 nS(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Tn(e.output??e.error??t)}return Tn(t)}function af(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function of(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Tn(t.args,!0),toolInputData:De(t.args),toolCallId:t.id,model:r}}var Ks,lf=A(()=>{"use strict";me();Ks=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||It(H,".qwen")}async discoverSessions(){let e=It(this.baseDir,"projects"),r;try{r=await Vs(e)}catch{return[]}let n=[];for(let s of r){let i=It(e,s,"chats"),o;try{o=await Vs(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=It(i,a);try{let u=await this.extractSummary(c,l);u&&n.push(u)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await se(e),i="(unknown)",o,a,l,c,u=0;for await(let d of ne(e)){if(n=!0,d.cwd&&(i=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(i=d.cwd,d.version&&(a=d.version),d.model&&(o=d.model)),tf(d)){let m=nf(d).trim();m&&(l||(l=$(m,80)),c=$(m,80),u++)}if(rf(d)){let m=sf(d);m&&(o=m),u+=rS(d)}}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:u,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=ef(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await se(e),s="(unknown)",i,o,a,l,c,u,d=[],m=Zw();for await(let h of ne(e)){if(eS(m,h.usageMetadata),h.cwd&&(s=h.cwd,h.version&&(o=h.version),h.gitBranch&&(a=h.gitBranch)),h.type==="system"&&h.cwd&&(s=h.cwd,h.version&&(o=h.version),h.model&&(i=h.model),h.gitBranch&&(a=h.gitBranch)),!h.message)continue;let _=h.message,T=h.timestamp?new Date(h.timestamp):n.modifiedAt;if(h.type==="tool_result"){let p=af(h).filter(f=>f.functionResponse!==void 0);p.length===0&&h.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:T,content:Tn(h.toolCallResult.resultDisplay??h.toolCallResult.error??h.toolCallResult.status)??"tool result",toolCallId:h.toolCallResult.callId});for(let f of p){let y=f.functionResponse,g=nS(y.response),E=Tn(h.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:T,content:E??g??h.toolCallResult?.status??"tool result",toolName:y.name,toolCallId:h.toolCallResult?.callId??y.id,...g!==void 0?{toolDetailedContent:g}:{}})}}else if(tf(h)){let p=nf(h);p.trim()&&(c||(c=$(p.trim(),80)),u=$(p.trim(),80)),d.push({role:"user",timestamp:T,content:p})}else if(rf(h)){let p=sf(h);if(p&&(i=p),Array.isArray(_.content))for(let f of _.content)f.type==="text"&&f.text?d.push({role:"assistant",timestamp:T,content:f.text,model:p}):f.type==="thinking"&&f.thinking?d.push({role:"thinking",timestamp:T,content:f.thinking}):f.functionCall&&d.push(of(f.functionCall,T,p));else if(typeof _.content=="string")d.push({role:"assistant",timestamp:T,content:_.content,model:p});else if(Array.isArray(_.parts))for(let f of _.parts)if(f.thought||f.type==="thinking"){let y=f.thinking||f.text;y&&d.push({role:"thinking",timestamp:T,content:y})}else f.functionCall?d.push(of(f.functionCall,T,p)):f.text&&d.push({role:"assistant",timestamp:T,content:f.text,model:p})}}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:u,messageCount:d.filter(h=>h.role==="user"||h.role==="assistant").length,filePath:e,...tS(m),messages:d}}async resolveSessionPath(e){let r=It(this.baseDir,"projects");try{let n=await Vs(r),s=[];for(let i of n){let o=It(r,i,"chats",`${e}.jsonl`);try{return await zw(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=It(r,i,"chats"),a;try{a=await Vs(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;ef(l,".jsonl").startsWith(e)&&s.push(It(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 Qw(r),!0}catch{return!1}}}});function Ta(){return new Ea}var Ea,wa=A(()=>{"use strict";lf();ke();ot();we();Ea=class extends Q{constructor(){super({provider:new Ks,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",X,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:$s})}openSession(e){return Us({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as cf,readFile as df,rm as uf,stat as mf}from"node:fs/promises";import{basename as Sa,join as Ye}from"node:path";import{fileURLToPath as sS}from"node:url";async function iS(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 oS(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function ff(t){return t.type==="USER_INPUT"}function pf(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function aS(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function hf(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function gf(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 lS(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function cS(t){for await(let e of ne(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=dS(s);if(i)return i}let n=uS(e.content);if(n)return n}return null}function dS(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 uS(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function mS(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 fS(t,e){let r=new Set;for(let n of e){let s=pS(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 pS(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:yS(r.event.content);if(n!==void 0)return _f(t.filter(i=>!e.has(i)&&ES(i)===n),r.event.step_index);let s=_S(r.event);if(s!==void 0)return _f(t.filter(i=>!e.has(i)&&hS(i.name,r.event.type)&&Ef(gS(i))===s),r.event.step_index)}function _f(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 hS(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 gS(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function _S(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]),Ef(e)}function Ef(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return sS(e)}catch{return}}function yS(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function ES(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 yf(t){if(t.endsWith(".db"))return Sa(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Ys,Tf=A(()=>{"use strict";me();Ys=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Ye(H,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Ye(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Ye(this.baseDir,"conversations"),r;try{r=await cf(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=Sa(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Ye(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return Ye(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 mf(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await iS([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,u=0;if(n)for await(let d of ne(n)){let m=gf(d.content);if(m&&(a=m),ff(d)){let h=hf(d.content).trim();h&&(l||(l=$(h,80)),c=$(h,80)),u++}else pf(d)&&d.content&&u++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=yf(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,u=[],d=[];if(i)for await(let m of ne(i)){let h=oS(m.created_at,s.modifiedAt),_=gf(m.content);if(_&&(a=_),ff(m)){let T=hf(m.content),p=T.trim();p&&(l||(l=$(p,80)),c=$(p,80)),o.push({role:"user",timestamp:h,content:T});continue}if(Array.isArray(m.tool_calls))for(let T of m.tool_calls){let p=T.name||"tool",f=lS(T.args),y=De(T.args),g={role:"tool_use",timestamp:h,content:f,toolName:p,toolInput:f,toolInputData:y};o.push(g),u.push({name:p,stepIndex:m.step_index,input:y,message:g})}if(pf(m)&&m.content)o.push({role:"assistant",timestamp:h,content:m.content,model:a});else if(aS(m)&&m.content){let T=mS(m,n),p=T===void 0?null:await this.readTaskLog(n,T),f={role:"tool_result",timestamp:p?.modifiedAt??h,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:T,...p===null?{}:{toolDetailedContent:p.content}};o.push(f),d.push({event:m,message:f})}m.thinking&&o.push({role:"thinking",timestamp:h,content:m.thinking})}return fS(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(m=>m.role==="user"||m.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await mf(r),r}catch{}let n=Ye(this.baseDir,"conversations");try{let s=[];for(let i of await cf(n)){if(!i.endsWith(".db"))continue;Sa(i,".db").startsWith(e)&&s.push(Ye(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=yf(r);return n?(await uf(this.conversationPath(n),{force:!0}),await uf(Ye(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 cS(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Ye(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await df(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=Ye(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([df(n,"utf8"),se(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as TS}from"node:child_process";import{StringDecoder as wf}from"node:string_decoder";function zs(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 wS(t.label,r.binary,s,{cwd:r.cwd,env:de(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 wS(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=TS(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new wf("utf8"),u=new wf("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=u.write(m)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,h)=>{if(n.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let _=h?`signal ${h}`:`exit code ${m}`,T=l.trim()||a.trim();i(new Error(`${t} failed (${_})${T?`: ${T}`:""}`))}),n.signal?.aborted?d():n.signal?.addEventListener("abort",d,{once:!0})})}var va=A(()=>{"use strict";Je()});import{randomUUID as SS}from"node:crypto";function Ia(t){return new ba(t)}function bS(t){return t!==void 0&&t<=0?"0":t===void 0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var ba,vS,xa=A(()=>{"use strict";Tf();ke();we();it();va();ba=class extends Q{constructor(e){super({provider:new Ys(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",X,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:vS})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}async seed(e,r){let n=`[lmctl-seed:${SS()}]`,s=await super.seed(e,{...r,prompt:`${n}
|
|
1675
|
-
${r?.prompt??X}`}),i=(await this.provider.discoverSessions()).filter(o=>o.firstUserMessage?.startsWith(n));if(s.success&&i.length===1)return{...s,sessionId:i[0].sessionId};for(let o of i)await this.provider.deleteSession(o.sessionId);return{...s,success:!1,error:s.error??`agy seed created ${i.length} identifiable sessions; expected one`}}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},
|
|
1676
|
-
`))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=xt(this.sessionsDir,e,r,"session.jsonl.zstd");return
|
|
1677
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function
|
|
1674
|
+
`):"":""}function lf(t){return t.model||t.message?.model}function yS(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:df(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function wn(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 ES(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return wn(e.output??e.error??t)}return wn(t)}function df(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function cf(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:wn(t.args,!0),toolInputData:De(t.args),toolCallId:t.id,model:r}}var Ys,uf=A(()=>{"use strict";me();Ys=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||It(H,".qwen")}async discoverSessions(){let e=It(this.baseDir,"projects"),r;try{r=await Vs(e)}catch{return[]}let n=[];for(let s of r){let i=It(e,s,"chats"),o;try{o=await Vs(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=It(i,a);try{let u=await this.extractSummary(c,l);u&&n.push(u)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await se(e),i="(unknown)",o,a,l,c,u=0;for await(let d of ne(e)){if(n=!0,d.cwd&&(i=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(i=d.cwd,d.version&&(a=d.version),d.model&&(o=d.model)),sf(d)){let m=af(d).trim();m&&(l||(l=$(m,80)),c=$(m,80),u++)}if(of(d)){let m=lf(d);m&&(o=m),u+=yS(d)}}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:u,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=nf(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await se(e),s="(unknown)",i,o,a,l,c,u,d=[],m=hS();for await(let h of ne(e)){if(gS(m,h.usageMetadata),h.cwd&&(s=h.cwd,h.version&&(o=h.version),h.gitBranch&&(a=h.gitBranch)),h.type==="system"&&h.cwd&&(s=h.cwd,h.version&&(o=h.version),h.model&&(i=h.model),h.gitBranch&&(a=h.gitBranch)),!h.message)continue;let _=h.message,T=h.timestamp?new Date(h.timestamp):n.modifiedAt;if(h.type==="tool_result"){let p=df(h).filter(f=>f.functionResponse!==void 0);p.length===0&&h.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:T,content:wn(h.toolCallResult.resultDisplay??h.toolCallResult.error??h.toolCallResult.status)??"tool result",toolCallId:h.toolCallResult.callId});for(let f of p){let y=f.functionResponse,g=ES(y.response),E=wn(h.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:T,content:E??g??h.toolCallResult?.status??"tool result",toolName:y.name,toolCallId:h.toolCallResult?.callId??y.id,...g!==void 0?{toolDetailedContent:g}:{}})}}else if(sf(h)){let p=af(h);p.trim()&&(c||(c=$(p.trim(),80)),u=$(p.trim(),80)),d.push({role:"user",timestamp:T,content:p})}else if(of(h)){let p=lf(h);if(p&&(i=p),Array.isArray(_.content))for(let f of _.content)f.type==="text"&&f.text?d.push({role:"assistant",timestamp:T,content:f.text,model:p}):f.type==="thinking"&&f.thinking?d.push({role:"thinking",timestamp:T,content:f.thinking}):f.functionCall&&d.push(cf(f.functionCall,T,p));else if(typeof _.content=="string")d.push({role:"assistant",timestamp:T,content:_.content,model:p});else if(Array.isArray(_.parts))for(let f of _.parts)if(f.thought||f.type==="thinking"){let y=f.thinking||f.text;y&&d.push({role:"thinking",timestamp:T,content:y})}else f.functionCall?d.push(cf(f.functionCall,T,p)):f.text&&d.push({role:"assistant",timestamp:T,content:f.text,model:p})}}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:u,messageCount:d.filter(h=>h.role==="user"||h.role==="assistant").length,filePath:e,..._S(m),messages:d}}async resolveSessionPath(e){let r=It(this.baseDir,"projects");try{let n=await Vs(r),s=[];for(let i of n){let o=It(r,i,"chats",`${e}.jsonl`);try{return await fS(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=It(r,i,"chats"),a;try{a=await Vs(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;nf(l,".jsonl").startsWith(e)&&s.push(It(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 pS(r),!0}catch{return!1}}}});function Sa(){return new wa}var wa,va=A(()=>{"use strict";uf();ke();ot();we();wa=class extends Q{constructor(){super({provider:new Ys,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",X,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:Us})}openSession(e){return js({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as mf,readFile as ff,rm as pf,stat as hf}from"node:fs/promises";import{basename as ba,join as Ye}from"node:path";import{fileURLToPath as TS}from"node:url";async function wS(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 SS(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function gf(t){return t.type==="USER_INPUT"}function _f(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function vS(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function yf(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function Ef(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 bS(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function IS(t){for await(let e of ne(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=xS(s);if(i)return i}let n=AS(e.content);if(n)return n}return null}function xS(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 AS(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function kS(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 NS(t,e){let r=new Set;for(let n of e){let s=RS(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 RS(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:DS(r.event.content);if(n!==void 0)return Tf(t.filter(i=>!e.has(i)&&MS(i)===n),r.event.step_index);let s=OS(r.event);if(s!==void 0)return Tf(t.filter(i=>!e.has(i)&&LS(i.name,r.event.type)&&Sf(CS(i))===s),r.event.step_index)}function Tf(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 LS(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 CS(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function OS(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]),Sf(e)}function Sf(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return TS(e)}catch{return}}function DS(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function MS(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 wf(t){if(t.endsWith(".db"))return ba(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var zs,vf=A(()=>{"use strict";me();zs=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Ye(H,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Ye(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Ye(this.baseDir,"conversations"),r;try{r=await mf(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=ba(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Ye(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return Ye(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 hf(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await wS([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,u=0;if(n)for await(let d of ne(n)){let m=Ef(d.content);if(m&&(a=m),gf(d)){let h=yf(d.content).trim();h&&(l||(l=$(h,80)),c=$(h,80)),u++}else _f(d)&&d.content&&u++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=wf(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,u=[],d=[];if(i)for await(let m of ne(i)){let h=SS(m.created_at,s.modifiedAt),_=Ef(m.content);if(_&&(a=_),gf(m)){let T=yf(m.content),p=T.trim();p&&(l||(l=$(p,80)),c=$(p,80)),o.push({role:"user",timestamp:h,content:T});continue}if(Array.isArray(m.tool_calls))for(let T of m.tool_calls){let p=T.name||"tool",f=bS(T.args),y=De(T.args),g={role:"tool_use",timestamp:h,content:f,toolName:p,toolInput:f,toolInputData:y};o.push(g),u.push({name:p,stepIndex:m.step_index,input:y,message:g})}if(_f(m)&&m.content)o.push({role:"assistant",timestamp:h,content:m.content,model:a});else if(vS(m)&&m.content){let T=kS(m,n),p=T===void 0?null:await this.readTaskLog(n,T),f={role:"tool_result",timestamp:p?.modifiedAt??h,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:T,...p===null?{}:{toolDetailedContent:p.content}};o.push(f),d.push({event:m,message:f})}m.thinking&&o.push({role:"thinking",timestamp:h,content:m.thinking})}return NS(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(m=>m.role==="user"||m.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await hf(r),r}catch{}let n=Ye(this.baseDir,"conversations");try{let s=[];for(let i of await mf(n)){if(!i.endsWith(".db"))continue;ba(i,".db").startsWith(e)&&s.push(Ye(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=wf(r);return n?(await pf(this.conversationPath(n),{force:!0}),await pf(Ye(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 IS(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Ye(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await ff(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=Ye(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([ff(n,"utf8"),se(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as FS}from"node:child_process";import{StringDecoder as bf}from"node:string_decoder";function Qs(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 PS(t.label,r.binary,s,{cwd:r.cwd,env:de(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 PS(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=FS(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new bf("utf8"),u=new bf("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=u.write(m)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,h)=>{if(n.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let _=h?`signal ${h}`:`exit code ${m}`,T=l.trim()||a.trim();i(new Error(`${t} failed (${_})${T?`: ${T}`:""}`))}),n.signal?.aborted?d():n.signal?.addEventListener("abort",d,{once:!0})})}var Ia=A(()=>{"use strict";Je()});import{randomUUID as $S}from"node:crypto";function Aa(t){return new xa(t)}function jS(t){return t!==void 0&&t<=0?"0":t===void 0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var xa,US,ka=A(()=>{"use strict";vf();ke();we();it();Ia();xa=class extends Q{constructor(e){super({provider:new zs(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",X,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:US})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}async seed(e,r){let n=`[lmctl-seed:${$S()}]`,s=await super.seed(e,{...r,prompt:`${n}
|
|
1675
|
+
${r?.prompt??X}`}),i=(await this.provider.discoverSessions()).filter(o=>o.firstUserMessage?.startsWith(n));if(s.success&&i.length===1)return{...s,sessionId:i[0].sessionId};for(let o of i)await this.provider.deleteSession(o.sessionId);return{...s,success:!1,error:s.error??`agy seed created ${i.length} identifiable sessions; expected one`}}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},US=Qs({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",jS(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>fe("agy",t,e.permissionMode??"yolo")})});import HS from"node:zlib";function YS(t,e){return t[e]===WS&&t[e+1]===XS&&t[e+2]===qS&&t[e+3]===GS}function If(t,e){return(t[e]&240)===80&&t[e+1]===JS&&t[e+2]===KS&&t[e+3]===VS}function zS(t,e){if(If(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!YS(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,u=(c&1)!==0,d=c>>1&3,m=c>>3;if(r+=3,d===3||(r+=d===1?1:m,r>t.length))return;if(u)break}if(o&&(r+=4),!(r>t.length))return r-e}}function QS(t){let e=[],r=0;for(;r+4<=t.length;){let n=zS(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function Zs(t){let e=[];for(let r of QS(t))If(r,0)||e.push(BS(r).toString("utf8"));return e.join("")}var BS,WS,XS,qS,GS,JS,KS,VS,Na=A(()=>{"use strict";BS=HS.zstdDecompressSync,WS=40,XS=181,qS=47,GS=253,JS=42,KS=77,VS=24});import{readdir as Ra,rm as ZS,stat as ev}from"node:fs/promises";import{join as xt}from"node:path";function tv(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function La(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 rv(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 xf(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:La(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of rv(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:La(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:La(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function nv(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 Af(t,e,r){let n=t.find(h=>h.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let h of t)if(h.type==="request/header"){let _=h.data?.header;_?.config?.model&&(a=_.config.model)}let l=t.map(h=>h.time).filter(h=>typeof h=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,m=r.filter(h=>h.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:m[0]?.content,lastUserMessage:m.at(-1)?.content,messageCount:r.filter(h=>h.role==="user"||h.role==="assistant").length,filePath:e,...sv(t)}}function sv(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 u=ei(c.inputTokens),d=ei(c.cacheReadTokens),m=ei(c.outputTokens),h=ei(c.reasoningTokens);r+=u,n+=d,s+=m,i+=h,o=u+d,a={inputTokens:u,cachedInputTokens:d,outputTokens:m,reasoningOutputTokens:h,totalTokens:u+d+m}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function ei(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var ti,kf=A(()=>{"use strict";me();Na();ti=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||xt(H,".dsh");this.sessionsDir=xt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Ra(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Ra(xt(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=xf(n),i=Af(n,r.filePath,s);return i?{...i,turnStatus:nv(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 ZS(xt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return xt(this.sessionsDir,tv(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Ra(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=xt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await ev(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=xt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=Zs(i),a=[];for(let l of o.split(`
|
|
1676
|
+
`))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=xt(this.sessionsDir,e,r,"session.jsonl.zstd");return Af(n,s,xf(n))}}});import{spawn as iv}from"node:child_process";async function ri(t,e=r=>Ca.spawn(r)){if(At){let r=await At.catch(()=>{});if(r?.alive)return r;At=void 0}return At=e(t),At}async function Sn(){if(!At)return;(await At.catch(()=>{}))?.shutdown(),At=void 0}var ov,Nf,xr,Ca,At,Rf=A(()=>{"use strict";ov=/dsh web:\s*(https?:\/\/\S+)/,Nf=2e4,xr=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)}},Ca=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 xr(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 xr(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 xr(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new xr(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=iv("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 ${Nf}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},Nf);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let u=ov.exec(o);u&&(i=!0,clearTimeout(l),r(new t(u[1],s)))}),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("error",c=>{i||(i=!0,clearTimeout(l),n(c))}),s.on("exit",(c,u)=>{if(i)return;i=!0,clearTimeout(l);let d=u?`signal ${u}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${d}): ${a.slice(0,500)}`))})})}}});import{randomUUID as av}from"node:crypto";import{existsSync as Lf}from"node:fs";import{readFile as lv,mkdir as cv}from"node:fs/promises";function Fa(t){return new Ma(t)}function Da(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function uv(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 ni(t){return t instanceof Error?t.message:String(t)}async function mv(t){let e=await Cf(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 Cf(t){let e;try{e=await lv(t)}catch{return[]}let r=Zs(e),n=[];for(let s of r.split(`
|
|
1677
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function fv(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 dv,Oa,Ma,Pa=A(()=>{"use strict";ke();kf();Na();Rf();we();it();dv=500,Oa=8*60*60*1e3;Ma=class extends Q{dshProvider;constructor(e){let r=new ti(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 cv(e,{recursive:!0});let n=`session-${av()}`,s=Da(process.env);fe("dsh",[],"yolo");try{let i;try{i=await ri(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${ni(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${ni(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: ${ni(a)}`}}let o=r?.prompt??X;try{await this.promptAndWait(i,e,n,o,Oa)}catch(a){return{success:!1,error:`seed turn failed: ${ni(a)}`}}return{success:!0,sessionId:n}}finally{await Sn()}}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=Da(r.env??process.env);fe("dsh",[],r.permissionMode??"yolo");let i;try{let o=await ri(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??Oa)}finally{await Sn()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:r.sessionId,durationMs:Date.now()-n}}async openSession(e){let r=Da(e.env??process.env);fe("dsh",[],e.permissionMode??"yolo");let n=await ri(r),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!Lf(s))throw await Sn(),new Error(`dsh bundle: session file does not exist for session "${e.sessionId}" (${s}) \u2014 the session must exist before a bundle can resume it`);e.model&&await n.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let i=e.sessionId,o=this,a=0,l=!1,c=null,u=!1,d=!1,m=async()=>{d||(d=!0,await Sn())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(h,_={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(u)throw new Error("dsh bundle session has a turn still in flight");if(_.signal?.aborted)throw new Error("Aborted");if(!Lf(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);u=!0;let T=Date.now();try{let p=o.promptAndWait(n,e.cwd,i,h,Oa,_.signal);p.catch(()=>{});let f=await Promise.race([p,new Promise((y,g)=>{_.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await m()})().finally(()=>g(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:f,sessionId:i,durationMs:Date.now()-T}}finally{u=!1}},close(){return c!==null||(c=(async()=>{l=!0,await m()})()),c}}}async promptAndWait(e,r,n,s,i,o){let a=this.dshProvider.sessionFilePath(r,n),l=await mv(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=i>0?Date.now()+i:1/0;for(;;){if(o?.aborted)throw new Error("Aborted");let u=await Cf(a),d=u.find(m=>m.type==="turn/end"&&(m.seq??-1)>l);if(d){let m=d.data?.reason,h=[...u].reverse().find(T=>T.type==="assistant/message"),_=h?fv(h):"";if(m?.kind!=="completed"&&!_)throw new Error(uv(m));return _}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(m=>setTimeout(m,dv))}}}});import{existsSync as pv}from"node:fs";import{join as Pf,resolve as hv}from"node:path";import{createRequire as gv}from"node:module";function _v(){return $a===null&&($a=gv(import.meta.url)("node:sqlite").DatabaseSync),$a}function Ua(t={}){return hv(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||Pf(H,".hermes"))}function yv(t={}){return Pf(Ua(t),"state.db")}function vn(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function Ie(t){return typeof t=="string"&&t.length>0?t:void 0}function Ev(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Mf(t){return Ie(t.cwd)??Ie(Ev(t.model_config).cwd)??"(unknown)"}function Tv(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function wv(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 Ff(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 $a,Of,Df,si,$f=A(()=>{"use strict";me();z();$a=null;Of="acp";Df=`id, source, model, model_config, started_at,
|
|
1678
1678
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
1679
|
-
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;
|
|
1679
|
+
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;si=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=yv(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!pv(this.dbPath))return null;let e=null;try{return e=new(_v())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(r){return e?.close(),N({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 ${Df} FROM sessions WHERE id = ? AND source = ?`).get(r,Of)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let r=e.prepare(`SELECT ${Df} FROM sessions
|
|
1680
1680
|
WHERE source = ?
|
|
1681
1681
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
1682
|
-
LIMIT ?`).all(
|
|
1682
|
+
LIMIT ?`).all(Of,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:Ie(s.title),cwd:Mf(s),createdAt:vn(s.started_at),modifiedAt:vn(s.last_activity_at??s.started_at),model:Ie(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...Ff(s)})}return n}catch(r){return N({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,
|
|
1683
1683
|
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 = ?
|
|
1684
|
-
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?$(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 u=Sn(c.timestamp),d=c.content??"";if(c.role==="user"){d&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(d),d.length>0&&(a||(a=$(d,80)),l=$(d,80)),i.push({role:"user",timestamp:u,content:d||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:u,content:d,toolCallId:Ie(c.tool_call_id),toolName:Ie(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:Ie(n.model),stopReason:Ie(c.finish_reason)});for(let m of sv(c.tool_calls)){let h=iv(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:Ie(m.function?.name)??"tool_call",toolName:Ie(m.function?.name),toolCallId:Ie(m.call_id)??Ie(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:De(h)})}}return{provider:this.name,sessionId:n.id,slug:Ie(n.title),cwd:Cf(n),createdAt:Sn(n.started_at),modifiedAt:Sn(n.last_activity_at??n.started_at),model:Ie(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...Of(n),messages:i,userPrompts:o}}catch(n){return N({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 ov}from"node:fs/promises";function lv(t){return av.test(t)}function Ff(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 cv}function Ua(t){return new $a(t)}var av,cv,$a,ja=A(()=>{"use strict";ke();Mf();ot();we();z();av=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;cv="dont_ask";$a=class extends Q{hermesProvider;hermesHome;constructor(e){let r=new ni(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)=>Ve(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:Ff(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Pa(e)}async openSession(e){return Ke({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:Ff(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await ov(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";N({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??X,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return lv(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(N({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 Pf,rm as dv,stat as uv}from"node:fs/promises";import{join as Ha}from"node:path";function Ba(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 $f(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var si,Uf=A(()=>{"use strict";me();si=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Ha(H,".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 Pf(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=Ha(this.baseDir,n);try{if(!(await uv(s)).isDirectory())continue;for(let i of await Pf(s))i.endsWith(".jsonl")&&r.push(Ha(s,i))}catch{}}return r}async readHeader(e){for await(let r of ne(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,u=0,d=0,m=0,h=0,_;for await(let T of ne(e)){if(T.type==="model_change"&&T.provider&&T.modelId){s=`${T.provider}/${T.modelId}`;continue}if(T.type!=="message"||!T.message)continue;let p=T.message;if(p.provider&&p.model&&(s=`${p.provider}/${p.model}`),p.role==="user"){let f=Ba(p).trim();f&&(i||(i=$(f,80)),o=$(f,80)),a++}else if(p.role==="assistant"){a++;let f=p.usage;f&&(l+=f.input??0,c+=f.cacheRead??0,u+=f.cacheWrite??0,d+=f.output??0,m+=f.reasoning??0,h=f.input??0,_={inputTokens:f.input,cachedInputTokens:f.cacheRead,cacheWriteInputTokens:f.cacheWrite,outputTokens:f.output,reasoningOutputTokens:f.reasoning,totalTokens:f.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:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:h,lastTokenUsage:_}}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 ne(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:Ba(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:$f(c.arguments),toolName:c.name??"tool",toolInput:$f(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Ba(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 dv(r,{force:!0}),!0):!1}}});function Xa(t){return new Wa(t)}var Wa,mv,qa=A(()=>{"use strict";Uf();ke();we();it();va();Wa=class extends Q{constructor(e){super({provider:new si(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",X],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:mv})}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}`}}},mv=zs({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>fe("pi",t,e.permissionMode??"yolo")})});import{createHash as fv}from"node:crypto";import{existsSync as pv,mkdirSync as Ja,readFileSync as hv,renameSync as gv,rmdirSync as Jf,statSync as _v,writeFileSync as yv}from"node:fs";import{dirname as za,join as jf,resolve as Ga}from"node:path";function Ev(t){return fv("sha256").update(t).digest("hex").slice(0,8)}function Tv(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function wv(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 Vf(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function ii(t){return Math.max(1,Math.ceil(t.length/4))}function Ar(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Ga(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?jf(za(Ga(r)),".lmctl-claude-mock","sessions.json"):jf(Ga(t),".lmctl-claude-mock","sessions.json")}function Hf(){return{schemaVersion:1,sessions:{}}}function vn(t){if(!pv(t))return Hf();try{let e=JSON.parse(hv(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=Va(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Hf()}}function Kf(t,e){Ja(za(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;yv(r,`${JSON.stringify(e,null,2)}
|
|
1685
|
-
`,"utf8"),gv(r,t)}function bv(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Iv(t){let e=`${t}.lock`;Ja(za(t),{recursive:!0});let r=Date.now()+Bf;for(;;)try{return Ja(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-_v(e).mtimeMs>Sv){try{Jf(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${Bf}ms: ${e}`);bv(vv)}}function xv(t){try{Jf(t)}catch{}}function Yf(t,e){let r=Iv(t);try{return e()}finally{xv(r)}}function Av(t){return{...t,timestamp:t.timestamp.toISOString()}}function kv(t){return{...t,timestamp:new Date(t.timestamp)}}function Nv(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(Av)}}function zf(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(kv)}}function oi(t,e=process.cwd()){let r=xr.get(t);if(r!==void 0)return r;let s=vn(Ar(e)).sessions[t];if(s===void 0)return;let i=zf(s);return xr.set(i.sessionId,i),i}function Wf(t){xr.set(t.sessionId,t);let e=Ar(t.cwd);Yf(e,()=>{let r=vn(e);r.sessions[t.sessionId]=Nv({...t,filePath:e}),Kf(e,r)})}function Rv(t,e=process.cwd()){let r=Ar(e);return Yf(r,()=>{let n=vn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],Kf(r,n)),s})}function Lv(){let t=vn(Ar()),e=Object.values(t.sessions).map(zf);for(let r of e)xr.set(r.sessionId,r);return e}function Va(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Xf(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Va(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=Va(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function qf(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function Cv(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Xf(r[t]??r[Vf(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Xf(n[s]);if(i!==void 0)return i}}}function Gf(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 Qa(){return new Ya}var xr,Sv,vv,Bf,Ka,Ya,Za=A(()=>{"use strict";xr=new Map;Sv=5e3,vv=15,Bf=1e4;Ka=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of Lv())e.set(r.sessionId,r);for(let r of xr.values())e.set(r.sessionId,r);return[...e.values()].map(Gf)}async loadSession(e){let r=oi(e);return r===void 0?null:{...Gf(r),messages:r.messages.slice()}}async resolveSessionPath(e){return oi(e)?.filePath??null}async deleteSession(e){let r=xr.delete(e),n=Rv(e);return r||n}},Ya=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Ka;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=Tv(wv(e,r)),s=`mock-${n}-${Ev(`${e}:${n}`)}`,i=new Date,o=Ar(e),a=oi(s,e),l=r?.prompt??"ClaudeMock seed",c=ii(l),u={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return u.messages.push({role:"user",timestamp:i,content:l}),u.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),u.totalInputTokens+=c,u.totalOutputTokens+=ii("ACK: ClaudeMock seeded"),Wf(u),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=oi(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=vn(Ar(r.cwd)),a=Cv(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await qf(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Vf(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+=ii(e),s.totalOutputTokens+=ii(c),Wf(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await qf(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function kt(t){let e=[Go({claudeDir:t?.claudeDir}),Yo({codexDir:t?.codexDir,codeDir:t?.codeDir}),ra({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),oa({copilotDir:t?.copilotDir}),ca(),pa({kimiHome:t?.kimiHome}),_a({lmplayerDbPath:t?.lmplayerDbPath}),Ta(),Ia({agyDir:t?.agyDir}),Da({dshHome:t?.dshHome}),Ua({hermesHome:t?.hermesHome}),Xa({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Qa()),e}var el=A(()=>{"use strict";Jo();zo();na();aa();da();ha();ya();wa();xa();Ma();ja();qa();Za();Jo();zo();na();aa();da();ha();ya();wa();xa();Ma();ja();qa();Za()});var ai,li,Qf=A(()=>{"use strict";ai=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],li=["agy","pi","lmplayer"]});var ep={};Jl(ep,{BUNDLE_CAPABLE_PROVIDERS:()=>ai,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>li,ProviderRegistry:()=>Qr,TransportConnectionError:()=>Z,TransportError:()=>Et,TransportJsonError:()=>ws,TransportProcessError:()=>en,TransportRpcError:()=>tn,_resetDefaultRegistryForTests:()=>Ov,bundleSupportedProviders:()=>di,chat:()=>bn,countTokens:()=>Mv,createAdapterRegistry:()=>yt,createAllAdapters:()=>kt,deleteSession:()=>il,listSessions:()=>sl,openBundleSession:()=>rl,seed:()=>nl});function Xt(){return ci===null&&(ci=yt(kt())),ci}function Ov(){ci=null}function tl(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function bn(t){let e=t.registry??Xt(),r=tl(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 di(t){return(t??Xt()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function rl(t){let e=t.registry??Xt(),r=tl(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${di(e).join(", ")})`);return r.openSession(t)}async function nl(t){let e=t.registry??Xt(),r=tl(e,t.provider),n=await Zf(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&&s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await Zf(e,t.provider,t.cwd),a=Dv(n,o);return s.success?a?{success:!0,sessionId:a,...i}:{success:!0,...i}:(a&&await r.delete?.(a).catch(()=>{}),{success:!1,error:s.error,...i})}async function Zf(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 Dv(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 sl(t={}){return(t.registry??Xt()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function il(t,e,r=Xt()){return r.deleteSession(e,t)}async function Mv(t){let r=await(t.registry??Xt()).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 ci,In=A(()=>{"use strict";_o();el();_o();el();Qf();Ut();ci=null});function ui(t){return Pv.has(t)}function al(){return ol===null&&(ol=yt(kt())),ol}function ll(t,e,r={}){if(!ui(t))return null;try{let n=al().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?As({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?Fv[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...tp[t]??[]]}catch{return null}}function np(t,e,r={}){let n=ll(t,e,r);return n===null?null:n.join(" ")}function kr(t,e){return al().getSession(t,e)}async function sp(t){return(await al().resolveSessions(t)).map(r=>r.provider.name)}var tp,Fv,Pv,rp,ol,mi=A(()=>{"use strict";In();ko();tp={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],pi:[],lmplayer:["--auto"],kimi:[],hermes:[]},Fv={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t],kimi:t=>["--model",t],hermes:t=>["--model",t],pi:t=>["--model",t]},Pv=new Set(Object.keys(tp)),rp=/^[\w.:-]+$/;ol=null});import{randomUUID as Bv}from"node:crypto";import{hostname as lp,networkInterfaces as Wv}from"node:os";function cp(t){let e=(t.now??new Date).toISOString();return{lock_id:Bv(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??lp(),holder_ips:t.ips??Vv(),started_at:e,last_heartbeat:e}}function dp(t=process.env){return up(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,Xv)}function Gv(t=process.env){return up(t.LMCTL_TERMINAL_LOCK_STALE_MS,qv)}function ul(t,e={}){let r=e.now??new Date,n=e.localHost??lp(),s=e.staleMs??Gv();if(t.holder_host===n)return(e.isProcessAlive??Jv)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?r.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function xn(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function up(t,e){if(t===void 0||t.trim()==="")return e;let r=t.trim(),n=Number.parseInt(r,10);return!Number.isFinite(n)||n<=0||String(n)!==r?e:n}function Jv(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function Vv(){let t=new Set;for(let e of Object.values(Wv()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var Xv,qv,fi=A(()=>{"use strict";Xv=15e3,qv=12e4});import{execFileSync as wA}from"node:child_process";import{resolve as rg}from"node:path";function SA(t){return t.filter(e=>e.state!=="retired")}function ng(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?B(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=wA("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return B(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=rg(s),o=e.listProjects().find(a=>rg(a.local_path)===i);return o===void 0?B(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function sg(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?B(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?B(t,`project ${r.name} has no assigned team; use --team <name>`):s}function ig(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?B(t,`member not found: ${n}`):i}let s=SA(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?B(t,`team ${r.name} has no active agent member`):s}var og=A(()=>{"use strict";_r()});function ag(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}var lg=A(()=>{"use strict"});var ug={};Jl(ug,{SIZE_WARN_EST_TOKENS:()=>Dn,estimateTokens:()=>dg,runTerminal:()=>xA});import{spawn as vA}from"node:child_process";import{statSync as bA}from"node:fs";async function xA(t,e){if(t.includes("--help")||t.includes("-h"))return OA(e);let r=po(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return B(e,r.error);if(pr(e)&&!$t(r,"--size"))return B(e,"terminal opens an interactive TUI; non-interactive mode is enabled");let n=gt(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return B(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return B(e,"--run is mutually exclusive with positional <teamfile>[:alias]");let i=["--team","--project","--size","--json"];for(let o of i)if(o==="--size"||o==="--json"?$t(r,o):gt(r,o)!==void 0)return B(e,`--run is mutually exclusive with ${o}`);try{return await j(e,async o=>{let a=gt(r,"--alias"),l=ag(o,s,a);return"err"in l?B(e,l.err):Wl(e,{provider:l.ok.provider,sessionid:l.ok.sessionid,sessiondir:l.ok.sessiondir,...l.ok.model!==void 0?{model:l.ok.model}:{}})})}catch(o){return hs(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?$t(r,l):gt(r,l)!==void 0)return B(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return B(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=Ic(IA,{target:i,alias:o,flags:{}});return a.mode==="error"?B(e,a.message):a.mode!=="ai-team"?B(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?B(e,"terminal: alias required for the teamfile target"):await j(e,l=>AA(e,a.teamfile,a.alias,l,$t(r,"--json")))}try{return await j(e,async s=>{let i=RA(e,s,r);if(typeof i=="number")return i;let o=gt(r,"--alias");return $t(r,"--size")?CA(e,s,i,o,$t(r,"--json")):LA(e,s,i,o)})}catch(s){return hs(e,s)}}async function AA(t,e,r,n,s){let i;try{i=tt(e,r,n)}catch(m){return m instanceof he?B(t,m.message):hs(t,m)}let o=lr(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:mt()});if(!o.acquired){let m=o.current.holder_pid,h=m===null?null:Ee(m)?"live":"dead",_=`${i.alias} is busy/held by ${o.current.sender_alias} (${o.current.sender_teamfile}) since ${o.current.started_at} `+(m===null?"(holder_pid=unavailable)":`(holder_pid=${m}, ${h})`);return s?(ho(t,{status:"error",errorKind:"busy",message:_,holder_pid:m,holder_liveness:h}),1):B(t,_)}let a=cp({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,u=null,d=[];try{n.setTerminalLock(a),c=kA(n,i),c!==null&&(process.env.LMCTL_INVOCATION_ID=String(c));let m=n.getRootTeam(i.teamfile)?.name??null;m!==null&&(process.env.LMBEE_TEAM_NAME=m),l=setInterval(()=>{try{let h=new Date().toISOString(),_=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,h);_&&n.heartbeatAgentInflight(o.lease,o.leaseId,h),!_&&l!==null&&(clearInterval(l),l=null)}catch{}},dp()),l.unref?.();try{sr(t,$e(i.teamfile),i.teamfile)}catch{}return u=await Wl(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},h=>{d.push(`${h.provider} terminal ignored model=${h.model}: ${h.reason}`)}),u}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),NA(n,c,u,d)}}function kA(t,e){try{return t.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:e.teamfile,from_identity:`${e.teamfile}:terminal`,target_teamfile:e.teamfile,target_alias:e.alias,root_teamfile:e.teamfile,cwd:e.sessiondir,command:`lmctl terminal ${e.teamfile} ${e.alias}`,holder_pid:process.pid,launch_source:"terminal",parent_invocation_id:gr(process.env.LMCTL_INVOCATION_ID),meta:JSON.stringify({provider:e.provider,sessionid:e.sessionid,...e.model!==void 0?{model:e.model}:{}})}).id}catch{return null}}function NA(t,e,r,n=[]){if(e!==null)try{t.finishTrackedInvocation(e,{status:r===0?"done":"error",exit_code:r,result_summary:r===0?"terminal session ended":null,error:r===0?null:`terminal exited with code ${r??"unknown"}`,...n.length>0?{config_warnings:JSON.stringify(n)}:{}})}catch{}}async function Wl(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!ui(n))return B(t,`no resume incantation for provider "${n}"`);if(!rp.test(s))return B(t,"refusing to resume: malformed sessionid");let a=ll(n,s,{isLead:e.isLead,model:o,onModelIgnored:u=>{let d=`warning: ${u.provider} terminal ignored model=${u.model}: ${u.reason}`;t.stderr.write(`${d}
|
|
1686
|
-
`),_e({event:"model_ignored",provider:u.provider,model:u.model,reason:u.reason}),r?.(u)}});if(a===null||a.length===0)return B(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(u=>{let d=
|
|
1687
|
-
`),t.stdout.write(`${
|
|
1684
|
+
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?$(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 u=vn(c.timestamp),d=c.content??"";if(c.role==="user"){d&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(d),d.length>0&&(a||(a=$(d,80)),l=$(d,80)),i.push({role:"user",timestamp:u,content:d||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:u,content:d,toolCallId:Ie(c.tool_call_id),toolName:Ie(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:Ie(n.model),stopReason:Ie(c.finish_reason)});for(let m of Tv(c.tool_calls)){let h=wv(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:Ie(m.function?.name)??"tool_call",toolName:Ie(m.function?.name),toolCallId:Ie(m.call_id)??Ie(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:De(h)})}}return{provider:this.name,sessionId:n.id,slug:Ie(n.title),cwd:Mf(n),createdAt:vn(n.started_at),modifiedAt:vn(n.last_activity_at??n.started_at),model:Ie(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...Ff(n),messages:i,userPrompts:o}}catch(n){return N({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 Sv}from"node:fs/promises";function bv(t){return vv.test(t)}function Uf(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 Iv}function Ha(t){return new ja(t)}var vv,Iv,ja,Ba=A(()=>{"use strict";ke();$f();ot();we();z();vv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Iv="dont_ask";ja=class extends Q{hermesProvider;hermesHome;constructor(e){let r=new si(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)=>Ke(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:Uf(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Ua(e)}async openSession(e){return Ve({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:Uf(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Sv(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";N({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??X,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return bv(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(N({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 jf,rm as xv,stat as Av}from"node:fs/promises";import{join as Wa}from"node:path";function Xa(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 Hf(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var ii,Bf=A(()=>{"use strict";me();ii=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Wa(H,".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 jf(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=Wa(this.baseDir,n);try{if(!(await Av(s)).isDirectory())continue;for(let i of await jf(s))i.endsWith(".jsonl")&&r.push(Wa(s,i))}catch{}}return r}async readHeader(e){for await(let r of ne(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,u=0,d=0,m=0,h=0,_;for await(let T of ne(e)){if(T.type==="model_change"&&T.provider&&T.modelId){s=`${T.provider}/${T.modelId}`;continue}if(T.type!=="message"||!T.message)continue;let p=T.message;if(p.provider&&p.model&&(s=`${p.provider}/${p.model}`),p.role==="user"){let f=Xa(p).trim();f&&(i||(i=$(f,80)),o=$(f,80)),a++}else if(p.role==="assistant"){a++;let f=p.usage;f&&(l+=f.input??0,c+=f.cacheRead??0,u+=f.cacheWrite??0,d+=f.output??0,m+=f.reasoning??0,h=f.input??0,_={inputTokens:f.input,cachedInputTokens:f.cacheRead,cacheWriteInputTokens:f.cacheWrite,outputTokens:f.output,reasoningOutputTokens:f.reasoning,totalTokens:f.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:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:h,lastTokenUsage:_}}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 ne(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:Xa(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:Hf(c.arguments),toolName:c.name??"tool",toolInput:Hf(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Xa(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 xv(r,{force:!0}),!0):!1}}});function Ga(t){return new qa(t)}var qa,kv,Ja=A(()=>{"use strict";Bf();ke();we();it();Ia();qa=class extends Q{constructor(e){super({provider:new ii(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",X],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:kv})}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}`}}},kv=Qs({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>fe("pi",t,e.permissionMode??"yolo")})});import{createHash as Nv}from"node:crypto";import{existsSync as Rv,mkdirSync as Va,readFileSync as Lv,renameSync as Cv,rmdirSync as Yf,statSync as Ov,writeFileSync as Dv}from"node:fs";import{dirname as Za,join as Wf,resolve as Ka}from"node:path";function Mv(t){return Nv("sha256").update(t).digest("hex").slice(0,8)}function Fv(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function Pv(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 zf(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function oi(t){return Math.max(1,Math.ceil(t.length/4))}function kr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Ka(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Wf(Za(Ka(r)),".lmctl-claude-mock","sessions.json"):Wf(Ka(t),".lmctl-claude-mock","sessions.json")}function Xf(){return{schemaVersion:1,sessions:{}}}function bn(t){if(!Rv(t))return Xf();try{let e=JSON.parse(Lv(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=Ya(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Xf()}}function Qf(t,e){Va(Za(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;Dv(r,`${JSON.stringify(e,null,2)}
|
|
1685
|
+
`,"utf8"),Cv(r,t)}function jv(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Hv(t){let e=`${t}.lock`;Va(Za(t),{recursive:!0});let r=Date.now()+qf;for(;;)try{return Va(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Ov(e).mtimeMs>$v){try{Yf(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${qf}ms: ${e}`);jv(Uv)}}function Bv(t){try{Yf(t)}catch{}}function Zf(t,e){let r=Hv(t);try{return e()}finally{Bv(r)}}function Wv(t){return{...t,timestamp:t.timestamp.toISOString()}}function Xv(t){return{...t,timestamp:new Date(t.timestamp)}}function qv(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(Wv)}}function ep(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(Xv)}}function ai(t,e=process.cwd()){let r=Ar.get(t);if(r!==void 0)return r;let s=bn(kr(e)).sessions[t];if(s===void 0)return;let i=ep(s);return Ar.set(i.sessionId,i),i}function Gf(t){Ar.set(t.sessionId,t);let e=kr(t.cwd);Zf(e,()=>{let r=bn(e);r.sessions[t.sessionId]=qv({...t,filePath:e}),Qf(e,r)})}function Gv(t,e=process.cwd()){let r=kr(e);return Zf(r,()=>{let n=bn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],Qf(r,n)),s})}function Jv(){let t=bn(kr()),e=Object.values(t.sessions).map(ep);for(let r of e)Ar.set(r.sessionId,r);return e}function Ya(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Jf(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Ya(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=Ya(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Kf(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function Kv(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Jf(r[t]??r[zf(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Jf(n[s]);if(i!==void 0)return i}}}function Vf(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 el(){return new Qa}var Ar,$v,Uv,qf,za,Qa,tl=A(()=>{"use strict";Ar=new Map;$v=5e3,Uv=15,qf=1e4;za=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of Jv())e.set(r.sessionId,r);for(let r of Ar.values())e.set(r.sessionId,r);return[...e.values()].map(Vf)}async loadSession(e){let r=ai(e);return r===void 0?null:{...Vf(r),messages:r.messages.slice()}}async resolveSessionPath(e){return ai(e)?.filePath??null}async deleteSession(e){let r=Ar.delete(e),n=Gv(e);return r||n}},Qa=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new za;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=Fv(Pv(e,r)),s=`mock-${n}-${Mv(`${e}:${n}`)}`,i=new Date,o=kr(e),a=ai(s,e),l=r?.prompt??"ClaudeMock seed",c=oi(l),u={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return u.messages.push({role:"user",timestamp:i,content:l}),u.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),u.totalInputTokens+=c,u.totalOutputTokens+=oi("ACK: ClaudeMock seeded"),Gf(u),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=ai(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=bn(kr(r.cwd)),a=Kv(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Kf(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${zf(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+=oi(e),s.totalOutputTokens+=oi(c),Gf(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Kf(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function kt(t){let e=[Ko({claudeDir:t?.claudeDir}),Qo({codexDir:t?.codexDir,codeDir:t?.codeDir}),sa({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),la({copilotDir:t?.copilotDir}),ua(),ga({kimiHome:t?.kimiHome}),Ea({lmplayerDbPath:t?.lmplayerDbPath}),Sa(),Aa({agyDir:t?.agyDir}),Fa({dshHome:t?.dshHome}),Ha({hermesHome:t?.hermesHome}),Ga({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(el()),e}var rl=A(()=>{"use strict";Vo();Zo();ia();ca();ma();_a();Ta();va();ka();Pa();Ba();Ja();tl();Vo();Zo();ia();ca();ma();_a();Ta();va();ka();Pa();Ba();Ja();tl()});var li,ci,tp=A(()=>{"use strict";li=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],ci=["agy","pi","lmplayer"]});var np={};Yl(np,{BUNDLE_CAPABLE_PROVIDERS:()=>li,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>ci,ProviderRegistry:()=>Zr,TransportConnectionError:()=>Z,TransportError:()=>Et,TransportJsonError:()=>Ss,TransportProcessError:()=>tn,TransportRpcError:()=>rn,_resetDefaultRegistryForTests:()=>Vv,bundleSupportedProviders:()=>ui,chat:()=>In,countTokens:()=>zv,createAdapterRegistry:()=>yt,createAllAdapters:()=>kt,deleteSession:()=>al,listSessions:()=>ol,openBundleSession:()=>sl,seed:()=>il});function qt(){return di===null&&(di=yt(kt())),di}function Vv(){di=null}function nl(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function In(t){let e=t.registry??qt(),r=nl(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 ui(t){return(t??qt()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function sl(t){let e=t.registry??qt(),r=nl(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${ui(e).join(", ")})`);return r.openSession(t)}async function il(t){let e=t.registry??qt(),r=nl(e,t.provider),n=await rp(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&&s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await rp(e,t.provider,t.cwd),a=Yv(n,o);return s.success?a?{success:!0,sessionId:a,...i}:{success:!0,...i}:(a&&await r.delete?.(a).catch(()=>{}),{success:!1,error:s.error,...i})}async function rp(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 Yv(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 ol(t={}){return(t.registry??qt()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function al(t,e,r=qt()){return r.deleteSession(e,t)}async function zv(t){let r=await(t.registry??qt()).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 di,xn=A(()=>{"use strict";Eo();rl();Eo();rl();tp();jt();di=null});function mi(t){return Zv.has(t)}function cl(){return ll===null&&(ll=yt(kt())),ll}function dl(t,e,r={}){if(!mi(t))return null;try{let n=cl().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?ks({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?Qv[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...sp[t]??[]]}catch{return null}}function op(t,e,r={}){let n=dl(t,e,r);return n===null?null:n.join(" ")}function Nr(t,e){return cl().getSession(t,e)}async function ap(t){return(await cl().resolveSessions(t)).map(r=>r.provider.name)}var sp,Qv,Zv,ip,ll,fi=A(()=>{"use strict";xn();Ro();sp={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],pi:[],lmplayer:["--auto"],kimi:[],hermes:[]},Qv={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t],kimi:t=>["--model",t],hermes:t=>["--model",t],pi:t=>["--model",t]},Zv=new Set(Object.keys(sp)),ip=/^[\w.:-]+$/;ll=null});import{randomUUID as sb}from"node:crypto";import{hostname as up,networkInterfaces as ib}from"node:os";function mp(t){let e=(t.now??new Date).toISOString();return{lock_id:sb(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??up(),holder_ips:t.ips??db(),started_at:e,last_heartbeat:e}}function fp(t=process.env){return pp(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,ob)}function lb(t=process.env){return pp(t.LMCTL_TERMINAL_LOCK_STALE_MS,ab)}function fl(t,e={}){let r=e.now??new Date,n=e.localHost??up(),s=e.staleMs??lb();if(t.holder_host===n)return(e.isProcessAlive??cb)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?r.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function An(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function pp(t,e){if(t===void 0||t.trim()==="")return e;let r=t.trim(),n=Number.parseInt(r,10);return!Number.isFinite(n)||n<=0||String(n)!==r?e:n}function cb(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function db(){let t=new Set;for(let e of Object.values(ib()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var ob,ab,pi=A(()=>{"use strict";ob=15e3,ab=12e4});import{execFileSync as VA}from"node:child_process";import{resolve as fg}from"node:path";function YA(t){return t.filter(e=>e.state!=="retired")}function pg(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?B(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=VA("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return B(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=fg(s),o=e.listProjects().find(a=>fg(a.local_path)===i);return o===void 0?B(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function hg(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?B(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?B(t,`project ${r.name} has no assigned team; use --team <name>`):s}function gg(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?B(t,`member not found: ${n}`):i}let s=YA(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?B(t,`team ${r.name} has no active agent member`):s}var _g=A(()=>{"use strict";yr()});function yg(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}var Eg=A(()=>{"use strict"});var Sg={};Yl(Sg,{SIZE_WARN_EST_TOKENS:()=>Mn,estimateTokens:()=>wg,runTerminal:()=>ek});import{spawn as zA}from"node:child_process";import{statSync as QA}from"node:fs";async function ek(t,e){if(t.includes("--help")||t.includes("-h"))return ak(e);let r=go(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return B(e,r.error);if(hr(e)&&!Ut(r,"--size"))return B(e,"terminal opens an interactive TUI; non-interactive mode is enabled");let n=gt(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return B(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return B(e,"--run is mutually exclusive with positional <teamfile>[:alias]");let i=["--team","--project","--size","--json"];for(let o of i)if(o==="--size"||o==="--json"?Ut(r,o):gt(r,o)!==void 0)return B(e,`--run is mutually exclusive with ${o}`);try{return await j(e,async o=>{let a=gt(r,"--alias"),l=yg(o,s,a);return"err"in l?B(e,l.err):Gl(e,{provider:l.ok.provider,sessionid:l.ok.sessionid,sessiondir:l.ok.sessiondir,...l.ok.model!==void 0?{model:l.ok.model}:{}})})}catch(o){return gs(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?Ut(r,l):gt(r,l)!==void 0)return B(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return B(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=kc(ZA,{target:i,alias:o,flags:{}});return a.mode==="error"?B(e,a.message):a.mode!=="ai-team"?B(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?B(e,"terminal: alias required for the teamfile target"):await j(e,l=>tk(e,a.teamfile,a.alias,l,Ut(r,"--json")))}try{return await j(e,async s=>{let i=sk(e,s,r);if(typeof i=="number")return i;let o=gt(r,"--alias");return Ut(r,"--size")?ok(e,s,i,o,Ut(r,"--json")):ik(e,s,i,o)})}catch(s){return gs(e,s)}}async function tk(t,e,r,n,s){let i;try{i=tt(e,r,n)}catch(m){return m instanceof he?B(t,m.message):gs(t,m)}let o=cr(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:mt()});if(!o.acquired){let m=o.current.holder_pid,h=m===null?null:Ee(m)?"live":"dead",_=`${i.alias} is busy/held by ${o.current.sender_alias} (${o.current.sender_teamfile}) since ${o.current.started_at} `+(m===null?"(holder_pid=unavailable)":`(holder_pid=${m}, ${h})`);return s?(_o(t,{status:"error",errorKind:"busy",message:_,holder_pid:m,holder_liveness:h}),1):B(t,_)}let a=mp({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,u=null,d=[];try{n.setTerminalLock(a),c=rk(n,i),c!==null&&(process.env.LMCTL_INVOCATION_ID=String(c));let m=n.getRootTeam(i.teamfile)?.name??null;m!==null&&(process.env.LMBEE_TEAM_NAME=m),l=setInterval(()=>{try{let h=new Date().toISOString(),_=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,h);_&&n.heartbeatAgentInflight(o.lease,o.leaseId,h),!_&&l!==null&&(clearInterval(l),l=null)}catch{}},fp()),l.unref?.();try{ir(t,$e(i.teamfile),i.teamfile)}catch{}return u=await Gl(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},h=>{d.push(`${h.provider} terminal ignored model=${h.model}: ${h.reason}`)}),u}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),nk(n,c,u,d)}}function rk(t,e){try{return t.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:e.teamfile,from_identity:`${e.teamfile}:terminal`,target_teamfile:e.teamfile,target_alias:e.alias,root_teamfile:e.teamfile,cwd:e.sessiondir,command:`lmctl terminal ${e.teamfile} ${e.alias}`,holder_pid:process.pid,launch_source:"terminal",parent_invocation_id:_r(process.env.LMCTL_INVOCATION_ID),meta:JSON.stringify({provider:e.provider,sessionid:e.sessionid,...e.model!==void 0?{model:e.model}:{}})}).id}catch{return null}}function nk(t,e,r,n=[]){if(e!==null)try{t.finishTrackedInvocation(e,{status:r===0?"done":"error",exit_code:r,result_summary:r===0?"terminal session ended":null,error:r===0?null:`terminal exited with code ${r??"unknown"}`,...n.length>0?{config_warnings:JSON.stringify(n)}:{}})}catch{}}async function Gl(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!mi(n))return B(t,`no resume incantation for provider "${n}"`);if(!ip.test(s))return B(t,"refusing to resume: malformed sessionid");let a=dl(n,s,{isLead:e.isLead,model:o,onModelIgnored:u=>{let d=`warning: ${u.provider} terminal ignored model=${u.model}: ${u.reason}`;t.stderr.write(`${d}
|
|
1686
|
+
`),_e({event:"model_ignored",provider:u.provider,model:u.model,reason:u.reason}),r?.(u)}});if(a===null||a.length===0)return B(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(u=>{let d=zA(l,c,{stdio:"inherit",cwd:i,env:de(process.env,i,s,"terminal")});d.on("error",m=>{u(B(t,`failed to launch ${l}: ${m.message}`))}),d.on("exit",m=>u(m??0))})}function sk(t,e,r){let n=gt(r,"--team");if(n!==void 0){let o=e.findTeamByName(n);return o===null?B(t,`team not found: ${n}`):o}let s=pg(t,e,gt(r,"--project"));return typeof s=="number"?s:hg(t,e,s,void 0)}async function ik(t,e,r,n){let s=gg(t,e,r,n);if(typeof s=="number")return s;let i=s.sessionid;return i===null||i.trim().length===0?B(t,`member ${s.alias} has no session yet \u2014 seed it first: lmctl seed <teamfile> (check with lmctl status <teamfile>)`):Gl(t,{provider:mo(s),sessionid:i,sessiondir:s.sessiondir,...s.model!==null&&s.model!==void 0?{model:s.model}:{}})}function wg(t){if(t&&Array.isArray(t.messages)&&t.messages.length>0){let r=t.messages.reduce((n,s)=>n+(s.content?.length??0),0);return{chars:r,est:Math.ceil(r/4),messages:t.messages.length,bytes:null}}let e=t?.filePath;if(e!==void 0)try{let r=QA(e).size;return{chars:r,est:Math.ceil(r/4),messages:t?.messages?.length??null,bytes:r}}catch{}return{chars:0,est:0,messages:null,bytes:null}}async function ok(t,e,r,n,s){let i;if(n!==void 0){let a=e.findTeamMemberByAlias(r.id,n);if(a===null||a.state==="retired")return B(t,`member not found: ${n}`);i=[a]}else i=e.listTeamMembers(r.id).filter(a=>a.state!=="retired"&&a.sessionid!==null);let o=[];for(let a of i){let l=a.sessionid;if(l===null)continue;let c=mo(a),u=a.model??null,d=null;mi(c)&&(d=await Nr(l,c));let m=wg(d),h=m.est>Mn;o.push({alias:a.alias,provider:c,sessionid:l,messages:m.messages,bytes:m.bytes,est_tokens:m.est,estimate:!0,over_guide:h,model:u,resume_incantation:h?op(c,l,u!==null?{model:u}:{}):null})}if(s)return _o(t,{estimate:!0,legend:Tg,guide_tokens:Mn,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
1687
|
+
`),t.stdout.write(`${Tg}
|
|
1688
1688
|
`);for(let a of o){let l=a.messages===null?"?":String(a.messages),c=a.bytes===null?"?":String(a.bytes);t.stdout.write(`${a.alias} ${a.provider} msgs=${l} bytes=${c} ~${a.est_tokens} tok (rough estimate)
|
|
1689
1689
|
`),a.over_guide&&t.stdout.write(` \u26A0 ${a.alias}: estimated ~${a.est_tokens} tokens \u2014 ESTIMATE only, exceeds the 200K guide.
|
|
1690
1690
|
Nothing was changed automatically. If you choose to compact, open the
|
|
1691
1691
|
session yourself:
|
|
1692
1692
|
${a.resume_incantation??"(no resume incantation for provider "+a.provider+")"}
|
|
1693
1693
|
(or: lmctl terminal --team ${r.name} --alias ${a.alias})
|
|
1694
|
-
`)}return 0}function
|
|
1694
|
+
`)}return 0}function ak(t){return t.stdout.write(`usage: lmctl terminal <teamfile>:<alias> [--json]
|
|
1695
1695
|
lmctl terminal <teamfile> <alias> [--json]
|
|
1696
1696
|
lmctl terminal --run <id> [--alias A]
|
|
1697
1697
|
lmctl terminal [--project P] [--team T] [--alias A] [--size] [--json]
|
|
@@ -1720,17 +1720,17 @@ ${r?.prompt??X}`}),i=(await this.provider.discoverSessions()).filter(o=>o.firstU
|
|
|
1720
1720
|
exact provider count: the messages path slightly
|
|
1721
1721
|
under-counts code-dense text; the byte fallback
|
|
1722
1722
|
over-counts (JSONL overhead \u2192 safe over-warn); CJK is
|
|
1723
|
-
denser (under-warns). At >${
|
|
1723
|
+
denser (under-warns). At >${Mn} est
|
|
1724
1724
|
tokens it surfaces the resume incantation so YOU can
|
|
1725
1725
|
open & self-compact. Nothing is ever changed
|
|
1726
|
-
automatically; ${
|
|
1727
|
-
`),0}var
|
|
1726
|
+
automatically; ${Mn} is a guide, not a gate.
|
|
1727
|
+
`),0}var ZA,Mn,Tg,vg=A(()=>{"use strict";fr();fi();yr();_g();Lt();et();Je();ts();Ft();rs();pi();Eg();z();Mt();ZA={name:"terminal",allowsBareTeamfile:!1,supportsRaw:!1},Mn=2e5,Tg="est = rough local heuristic (~4 chars/token), NOT an exact provider token count \u2014 open the session to verify before acting."});import{spawn as Ql,spawnSync as Di}from"node:child_process";import{randomUUID as Ug}from"node:crypto";import{tmpdir as jg}from"node:os";import*as M from"node:fs";import*as ae from"node:path";import*as ic from"node:readline";import{fileURLToPath as oc}from"node:url";var D=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}},ve=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};function ac(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{M.existsSync(t.file)&&M.statSync(t.file).isFile()&&(n=M.readFileSync(t.file,"utf-8"))}catch{}if(!n)return`[${t.severity.toUpperCase()} at ${r}] ${t.message}`;let s=n.split(`
|
|
1728
1728
|
`),i=String(t.line),o=t.line-1,a=s[o]??"",l=" | ",c=` ${i.padStart(4," ")} | `,u=" ".repeat(Math.max(0,t.column-1));return`[${t.severity.toUpperCase()} at ${r}] ${t.message}
|
|
1729
1729
|
`+l+`
|
|
1730
1730
|
${c}${a}
|
|
1731
|
-
${l}${u}^`}function
|
|
1731
|
+
${l}${u}^`}function lc(t){if(typeof t!="string"||t.length!==1||/["\r\n]/.test(t))throw new Error("CSV delimiter must be one character other than a quote or newline")}function Be(t,e){return t!=null&&Object.hasOwn(t,e)?t[e]:void 0}function ct(t,e,r){String(e)==="__proto__"?Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}):t[e]=r}function $r(t,e){if(t==null)return;let r=Array.isArray(e)?e:String(e).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),n=t;for(let s of r){if(n==null||typeof n!="object")return;n=Be(n,s)}return n}var Mi=10*1024*1024;function cc(t){if(typeof t!="string"||!t.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(t)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let r=`
|
|
1732
1732
|
const target = process.argv[1];
|
|
1733
|
-
const maxBytes = ${
|
|
1733
|
+
const maxBytes = ${Mi};
|
|
1734
1734
|
const controller = new AbortController();
|
|
1735
1735
|
const timer = setTimeout(() => controller.abort(), 30000);
|
|
1736
1736
|
try {
|
|
@@ -1756,19 +1756,19 @@ try {
|
|
|
1756
1756
|
} finally {
|
|
1757
1757
|
clearTimeout(timer);
|
|
1758
1758
|
}
|
|
1759
|
-
`,n=
|
|
1759
|
+
`,n=Di(process.execPath,["--input-type=module","-e",r,t],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:Mi+4096,windowsHide:!0});if(n.error)throw n.error.code==="ETIMEDOUT"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${n.error.message}`);if(n.status!==0)throw new Error(`urlget() failed: ${String(n.stderr||"child process exited")}`.trim());return String(n.stdout||"")}async function Hg(t){if(typeof t!="string"||!t.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(t)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let r=new AbortController,n=setTimeout(()=>r.abort(),3e4),s;try{let i=await fetch(e.toString(),{method:"GET",redirect:"follow",signal:r.signal});if(!i.ok)throw r.abort(),new Error("HTTP "+i.status+" "+i.statusText);s=i.body?.getReader();let o=[],a=0;if(s)for(;;){let l=await s.read();if(l.done)break;if(a+=l.value.byteLength,a>Mi)throw await s.cancel().catch(()=>{}),r.abort(),new Error("response exceeds 10 MiB limit");o.push(l.value)}return Buffer.concat(o).toString("utf-8")}catch(i){if(r.abort(),s)try{await s.cancel().catch(()=>{})}catch{}throw i.name==="AbortError"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${i?.message||String(i)}`)}finally{clearTimeout(n)}}var jn=new Set,$n=1e3;process.on("exit",()=>{for(let t of jn)try{process.platform!=="win32"&&t.pid?process.kill(-t.pid,"SIGKILL"):t.kill("SIGKILL")}catch{}jn.clear()});function Hn(t,e,r,n=null,s=!1,i=0,o=null){return{stdout:t,stderr:e,code:r,signal:n,timed_out:s,duration_ms:i,pid:o}}function dc(t){let e=String(t);return e.length>0&&/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function uc(t,e=6e4){if(!Number.isSafeInteger(e)||e<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");let r=performance.now(),n;if(Array.isArray(t)){if(t.length===0)throw new Error("system() argv array must not be empty");let u=String(t[0]),d=t.slice(1).map(String);n=Di(u,d,{shell:!1,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"})}else n=Di(t,{shell:!0,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"});let s=Math.max(0,Math.round(performance.now()-r)),i=typeof n.pid=="number"?n.pid:null;if(n.error){if(n.error.code==="ETIMEDOUT"){let u=n.stdout!=null?String(n.stdout):"",d=n.stderr!=null?String(n.stderr):"";return Hn(u,d,null,n.signal||"SIGKILL",!0,s,i)}throw n.error}let o=n.stdout!=null?String(n.stdout):"",a=n.stderr!=null?String(n.stderr):"",l=n.status!==null?n.status:null,c=n.signal!==null?String(n.signal):null;return Hn(o,a,l,c,!1,s,i)}function mc(t,e=6e4){return new Promise((r,n)=>{if(!Number.isSafeInteger(e)||e<0){n(new Error("system() timeout must be a non-negative safe integer in milliseconds"));return}let s=performance.now();try{let i=process.platform!=="win32",o;if(Array.isArray(t)){if(t.length===0){n(new Error("system() argv array must not be empty"));return}let g=String(t[0]),E=t.slice(1).map(String);o=Ql(g,E,{shell:!1,detached:i,stdio:["ignore","pipe","pipe"]})}else o=Ql(t,{shell:!0,detached:i,stdio:["ignore","pipe","pipe"]});jn.add(o);let a="",l="",c=null,u=null,d=0,m=!1,h=!1,_,T=!1,p,f=()=>{if(T)return;T=!0,jn.delete(o),p&&clearTimeout(p);try{o.stdout?.destroy(),o.stderr?.destroy()}catch{}let g=Math.max(0,Math.round(performance.now()-s)),E=typeof o.pid=="number"?o.pid:null;if(_){n(_);return}if(h){r(Hn(a,l,null,u||"SIGKILL",!0,g,E));return}r(Hn(a,l,c,u,!1,g,E))};e>0&&(p=setTimeout(()=>{h=!0,u="SIGKILL";try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}f()},e));let y=10*1024*1024;o.stdout?.setEncoding("utf-8"),o.stderr?.setEncoding("utf-8"),o.stdout?.on("data",g=>{let E=Buffer.byteLength(g,"utf-8");if(d+E>y){if(!m){m=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
1760
1760
|
`)?`
|
|
1761
1761
|
`:"")+"system() output exceeds 10 MiB limit",_=new Error("system() output exceeds 10 MiB limit"),f()}return}d+=E,a+=g}),o.stderr?.on("data",g=>{let E=Buffer.byteLength(g,"utf-8");if(d+E>y){if(!m){m=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
1762
1762
|
`)?`
|
|
1763
|
-
`:"")+"system() output exceeds 10 MiB limit",_=new Error("system() output exceeds 10 MiB limit"),f()}return}d+=E,l+=g}),o.on("error",g=>{_||(_=g)}),o.on("close",(g,E)=>{g!==null?(c=g,u=null):(c=null,u=E?String(E):null),f()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function
|
|
1764
|
-
`)return r.endsWith("\r")&&(r=r.slice(0,-1)),r;r+=s}}catch{return null}}function
|
|
1763
|
+
`:"")+"system() output exceeds 10 MiB limit",_=new Error("system() output exceeds 10 MiB limit"),f()}return}d+=E,l+=g}),o.on("error",g=>{_||(_=g)}),o.on("close",(g,E)=>{g!==null?(c=g,u=null):(c=null,u=E?String(E):null),f()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function Bg(t,e=null){if(typeof t!="string")return t??e;let r=t.trim();if(r.length===0)return e;try{return JSON.parse(r)}catch{}let n=r.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(n&&n[1])try{return JSON.parse(n[1].trim())}catch{}let s=r.indexOf("{"),i=r.lastIndexOf("}");if(s!==-1&&i>s)try{return JSON.parse(r.slice(s,i+1))}catch{}let o=r.indexOf("["),a=r.lastIndexOf("]");if(o!==-1&&a>o)try{return JSON.parse(r.slice(o,a+1))}catch{}return e}function Br(t){if(typeof process>"u"||!process.stdin||!process.stdin.isTTY)return null;t!=null&&process.stdout&&typeof process.stdout.write=="function"&&process.stdout.write(String(t));try{let e=Buffer.alloc(1024),r="";for(;;){let n=0;try{n=M.readSync(0,e,0,1,null)}catch{return r.length>0?r:null}if(n===0)return r.length>0?r:null;let s=e.toString("utf-8",0,n);if(s===`
|
|
1764
|
+
`)return r.endsWith("\r")&&(r=r.slice(0,-1)),r;r+=s}}catch{return null}}function Wr(t,e=typeof process<"u"?process.stdin:null,r=typeof process<"u"?process.stdout:null){return new Promise(n=>{if(!e||typeof e.on!="function"){n(null);return}if(e.destroyed||e.readableEnded){n(null);return}if(e.isTTY===!1||typeof process<"u"&&e===process.stdin&&!process.stdin.isTTY){n(null);return}t!=null&&r&&typeof r.write=="function"&&r.write(String(t));let s=ic.createInterface({input:e,output:r,terminal:!!e.isTTY}),i=!1,o=()=>{s.close()};s.question("",a=>{i||(i=!0,o(),n(a))}),s.on("close",()=>{i||(i=!0,n(null))}),s.on("error",()=>{i||(i=!0,o(),n(null))})})}function Zl(t,e=!0,r=","){lc(r);let n=[],s=[],i="",o=!1,a=!1,l=!1;for(let d=0;d<t.length;d++){let m=t[d],h=t[d+1];if(l=!0,o)m==='"'?h==='"'?(i+='"',d++):(o=!1,a=!0):i+=m;else{if(a&&m!==r&&m!=="\r"&&m!==`
|
|
1765
1765
|
`)throw new Error("Invalid CSV: unexpected character after closing quote");if(m==='"'){if(i.length>0)throw new Error("Invalid CSV: quote inside unquoted field");o=!0}else m===r?(a=!1,s.push(i),i=""):m==="\r"?(h===`
|
|
1766
1766
|
`&&d++,s.push(i),n.push(s),s=[],i="",a=!1,l=!1):m===`
|
|
1767
|
-
`?(s.push(i),n.push(s),s=[],i="",a=!1,l=!1):i+=m}}if(o)throw new Error("Invalid CSV: unterminated quoted field");if(l&&(s.push(i),n.push(s)),!e)return n.map(d=>d.map(
|
|
1768
|
-
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o
|
|
1769
|
-
`)}return t.map(n
|
|
1770
|
-
`)}function
|
|
1771
|
-
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}var
|
|
1767
|
+
`?(s.push(i),n.push(s),s=[],i="",a=!1,l=!1):i+=m}}if(o)throw new Error("Invalid CSV: unterminated quoted field");if(l&&(s.push(i),n.push(s)),!e)return n.map(d=>d.map(ec));if(n.length===0)return[];let c=n[0].map(d=>d.trim()),u=[];for(let d=1;d<n.length;d++){let m=n[d],h={};for(let _=0;_<c.length;_++)ct(h,c[_],_<m.length?ec(m[_]):null);u.push(h)}return u}function ec(t){let e=t.trim();if(e==="")return"";if(/^-?\d+$/.test(e)){let r=Number(e);if(!Number.isNaN(r))return r}if(/^-?\d+\.\d+$/.test(e)){let r=Number(e);if(!Number.isNaN(r))return r}return e.toLowerCase()==="true"?!0:e.toLowerCase()==="false"?!1:e.toLowerCase()==="null"?null:t}function tc(t,e=","){if(lc(e),!Array.isArray(t)||t.length===0)return"";let r=t[0];if(Array.isArray(r))return t.map(n=>n.map(s=>Un(s,e)).join(e)).join(`
|
|
1768
|
+
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o=>Un(o,e)).join(e),i=t.map(o=>n.map(a=>Un(Be(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
1769
|
+
`)}return t.map(n=>Un(n,e)).join(`
|
|
1770
|
+
`)}function Un(t,e){let r=t==null?"":String(t);return r===""||r.includes(e)||r.includes('"')||r.includes(`
|
|
1771
|
+
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}var rc={fn:"FN",function:"FN",let:"LET",if:"IF",else:"ELSE",while:"WHILE",for:"FOR",return:"RETURN",break:"BREAK",continue:"CONTINUE",true:"TRUE",false:"FALSE",null:"NULL",parallel:"PARALLEL",sync:"SYNC",import:"IMPORT"},Ur=class{source;length;file;pos=0;line=1;column=1;constructor(e,r){this.source=e,this.length=e.length,this.file=r}tokenize(){let e=[];for(;this.pos<this.length&&(this.skipWhitespaceAndComments(),!(this.pos>=this.length));){let r=this.line,n=this.column,s=this.peek();if(this.isDigit(s)||s==="."&&this.isDigit(this.peekNext())){e.push(this.readNumber(r,n));continue}if(s==='"'||s==="'"){e.push(this.readString(s,r,n));continue}if(s==="<"&&this.peekNext()==="<"){let i=this.tryReadHeredoc(r,n);if(i){e.push(i);continue}}if(this.isAlpha(s)){e.push(this.readIdentifier(r,n));continue}switch(this.advance(),s){case".":e.push({type:"DOT",value:".",line:r,column:n});break;case":":e.push({type:"COLON",value:":",line:r,column:n});break;case"(":e.push({type:"LPAREN",value:"(",line:r,column:n});break;case")":e.push({type:"RPAREN",value:")",line:r,column:n});break;case"{":e.push({type:"LBRACE",value:"{",line:r,column:n});break;case"}":e.push({type:"RBRACE",value:"}",line:r,column:n});break;case"[":e.push({type:"LBRACKET",value:"[",line:r,column:n});break;case"]":e.push({type:"RBRACKET",value:"]",line:r,column:n});break;case",":e.push({type:"COMMA",value:",",line:r,column:n});break;case";":e.push({type:"SEMICOLON",value:";",line:r,column:n});break;case"+":e.push({type:"PLUS",value:"+",line:r,column:n});break;case"-":e.push({type:"MINUS",value:"-",line:r,column:n});break;case"*":e.push({type:"STAR",value:"*",line:r,column:n});break;case"/":e.push({type:"SLASH",value:"/",line:r,column:n});break;case"%":e.push({type:"PERCENT",value:"%",line:r,column:n});break;case"=":this.match("=")?e.push({type:"EQUAL",value:"==",line:r,column:n}):e.push({type:"ASSIGN",value:"=",line:r,column:n});break;case"!":this.match("=")?e.push({type:"NOT_EQUAL",value:"!=",line:r,column:n}):e.push({type:"NOT",value:"!",line:r,column:n});break;case"<":this.match("=")?e.push({type:"LESS_EQUAL",value:"<=",line:r,column:n}):e.push({type:"LESS",value:"<",line:r,column:n});break;case">":this.match("=")?e.push({type:"GREATER_EQUAL",value:">=",line:r,column:n}):e.push({type:"GREATER",value:">",line:r,column:n});break;case"&":if(this.match("&"))e.push({type:"AND",value:"&&",line:r,column:n});else throw new D("Unexpected character '&'. Did you mean '&&'?",r,n,"LEXER",this.file);break;case"|":if(this.match("|"))e.push({type:"OR",value:"||",line:r,column:n});else throw new D("Unexpected character '|'. Did you mean '||'?",r,n,"LEXER",this.file);break;default:throw new D(`Unexpected character: '${s}'`,r,n,"LEXER",this.file)}}return e.push({type:"EOF",value:"",line:this.line,column:this.column}),e}peek(){return this.source[this.pos]||""}peekNext(){return this.source[this.pos+1]||""}advance(){let e=this.source[this.pos++];return e===`
|
|
1772
1772
|
`?(this.line++,this.column=1):this.column++,e}match(e){return this.pos>=this.length||this.source[this.pos]!==e?!1:(this.advance(),!0)}isDigit(e){return e>="0"&&e<="9"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}skipWhitespaceAndComments(){for(;this.pos<this.length;){let e=this.peek();if(e===" "||e===" "||e==="\r"||e===`
|
|
1773
1773
|
`)this.advance();else if(e==="/"&&this.peekNext()==="/"||e==="#")for(;this.pos<this.length&&this.peek()!==`
|
|
1774
1774
|
`;)this.advance();else if(e==="/"&&this.peekNext()==="*"){let r=this.line,n=this.column;this.advance(),this.advance();let s=!1;for(;this.pos<this.length;){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance(),s=!0;break}this.advance()}if(!s)throw new D("Unterminated block comment",r,n,"LEXER",this.file)}else break}}readNumber(e,r){let n="";for(;this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(n+=this.advance();this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();return{type:"NUMBER",value:n,literal:parseFloat(n),line:e,column:r}}readString(e,r,n){this.advance();let s="";for(;this.pos<this.length&&this.peek()!==e;){if(this.peek()===`
|
|
@@ -1779,7 +1779,7 @@ try {
|
|
|
1779
1779
|
`;)c++;let u=this.source.slice(l,c),d=u===`${s};`;if(u===s||d){let _=this.source[c]==="\r"&&this.source[c+1]===`
|
|
1780
1780
|
`?2:this.source[c]===`
|
|
1781
1781
|
`||this.source[c]==="\r"?1:0,T=this.source.slice(a,l),f=s.length+(d?0:_);for(let y=0;y<f;y++)this.advance();return{type:"STRING",value:T,literal:T,line:e,column:r}}let m=this.source[c]==="\r"&&this.source[c+1]===`
|
|
1782
|
-
`?2:c<this.length?1:0,h=c+m-this.pos;for(let _=0;_<h;_++)this.advance()}throw new D(`Unterminated heredoc; expected closing marker '${s}'`,e,r,"LEXER",this.file)}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(Zl,n)?Zl[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:r}}return{type:"IDENTIFIER",value:n,line:e,column:r}}};function Di(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let r of Object.keys(t)){let n=t[r];if(Array.isArray(n))for(let s of n)Di(s,e);else n&&typeof n=="object"&&Di(n,e)}}}var Ur=class{tokens;current=0;file;constructor(e,r){this.tokens=e,this.file=r}parse(){let e=[],r=this.peek();for(;!this.isAtEnd();)e.push(this.parseDeclaration(!0));let n={kind:"Program",statements:e,line:r.line,column:r.column,file:this.file};return this.file&&Di(n,this.file),n}parseDeclaration(e=!1){try{if(this.match("FN"))return this.parseFunctionDecl();if(this.match("LET"))return this.parseVarDecl();if(this.match("IMPORT")){if(!e)throw new D("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.parseImportStmt()}return this.parseStatement()}catch(r){throw r instanceof D?r:new D(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),r=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:r.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),r=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:r.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let r=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:r.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new D("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.match("SYNC")?this.parseSyncStatement():this.match("IF")?this.parseIfStatement():this.match("WHILE")?this.parseWhileStatement():this.match("FOR")?this.parseForStatement():this.match("RETURN")?this.parseReturnStatement():this.match("BREAK")?this.parseBreakStatement():this.match("CONTINUE")?this.parseContinueStatement():this.match("LBRACE")?this.parseBlockBody(this.previous()):this.parseExpressionStatement()}parseSyncStatement(){let e=this.previous(),r=this.parseExpression();if(this.consumeOptionalSemicolon(),r.kind==="AssignExpr")return{kind:"SyncAssignStmt",target:r.target,value:r.value,line:e.line,column:e.column};if(r.kind==="IndexAssignExpr")return{kind:"SyncIndexAssignStmt",target:r.target,index:r.index,value:r.value,line:e.line,column:e.column};if(r.kind==="CallExpr")return{kind:"SyncCallStmt",call:r,line:e.line,column:e.column};throw new D("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:r,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:r,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let r;if(this.match("SEMICOLON"))r=void 0;else if(this.match("LET"))r=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),r={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:r,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),r;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(r=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:r,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:r,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let r=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:r.line,column:r.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:r.line,column:r.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new D("Destructuring assignment target must be an identifier",i.line,i.column,"PARSER",this.file);s.push(i.name)}return{kind:"TupleAssignExpr",targets:s,value:n,line:r.line,column:r.column}}throw new D("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let r=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:r.line,column:r.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let r=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:r.line,column:r.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let r=this.previous(),n=r.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let r=this.previous(),n=r.type==="LESS"?"<":r.type==="LESS_EQUAL"?"<=":r.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let r=this.previous(),n=r.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let r=this.previous(),n=r.type==="STAR"?"*":r.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),r=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:r,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new D("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:r,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let r=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:r,line:e.line,column:e.column}}else if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:r.value,line:r.line,column:r.column},line:r.line,column:r.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let r=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new D("Each task in parallel([...]) must be a direct function call expression",s.line,s.column,"PARSER",this.file);n.push(s)}while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' closing array in 'parallel([ ... ])'"),this.consume("RPAREN","Expected ')' closing 'parallel(...)'"),{kind:"ParallelExpr",tasks:n,line:r.line,column:r.column}}if(this.match("IDENTIFIER"))return{kind:"IdentifierExpr",name:this.previous().value,line:e.line,column:e.column};if(this.match("LPAREN")){let r=this.previous(),n=[],s=!1;if(!this.check("RPAREN"))do if(n.push(this.parseExpression()),this.match("COMMA"))s=!0;else break;while(!this.check("RPAREN")&&!this.isAtEnd());return this.consume("RPAREN","Expected ')' after expression"),n.length===1&&!s?{kind:"GroupingExpr",expression:n[0],line:r.line,column:r.column}:{kind:"TupleExpr",elements:n,line:r.line,column:r.column}}if(this.match("LBRACKET")){let r=[];if(!this.check("RBRACKET"))do r.push(this.parseExpression());while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' after array elements"),{kind:"ArrayExpr",elements:r,line:e.line,column:e.column}}if(this.match("LBRACE")){let r=this.previous(),n=[];if(!this.check("RBRACE"))do{let s="";if(this.match("IDENTIFIER","STRING"))s=this.previous().value;else throw new D("Expected object key (identifier or string)",this.peek().line,this.peek().column,"PARSER",this.file);this.consume("COLON","Expected ':' after object key");let i=this.parseExpression();n.push({key:s,value:i})}while(this.match("COMMA"));return this.consume("RBRACE","Expected '}' after object literal"),{kind:"ObjectExpr",properties:n,line:r.line,column:r.column}}throw new D(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let r of e)if(this.check(r))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,r){if(this.check(e))return this.advance();let n=this.peek();throw new D(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},Cg=`# LMScript Standard Library (std.lms)
|
|
1782
|
+
`?2:c<this.length?1:0,h=c+m-this.pos;for(let _=0;_<h;_++)this.advance()}throw new D(`Unterminated heredoc; expected closing marker '${s}'`,e,r,"LEXER",this.file)}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(rc,n)?rc[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:r}}return{type:"IDENTIFIER",value:n,line:e,column:r}}};function Fi(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let r of Object.keys(t)){let n=t[r];if(Array.isArray(n))for(let s of n)Fi(s,e);else n&&typeof n=="object"&&Fi(n,e)}}}var jr=class{tokens;current=0;file;constructor(e,r){this.tokens=e,this.file=r}parse(){let e=[],r=this.peek();for(;!this.isAtEnd();)e.push(this.parseDeclaration(!0));let n={kind:"Program",statements:e,line:r.line,column:r.column,file:this.file};return this.file&&Fi(n,this.file),n}parseDeclaration(e=!1){try{if(this.match("FN"))return this.parseFunctionDecl();if(this.match("LET"))return this.parseVarDecl();if(this.match("IMPORT")){if(!e)throw new D("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.parseImportStmt()}return this.parseStatement()}catch(r){throw r instanceof D?r:new D(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),r=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:r.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),r=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:r.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let r=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:r.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new D("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.match("SYNC")?this.parseSyncStatement():this.match("IF")?this.parseIfStatement():this.match("WHILE")?this.parseWhileStatement():this.match("FOR")?this.parseForStatement():this.match("RETURN")?this.parseReturnStatement():this.match("BREAK")?this.parseBreakStatement():this.match("CONTINUE")?this.parseContinueStatement():this.match("LBRACE")?this.parseBlockBody(this.previous()):this.parseExpressionStatement()}parseSyncStatement(){let e=this.previous(),r=this.parseExpression();if(this.consumeOptionalSemicolon(),r.kind==="AssignExpr")return{kind:"SyncAssignStmt",target:r.target,value:r.value,line:e.line,column:e.column};if(r.kind==="IndexAssignExpr")return{kind:"SyncIndexAssignStmt",target:r.target,index:r.index,value:r.value,line:e.line,column:e.column};if(r.kind==="CallExpr")return{kind:"SyncCallStmt",call:r,line:e.line,column:e.column};throw new D("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:r,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:r,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let r;if(this.match("SEMICOLON"))r=void 0;else if(this.match("LET"))r=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),r={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:r,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),r;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(r=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:r,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:r,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let r=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:r.line,column:r.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:r.line,column:r.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new D("Destructuring assignment target must be an identifier",i.line,i.column,"PARSER",this.file);s.push(i.name)}return{kind:"TupleAssignExpr",targets:s,value:n,line:r.line,column:r.column}}throw new D("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let r=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:r.line,column:r.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let r=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:r.line,column:r.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let r=this.previous(),n=r.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let r=this.previous(),n=r.type==="LESS"?"<":r.type==="LESS_EQUAL"?"<=":r.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let r=this.previous(),n=r.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let r=this.previous(),n=r.type==="STAR"?"*":r.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),r=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:r,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new D("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:r,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let r=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:r,line:e.line,column:e.column}}else if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:r.value,line:r.line,column:r.column},line:r.line,column:r.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let r=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new D("Each task in parallel([...]) must be a direct function call expression",s.line,s.column,"PARSER",this.file);n.push(s)}while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' closing array in 'parallel([ ... ])'"),this.consume("RPAREN","Expected ')' closing 'parallel(...)'"),{kind:"ParallelExpr",tasks:n,line:r.line,column:r.column}}if(this.match("IDENTIFIER"))return{kind:"IdentifierExpr",name:this.previous().value,line:e.line,column:e.column};if(this.match("LPAREN")){let r=this.previous(),n=[],s=!1;if(!this.check("RPAREN"))do if(n.push(this.parseExpression()),this.match("COMMA"))s=!0;else break;while(!this.check("RPAREN")&&!this.isAtEnd());return this.consume("RPAREN","Expected ')' after expression"),n.length===1&&!s?{kind:"GroupingExpr",expression:n[0],line:r.line,column:r.column}:{kind:"TupleExpr",elements:n,line:r.line,column:r.column}}if(this.match("LBRACKET")){let r=[];if(!this.check("RBRACKET"))do r.push(this.parseExpression());while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' after array elements"),{kind:"ArrayExpr",elements:r,line:e.line,column:e.column}}if(this.match("LBRACE")){let r=this.previous(),n=[];if(!this.check("RBRACE"))do{let s="";if(this.match("IDENTIFIER","STRING"))s=this.previous().value;else throw new D("Expected object key (identifier or string)",this.peek().line,this.peek().column,"PARSER",this.file);this.consume("COLON","Expected ':' after object key");let i=this.parseExpression();n.push({key:s,value:i})}while(this.match("COMMA"));return this.consume("RBRACE","Expected '}' after object literal"),{kind:"ObjectExpr",properties:n,line:r.line,column:r.column}}throw new D(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let r of e)if(this.check(r))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,r){if(this.check(e))return this.advance();let n=this.peek();throw new D(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},Wg=`# LMScript Standard Library (std.lms)
|
|
1783
1783
|
|
|
1784
1784
|
# String Utilities
|
|
1785
1785
|
fn is_blank(s) {
|
|
@@ -1874,22 +1874,22 @@ fn clamp(val, low, high) {
|
|
|
1874
1874
|
}
|
|
1875
1875
|
return val;
|
|
1876
1876
|
}
|
|
1877
|
-
`,Li=null;function Og(){if(!Li){let e=new $r(Cg,"<std>").tokenize(),n=new Ur(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);Li=n}return{kind:"Program",statements:[...Li.statements],line:1,column:1,file:"<std>"}}function Dg(t,e={}){let r=e.file||"<main>",n=e.baseDir||(e.file?ae.dirname(ae.resolve(e.file)):process.cwd()),s=new Map,i=new Set;function o(p,f){if(e.moduleResolver)return e.moduleResolver(p,f).path;let y=n;f&&f!=="<main>"&&f!=="<std>"&&(y=ae.dirname(f));let g=ae.resolve(y,p);try{return M.realpathSync(g)}catch{return g}}function a(p,f){let y,g;if(e.moduleResolver){let S=e.moduleResolver(p,f);y=S.path,g=S.source}else{if(y=o(p,f),s.has(y))return s.get(y);if(i.has(y))return{kind:"Program",statements:[],line:1,column:1,file:y};try{g=M.readFileSync(y,"utf-8")}catch(S){throw new D(`Cannot resolve import '${p}': ${S?.message||String(S)}`,1,1,"PARSER",f)}}if(s.has(y))return s.get(y);if(i.has(y))return{kind:"Program",statements:[],line:1,column:1,file:y};i.add(y);let v=new $r(g,y).tokenize(),b=new Ur(v,y).parse();for(let S of b.statements)if(S.kind!=="FunctionDeclStmt"&&S.kind!=="ImportStmt")throw new D(`Library '${y}' cannot contain top-level executable statements; libraries must only declare functions. Found '${S.kind}'.`,S.line,S.column,"CHECKER",y);for(let S of b.statements)S.kind==="ImportStmt"&&a(S.path,y);return i.delete(y),s.set(y,b),b}let c=new $r(t,r).tokenize(),d=new Ur(c,r).parse(),m=r!=="<main>"?o(r):"<main>";s.set(m,d);for(let p of d.statements)p.kind==="ImportStmt"&&a(p.path,r);let h=[];if(!e.noStdlib){let p=Og();for(let f of p.statements)f.kind==="FunctionDeclStmt"&&h.push(f)}for(let[p,f]of s.entries())if(p!==m)for(let y of f.statements)y.kind==="FunctionDeclStmt"&&h.push(y);for(let p of d.statements)p.kind!=="ImportStmt"&&h.push(p);let _={kind:"Program",statements:h,line:d.line,column:d.column,file:r},T=Array.from(s.keys());return{program:_,loadedFiles:T}}var Rt=class{variables=new Set;parent;constructor(e){this.parent=e}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}},Mi=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new Rt;loopDepth=0;inFunction=!1;hasConcurrency=!1;constructor(e,r={}){this.options=r;for(let[n,s]of e.entries())this.hostFunctions.set(n,s),this.functions.set(n,{name:n,paramCount:typeof s.arity=="number"?s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.loopDepth=0,this.inFunction=!1,this.currentScope=new Rt,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,n]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof n.arity=="number"?n.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);for(let r of e.statements)this.checkStmt(r);return this.diagnostics}addError(e,r,n,s){this.diagnostics.push({message:e,line:r,column:n,severity:"error",file:s})}collectFunction(e){if(this.functions.has(e.name)){let n=this.functions.get(e.name);if(n.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(n.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=n.file?`${n.file}:${n.line}`:`line ${n.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let r=new Set;for(let n of e.params)r.has(n)&&this.addError(`Duplicate parameter name '${n}' in function '${e.name}'`,e.line,e.column,e.file),r.add(n);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"ImportStmt":break;case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let r=this.currentScope,n=this.inFunction;this.inFunction=!0,this.currentScope=new Rt(r);for(let s of e.params)this.currentScope.define(s);for(let s of e.body.statements)this.checkStmt(s);this.inFunction=n,this.currentScope=r;break}case"VarDeclStmt":{this.currentScope.hasInCurrent(e.name)&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer),this.currentScope.define(e.name);break}case"TupleVarDeclStmt":{this.checkExpr(e.initializer);for(let r of e.names)this.currentScope.hasInCurrent(r)&&this.addError(`Variable '${r}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(r);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForStmt":{let r=this.currentScope;this.currentScope=new Rt(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),e.update&&this.checkExpr(e.update),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let r=this.currentScope;this.currentScope=new Rt(r);for(let n of e.statements)this.checkStmt(n);this.currentScope=r;break}case"SyncAssignStmt":{this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let r=e.call;r.args.length===0&&this.addError(`Synchronized call '${r.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let n=this.hostFunctions.get(r.callee);(!n||!n.isContainerMutation)&&this.addError(`Synchronized call '${r.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr);break}}}checkReadPath(e){let r=e.args[0];for(;r.kind==="GroupingExpr";)r=r.expression;if(r.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof r.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!M.statSync(r.value).isFile())throw new Error("path is not a regular file");M.accessSync(r.value,M.constants.R_OK)}catch(n){this.addError(`Cannot read file ${JSON.stringify(r.value)}: ${n instanceof Error?n.message:String(n)}`,e.line,e.column,e.file)}}checkExpr(e){switch(e.kind){case"LiteralExpr":break;case"IdentifierExpr":{!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.checkExpr(e.value),this.currentScope.resolve(e.target)||this.currentScope.define(e.target);break}case"TupleAssignExpr":{this.checkExpr(e.value);for(let r of e.targets)this.currentScope.resolve(r)||this.currentScope.define(r);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(`Call to undefined function '${e.callee}'`,e.line,e.column,e.file);let n=this.hostFunctions.get(e.callee),s=n?.arity;typeof s=="object"&&(e.args.length<s.min||e.args.length>(s.max??1/0))&&this.addError(`Function '${e.callee}' expects ${s.min}..${s.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),this.options.checkFiles&&n?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let i of e.args)this.checkExpr(i);break}}}},Qt=class{value;constructor(e){this.value=e}},at=class{},lt=class{},Zt=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Pe=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionBoundary;constructor(e,r=!1){this.parent=e,this.isFunctionBoundary=r}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,r){this.values.set(e,r)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}set(e,r){if(this.values.has(e)){this.values.set(e,r);return}if(!this.isFunctionBoundary&&this.parent?.has(e)){this.parent.set(e,r);return}this.values.set(e,r)}},Hn=class{holderTaskId;depth=0;waiters=[];acquire(e=0,r=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((n,s)=>{let i;r>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${r}ms (possible deadlock)`)))},r));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,n()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,r=0,n=1e4){await this.acquire(r,n);try{return await e()}finally{this.release()}}},Fi=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let r=this.bindingLocks.get(e);return r||(r=new Hn,this.bindingLocks.set(e,r)),r}getObjectLock(e){let r=this.objectLocks.get(e);return r||(r=new Hn,this.objectLocks.set(e,r)),r}},Bn=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new Fi;isAsync;nextTaskId=1;initialGlobals;callDepth=0;asyncCallDepth=new Map;recordedErrors=[];constructor(e,r=o=>console.log(o),n=!1,s,i){this.stdout=r,this.stderr=i,this.isAsync=n,this.initialGlobals=s,this.globalEnv=new Pe,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(f),f},description:"Prints formatted values to output log",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(f),f},description:"Prints line to output log",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(p,...f)=>{let y=jr(p,f);return this.stdout(y),y},description:"Formats a template using %s/%d/%f/%% substitution and prints it",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stderr?this.stderr(`error: ${f}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${f}
|
|
1878
|
-
`):console.error(`error: ${f}`),this.recordedErrors.push(f),f},description:"Prints error message to stderr and records it for execution error summary",isDefault:!0});let u=e.get("system");(!u||u.isDefault)&&this.hostFunctions.set("system",{fn:(p,f=6e4)=>{if(!Number.isSafeInteger(f)||f<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsync?
|
|
1877
|
+
`,Oi=null;function Xg(){if(!Oi){let e=new Ur(Wg,"<std>").tokenize(),n=new jr(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);Oi=n}return{kind:"Program",statements:[...Oi.statements],line:1,column:1,file:"<std>"}}function qg(t,e={}){let r=e.file||"<main>",n=e.baseDir||(e.file?ae.dirname(ae.resolve(e.file)):process.cwd()),s=new Map,i=new Set;function o(p,f){if(e.moduleResolver)return e.moduleResolver(p,f).path;let y=n;f&&f!=="<main>"&&f!=="<std>"&&(y=ae.dirname(f));let g=ae.resolve(y,p);try{return M.realpathSync(g)}catch{return g}}function a(p,f){let y,g;if(e.moduleResolver){let S=e.moduleResolver(p,f);y=S.path,g=S.source}else{if(y=o(p,f),s.has(y))return s.get(y);if(i.has(y))return{kind:"Program",statements:[],line:1,column:1,file:y};try{g=M.readFileSync(y,"utf-8")}catch(S){throw new D(`Cannot resolve import '${p}': ${S?.message||String(S)}`,1,1,"PARSER",f)}}if(s.has(y))return s.get(y);if(i.has(y))return{kind:"Program",statements:[],line:1,column:1,file:y};i.add(y);let v=new Ur(g,y).tokenize(),b=new jr(v,y).parse();for(let S of b.statements)if(S.kind!=="FunctionDeclStmt"&&S.kind!=="ImportStmt")throw new D(`Library '${y}' cannot contain top-level executable statements; libraries must only declare functions. Found '${S.kind}'.`,S.line,S.column,"CHECKER",y);for(let S of b.statements)S.kind==="ImportStmt"&&a(S.path,y);return i.delete(y),s.set(y,b),b}let c=new Ur(t,r).tokenize(),d=new jr(c,r).parse(),m=r!=="<main>"?o(r):"<main>";s.set(m,d);for(let p of d.statements)p.kind==="ImportStmt"&&a(p.path,r);let h=[];if(!e.noStdlib){let p=Xg();for(let f of p.statements)f.kind==="FunctionDeclStmt"&&h.push(f)}for(let[p,f]of s.entries())if(p!==m)for(let y of f.statements)y.kind==="FunctionDeclStmt"&&h.push(y);for(let p of d.statements)p.kind!=="ImportStmt"&&h.push(p);let _={kind:"Program",statements:h,line:d.line,column:d.column,file:r},T=Array.from(s.keys());return{program:_,loadedFiles:T}}var Rt=class{variables=new Set;parent;constructor(e){this.parent=e}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}},Pi=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new Rt;loopDepth=0;inFunction=!1;hasConcurrency=!1;constructor(e,r={}){this.options=r;for(let[n,s]of e.entries())this.hostFunctions.set(n,s),this.functions.set(n,{name:n,paramCount:typeof s.arity=="number"?s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.loopDepth=0,this.inFunction=!1,this.currentScope=new Rt,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,n]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof n.arity=="number"?n.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);for(let r of e.statements)this.checkStmt(r);return this.diagnostics}addError(e,r,n,s){this.diagnostics.push({message:e,line:r,column:n,severity:"error",file:s})}collectFunction(e){if(this.functions.has(e.name)){let n=this.functions.get(e.name);if(n.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(n.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=n.file?`${n.file}:${n.line}`:`line ${n.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let r=new Set;for(let n of e.params)r.has(n)&&this.addError(`Duplicate parameter name '${n}' in function '${e.name}'`,e.line,e.column,e.file),r.add(n);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"ImportStmt":break;case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let r=this.currentScope,n=this.inFunction;this.inFunction=!0,this.currentScope=new Rt(r);for(let s of e.params)this.currentScope.define(s);for(let s of e.body.statements)this.checkStmt(s);this.inFunction=n,this.currentScope=r;break}case"VarDeclStmt":{this.currentScope.hasInCurrent(e.name)&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer),this.currentScope.define(e.name);break}case"TupleVarDeclStmt":{this.checkExpr(e.initializer);for(let r of e.names)this.currentScope.hasInCurrent(r)&&this.addError(`Variable '${r}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(r);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForStmt":{let r=this.currentScope;this.currentScope=new Rt(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),e.update&&this.checkExpr(e.update),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let r=this.currentScope;this.currentScope=new Rt(r);for(let n of e.statements)this.checkStmt(n);this.currentScope=r;break}case"SyncAssignStmt":{this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let r=e.call;r.args.length===0&&this.addError(`Synchronized call '${r.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let n=this.hostFunctions.get(r.callee);(!n||!n.isContainerMutation)&&this.addError(`Synchronized call '${r.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr);break}}}checkReadPath(e){let r=e.args[0];for(;r.kind==="GroupingExpr";)r=r.expression;if(r.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof r.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!M.statSync(r.value).isFile())throw new Error("path is not a regular file");M.accessSync(r.value,M.constants.R_OK)}catch(n){this.addError(`Cannot read file ${JSON.stringify(r.value)}: ${n instanceof Error?n.message:String(n)}`,e.line,e.column,e.file)}}checkExpr(e){switch(e.kind){case"LiteralExpr":break;case"IdentifierExpr":{!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.checkExpr(e.value),this.currentScope.resolve(e.target)||this.currentScope.define(e.target);break}case"TupleAssignExpr":{this.checkExpr(e.value);for(let r of e.targets)this.currentScope.resolve(r)||this.currentScope.define(r);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(`Call to undefined function '${e.callee}'`,e.line,e.column,e.file);let n=this.hostFunctions.get(e.callee),s=n?.arity;typeof s=="object"&&(e.args.length<s.min||e.args.length>(s.max??1/0))&&this.addError(`Function '${e.callee}' expects ${s.min}..${s.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),this.options.checkFiles&&n?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let i of e.args)this.checkExpr(i);break}}}},Zt=class{value;constructor(e){this.value=e}},at=class{},lt=class{},er=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Pe=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionBoundary;constructor(e,r=!1){this.parent=e,this.isFunctionBoundary=r}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,r){this.values.set(e,r)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}set(e,r){if(this.values.has(e)){this.values.set(e,r);return}if(!this.isFunctionBoundary&&this.parent?.has(e)){this.parent.set(e,r);return}this.values.set(e,r)}},Bn=class{holderTaskId;depth=0;waiters=[];acquire(e=0,r=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((n,s)=>{let i;r>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${r}ms (possible deadlock)`)))},r));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,n()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,r=0,n=1e4){await this.acquire(r,n);try{return await e()}finally{this.release()}}},$i=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let r=this.bindingLocks.get(e);return r||(r=new Bn,this.bindingLocks.set(e,r)),r}getObjectLock(e){let r=this.objectLocks.get(e);return r||(r=new Bn,this.objectLocks.set(e,r)),r}},Wn=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new $i;isAsync;nextTaskId=1;initialGlobals;callDepth=0;asyncCallDepth=new Map;recordedErrors=[];constructor(e,r=o=>console.log(o),n=!1,s,i){this.stdout=r,this.stderr=i,this.isAsync=n,this.initialGlobals=s,this.globalEnv=new Pe,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(f),f},description:"Prints formatted values to output log",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(f),f},description:"Prints line to output log",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(p,...f)=>{let y=Hr(p,f);return this.stdout(y),y},description:"Formats a template using %s/%d/%f/%% substitution and prints it",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stderr?this.stderr(`error: ${f}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${f}
|
|
1878
|
+
`):console.error(`error: ${f}`),this.recordedErrors.push(f),f},description:"Prints error message to stderr and records it for execution error summary",isDefault:!0});let u=e.get("system");(!u||u.isDefault)&&this.hostFunctions.set("system",{fn:(p,f=6e4)=>{if(!Number.isSafeInteger(f)||f<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsync?mc(p,f):uc(p,f)},arity:{min:1,max:2},description:"Executes shell command or argv array directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",isDefault:!0});let d=e.get("prompt_human");(!d||d.isDefault)&&this.hostFunctions.set("prompt_human",{fn:p=>this.isAsync?Wr(p):Br(p),arity:{min:0,max:1},description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",isDefault:!0});let m=e.get("shell_quote");(!m||m.isDefault)&&this.hostFunctions.set("shell_quote",{fn:p=>dc(p),arity:1,description:"Quotes string safely for POSIX shell command execution",isDefault:!0});let h=e.get("run_script");(!h||h.isDefault)&&this.hostFunctions.set("run_script",{fn:(p,f=[])=>{let y=ae.resolve(String(p));if(!M.existsSync(y))throw new Error(`run_script: file not found: '${y}'`);let g=M.readFileSync(y,"utf-8"),E=Array.isArray(f)?f.map(String):[],v=new Ze;for(let[w,b]of this.hostFunctions)v.hasFunction(w)?b.isDefault||v.registerFunction(w,b.fn,b.arity,{description:b.description,allowOverwrite:!0},!1,b.isContainerMutation):v.registerFunction(w,b.fn,b.arity,b.description,b.isDefault,b.isContainerMutation);if(v.setGlobal("args",[...E]),v.setGlobal("ARGV",[y,...E]),this.isAsync)return(async()=>{let w=await v.runAsync(g,{file:y}),b=w.output.join(`
|
|
1879
1879
|
`)+(w.output.length>0?`
|
|
1880
1880
|
`:""),S=w.exitCode!==void 0?w.exitCode:w.success?0:1,I={success:w.success&&S===0,stdout:b,output:[...w.output],value:w.value,exit_code:S,code:S,errors:w.errors??[]};return I.toString=()=>b,I})();{let w=v.run(g,{file:y}),b=w.output.join(`
|
|
1881
1881
|
`)+(w.output.length>0?`
|
|
1882
|
-
`:""),S=w.exitCode!==void 0?w.exitCode:w.success?0:1,I={success:w.success&&S===0,stdout:b,output:[...w.output],value:w.value,exit_code:S,code:S,errors:w.errors??[]};return I.toString=()=>b,I}},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 _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:p=>this.isAsync?Rg(p):oc(p),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let T=e.get("sleep");(!T||T.isDefault)&&this.hostFunctions.set("sleep",{fn:p=>{if(typeof p!="number"||!Number.isFinite(p)||p<0)throw new Error("sleep() duration must be a non-negative finite number");if(p>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(y=>setTimeout(y,p));let f=Date.now()+p;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Pe,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 Pe(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 D(`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 D("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 at)break;if(s instanceof lt)continue;throw s}}return}case"ForStmt":{let n=new Pe(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 D("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 at)break;if(!(i instanceof lt))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new Qt(n)}case"BreakStmt":throw new at;case"ContinueStmt":throw new lt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new D("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new D("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,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 D(`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),ct(n,s,i),i;throw new D("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,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)ct(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 D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:Be(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new D(`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 D("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 D(`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 Zt)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>Pn)throw this.callDepth--,new D(`Execution fuel exhausted: maximum function call depth exceeded (${Pn})`,s,i,"RUNTIME",o);let l=new Pe(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 Qt)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 ve||l?.name==="LMScriptExit"||l?.isControlFlow?l:new D(`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 D(`'${e}' is not a function`,s,i,"RUNTIME",o):new D(`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 Zt(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Pe,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 Pe(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 D(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;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 D("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 at)break;if(i instanceof lt)continue;throw i}}return}case"ForStmt":{let s=new Pe(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 D("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 at)break;if(!(o instanceof lt))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 Qt(s)}case"BreakStmt":throw new at;case"ContinueStmt":throw new lt;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new D(`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 D("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),ct(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new D("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new D(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new D("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],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 D(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;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),ct(s,i,o),o;throw new D("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,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)ct(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 u=this.nextTaskId++;return this.asyncCallDepth.set(u,s),await this.evalExprAsync(c,r,u)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:Be(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 D(`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 D("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new D(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,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),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>Pn)throw this.asyncCallDepth.set(o,u-1),new D(`Execution fuel exhausted: maximum function call depth exceeded (${Pn})`,s,i,"RUNTIME",a);let d=new Pe(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)d.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,d,o)}catch(m){if(m instanceof Qt)return m.value;throw m}finally{this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let u=c.fn(...r);return u instanceof Promise?await u:u}catch(u){throw u instanceof ve||u?.name==="LMScriptExit"||u?.isControlFlow?u:new D(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new D(`'${l}' is not a function`,s,i,"RUNTIME",a):new D(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},Mg=[{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;"}],Fg=[{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_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"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, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"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");'}],Pg=[{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 $g(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 ec(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 jr(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 Ze=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 Mg)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Fg)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Pg)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=>M.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>M.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=M.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
1882
|
+
`:""),S=w.exitCode!==void 0?w.exitCode:w.success?0:1,I={success:w.success&&S===0,stdout:b,output:[...w.output],value:w.value,exit_code:S,code:S,errors:w.errors??[]};return I.toString=()=>b,I}},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 _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:p=>this.isAsync?Hg(p):cc(p),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let T=e.get("sleep");(!T||T.isDefault)&&this.hostFunctions.set("sleep",{fn:p=>{if(typeof p!="number"||!Number.isFinite(p)||p<0)throw new Error("sleep() duration must be a non-negative finite number");if(p>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(y=>setTimeout(y,p));let f=Date.now()+p;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Pe,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 Pe(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 D(`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 D("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 at)break;if(s instanceof lt)continue;throw s}}return}case"ForStmt":{let n=new Pe(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 D("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 at)break;if(!(i instanceof lt))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new Zt(n)}case"BreakStmt":throw new at;case"ContinueStmt":throw new lt;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new D("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new D("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,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 D(`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),ct(n,s,i),i;throw new D("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,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)ct(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 D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:Be(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new D(`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 D("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 D(`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 er)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>$n)throw this.callDepth--,new D(`Execution fuel exhausted: maximum function call depth exceeded (${$n})`,s,i,"RUNTIME",o);let l=new Pe(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 Zt)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 ve||l?.name==="LMScriptExit"||l?.isControlFlow?l:new D(`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 D(`'${e}' is not a function`,s,i,"RUNTIME",o):new D(`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 er(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Pe,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 Pe(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 D(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;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 D("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 at)break;if(i instanceof lt)continue;throw i}}return}case"ForStmt":{let s=new Pe(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 D("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 at)break;if(!(o instanceof lt))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 Zt(s)}case"BreakStmt":throw new at;case"ContinueStmt":throw new lt;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new D(`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 D("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),ct(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new D("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new D(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new D("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],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 D(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;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),ct(s,i,o),o;throw new D("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,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)ct(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 u=this.nextTaskId++;return this.asyncCallDepth.set(u,s),await this.evalExprAsync(c,r,u)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new D("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:Be(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 D(`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 D("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new D(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,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),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>$n)throw this.asyncCallDepth.set(o,u-1),new D(`Execution fuel exhausted: maximum function call depth exceeded (${$n})`,s,i,"RUNTIME",a);let d=new Pe(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)d.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,d,o)}catch(m){if(m instanceof Zt)return m.value;throw m}finally{this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let u=c.fn(...r);return u instanceof Promise?await u:u}catch(u){throw u instanceof ve||u?.name==="LMScriptExit"||u?.isControlFlow?u:new D(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new D(`'${l}' is not a function`,s,i,"RUNTIME",a):new D(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},Gg=[{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;"}],Jg=[{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_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"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, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"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");'}],Kg=[{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 Vg(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 nc(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 Hr(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 Ze=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 Gg)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Jg)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of Kg)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=>M.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>M.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=M.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
1883
1883
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
1884
1884
|
`)&&(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(`
|
|
1885
1885
|
`)+`
|
|
1886
|
-
`;return M.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(M.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 M.readdirSync(ae.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>(M.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>(M.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,r)=>(M.writeFileSync(e,String(r),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,r)=>(M.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=M.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>(M.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=M.readFileSync(e,"utf-8");return
|
|
1886
|
+
`;return M.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(M.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 M.readdirSync(ae.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>(M.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>(M.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,r)=>(M.writeFileSync(e,String(r),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,r)=>(M.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=M.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>(M.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=M.readFileSync(e,"utf-8");return Zl(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=",")=>(M.writeFileSync(e,tc(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",Zl,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",tc,{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(jg(),`lmscript-${Ug()}`),r=M.openSync(e,"wx",384);return M.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>M.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new ve(Number(e))},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>M.existsSync(e)?(M.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>M.existsSync(e)?(M.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,r=!0)=>(M.mkdirSync(e,{recursive:!!r}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,r=!1)=>M.existsSync(e)?(r?M.rmSync(e,{recursive:!0,force:!0}):M.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)=>(M.copyFileSync(e,r),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,r)=>(M.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?mc(e,r):uc(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(!M.existsSync(n))throw new Error(`run_script: file not found: '${n}'`);let s=M.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(`
|
|
1887
1887
|
`)+(a.output.length>0?`
|
|
1888
1888
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,u={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return u.toString=()=>l,u})();{let a=o.run(s,{file:n}),l=a.output.join(`
|
|
1889
1889
|
`)+(a.output.length>0?`
|
|
1890
1890
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,u={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return u.toString=()=>l,u}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
|
|
1891
|
-
`):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=>
|
|
1892
|
-
`):console.error(`error: ${String(r)}`),new ve(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];(Be(i,a)==null||typeof Be(i,a)!="object")&&ct(i,a,{}),i=Be(i,a)}return s.length>0&&ct(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=>Be(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Be(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&&Be(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=jr(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/).map(a=>a.trim()).filter(a=>a.length>0);if(r.length===0)return null;let n=a=>a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER",s=r[r.length-1],i=r.length>1?r[r.length-2]:null,o=r.length>2?r[r.length-3]:null;return n(s)?i&&n(i)&&i!==s?null:s:i&&n(i)?o&&n(o)&&o!==i?null:i: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 Zt,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>ac(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 u=n.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=n.slice(l+1,u);if(d==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<r.length?a(r[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>jr(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)=>ec(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>ec(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 Zt?"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,u=typeof s=="object"?s.doc:void 0,d=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,h=this.functionOriginModule.get(e);if(h&&h!==m&&!d)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${h}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:u}),u?this.functionDocs.set(e,{...u,module:u.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:$g(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}=Dg(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new Mi(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof D?{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 Bn(this.hostFunctions,d=>n.push(d),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let u=l.getRecordedErrors();return this.lastRecordedErrors=u,{success:!0,value:c,diagnostics:i,output:n,errors:u}}catch(c){let u=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=u,c instanceof ve||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let _=typeof c.exitCode=="number"?c.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:i,output:n,errors:u}}let d=c instanceof D?c.line:1,m=c instanceof D?c.column:1,h=c instanceof D&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:d,column:m,severity:"error",file:h}],output:n,errors:u}}}async runAsync(e,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 Bn(this.hostFunctions,u=>n.push(u),!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 ve||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let h=typeof l.exitCode=="number"?l.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:i,output:n,errors:c}}let u=l instanceof D?l.line:1,d=l instanceof D?l.column:1,m=l instanceof D&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:u,column:d,severity:"error",file:m}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function Ug(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
1891
|
+
`):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=>cc(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?Wr(e):Br(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)=>Bg(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=$r(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,n="")=>{let s=$r(e,r);return s==null?n:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,r,n=0)=>{let s=$r(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=$r(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,n=[])=>{let s=$r(e,r);return Array.isArray(s)?s:n},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",(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)}
|
|
1892
|
+
`):console.error(`error: ${String(r)}`),new ve(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];(Be(i,a)==null||typeof Be(i,a)!="object")&&ct(i,a,{}),i=Be(i,a)}return s.length>0&&ct(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=>Be(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Be(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&&Be(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=Hr(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/).map(a=>a.trim()).filter(a=>a.length>0);if(r.length===0)return null;let n=a=>a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER",s=r[r.length-1],i=r.length>1?r[r.length-2]:null,o=r.length>2?r[r.length-3]:null;return n(s)?i&&n(i)&&i!==s?null:s:i&&n(i)?o&&n(o)&&o!==i?null:i: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 er,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>dc(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 u=n.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=n.slice(l+1,u);if(d==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<r.length?a(r[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>Hr(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)=>nc(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>nc(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 er?"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,u=typeof s=="object"?s.doc:void 0,d=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,h=this.functionOriginModule.get(e);if(h&&h!==m&&!d)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${h}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:u}),u?this.functionDocs.set(e,{...u,module:u.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:Vg(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}=qg(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new Pi(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof D?{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 Wn(this.hostFunctions,d=>n.push(d),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let u=l.getRecordedErrors();return this.lastRecordedErrors=u,{success:!0,value:c,diagnostics:i,output:n,errors:u}}catch(c){let u=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=u,c instanceof ve||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let _=typeof c.exitCode=="number"?c.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:i,output:n,errors:u}}let d=c instanceof D?c.line:1,m=c instanceof D?c.column:1,h=c instanceof D&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:d,column:m,severity:"error",file:h}],output:n,errors:u}}}async runAsync(e,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 Wn(this.hostFunctions,u=>n.push(u),!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 ve||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let h=typeof l.exitCode=="number"?l.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:i,output:n,errors:c}}let u=l instanceof D?l.line:1,d=l instanceof D?l.column:1,m=l instanceof D&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:u,column:d,severity:"error",file:m}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function Yg(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
1893
1893
|
`);let t=new Ze,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=t.run(`
|
|
1894
1894
|
fn factorial(n) {
|
|
1895
1895
|
if (n <= 1) {
|
|
@@ -1946,7 +1946,7 @@ fn clamp(val, low, high) {
|
|
|
1946
1946
|
|
|
1947
1947
|
undefinedFunctionCall(); // ERROR 4: undefined function
|
|
1948
1948
|
base64Encode("hello", "extra_arg"); // ERROR 5: arity mismatch
|
|
1949
|
-
`,a=t.run(o);console.log(" Executed successfully?",a.success),console.log(" Formatted visual diagnostics caught BEFORE execution:");for(let y of a.diagnostics)console.log(" "+
|
|
1949
|
+
`,a=t.run(o);console.log(" Executed successfully?",a.success),console.log(" Formatted visual diagnostics caught BEFORE execution:");for(let y of a.diagnostics)console.log(" "+ac(y,o).split(`
|
|
1950
1950
|
`).join(`
|
|
1951
1951
|
`));!a.success&&a.diagnostics.length===5?console.log(` -> Passed! (All 5 static errors caught upfront with visual carets)
|
|
1952
1952
|
`):(console.error(" -> Failed! Expected 5 diagnostics, got",a.diagnostics.length),e=!1),console.log("Test Suite 4: Forward Function Declarations & Mutual Recursion");let c=t.run(`
|
|
@@ -2116,97 +2116,97 @@ fn clamp(val, low, high) {
|
|
|
2116
2116
|
assert(res1 == "a" && res2 == "b" && res3 == "c", "parallel results must match return values");
|
|
2117
2117
|
`);return f.success?(console.log(f.output.map(y=>" [out] "+y).join(`
|
|
2118
2118
|
`)),console.log(` -> Passed!
|
|
2119
|
-
`)):(console.error(" -> Failed:",f.diagnostics),e=!1),e}async function
|
|
2119
|
+
`)):(console.error(" -> Failed:",f.diagnostics),e=!1),e}async function zg(){let t=process.argv.slice(2);if(t.length===0||t.length===1&&t[0]==="--test"){await Yg()||(process.exitCode=1);return}let e="Usage: lmscript.ts [--check|--dry-run|--lint] [--check-files] <file> | [check options] -e <source> | --test | --help";if(t.length===1&&t[0]==="--help"){console.log(e);return}let r=!1,n=!1;for(;["--check","--dry-run","--lint","--check-files"].includes(t[0]);)r=!0,t.shift()==="--check-files"&&(n=!0);let s=t[0]==="-e";if(s?t.length!==2:t.length!==1||t[0].startsWith("-")){console.error(e),process.exitCode=1;return}try{let i=s?void 0:ae.resolve(t[0]),o=s?t[1]:M.readFileSync(i,"utf-8"),a=new Ze,l=r?a.scanAndCheck(o,{checkFiles:n,file:i}):await a.runAsync(o,{file:i});if("output"in l)for(let c of l.output)console.log(c);for(let c of l.diagnostics)console.error(ac(c,o));l.diagnostics.some(c=>c.severity==="error")&&(process.exitCode=1)}catch(i){console.error(`Execution failed: ${i instanceof Error?i.message:String(i)}`),process.exitCode=1}}var sc=ae.basename(oc(import.meta.url));(sc==="lmscript.ts"||sc==="lmscript.js")&&process.argv[1]&&M.existsSync(process.argv[1])&&M.realpathSync(oc(import.meta.url))===M.realpathSync(ae.resolve(process.argv[1]))&&zg();import{readFileSync as lk,rmSync as ck}from"node:fs";import{createInterface as dk}from"node:readline";Lt();et();ts();function Kc(t){let e=Gc(t.registry,t.fromTeamfile);if(e===void 0)return or(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!Jc(e,t.fromAlias))return or(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Gc(t.registry,t.toTeamfile);return r===void 0?or(`target team is not registered in policy graph: ${t.toTeamfile}`):Jc(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?or(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?or(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:or(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Gc(t,e){return t.teams.find(r=>r.teamfile===e)}function Jc(t,e){return t.aliases.some(r=>r===e)}function or(t){return{allowed:!1,outOfPolicy:!0,reason:t}}qr();rs();z();yr();Ft();Lt();fr();Ft();function qE(t,e){if(wd(e)!=="dead")return null;let r=`holder process verified not alive; reconciled to aborted (invocation #${e.id}, holder pid ${e.holder_pid??"unknown"} on ${e.holder_host??"unknown"})`;return t.abortTrackedInvocationAndTerminalizeMessage(e.id,{holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat_at:e.last_heartbeat_at},r)}function _s(t,e,r){let n=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
2120
2120
|
FROM tracked_invocation
|
|
2121
2121
|
WHERE target_teamfile = ?
|
|
2122
2122
|
AND target_alias = ?
|
|
2123
|
-
AND status = 'running'`,e,r),s=0;for(let i of n)
|
|
2123
|
+
AND status = 'running'`,e,r),s=0;for(let i of n)qE(t,i)!==null&&(s+=1);return s}z();fi();Lt();var lp=36e5;function eb(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return lp;let r=Number(e);return!Number.isFinite(r)||r<=0?lp:r}async function tb(t,e,r){try{let n=tt(e,r,t),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let c=await ap(s);if(c.length!==1)return null;i=c[0]}let o=await Nr(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function cp(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??eb(),o=await tb(t,r,n),a=o!==null&&o>=i;return a&&N({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}Mt();var dp=zl(ho(),1);function rb(t){return t===null?null:Ee(t)?"live":"dead"}function ul(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:rb(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function nb(t){return(0,dp.formatDuration)(t)}function ml(t){let e=[];return t.idle_ms!==null&&e.push(`active ${nb(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}pi();Je();Qr();qr();function hi(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
2124
2124
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
2125
|
-
Consulted ${
|
|
2126
|
-
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function
|
|
2127
|
-
`)}function
|
|
2128
|
-
`});let y=t.env??process.env,g=await j(r,k=>k.getRootTeam(p)?.name??null);g!==null&&(y.LMBEE_TEAM_NAME=g),i=await sb(r,{receiverTeamfile:h,receiverAlias:m.alias,sender:T,rootTeamfile:p,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:t.prompt,origin:_.origin,parentInvocationId:gr(y.LMCTL_INVOCATION_ID)}),o=lb(r,i),i!==null&&(y.LMCTL_INVOCATION_ID=String(i));try{sr(r,$e(h),h)}catch{}n={root_teamfile:p,sender_teamfile:T?.teamfile??null,sender_alias:T?.alias??null,receiver_teamfile:h,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:_.origin,message_type:t.messageType??null,policy:f};let E=await yp(r,h,m.alias);if(E!==null){let k=xn(E);return qt(i,n,t.prompt,k,"unavailable"),u=fl(k,null),{status:"busy",message:k,teamChatLogId:null}}let v=!1;if(t.heldLease!==void 0){let k=t.heldLease;if(!await j(r,q=>{let V=q.getAgentInflight(h,m.alias);return V===null||V.sender_teamfile!==k.row.sender_teamfile||V.sender_alias!==k.row.sender_alias||V.started_at!==k.row.started_at||V.holder_pid!==process.pid?!1:q.heartbeatAgentInflight(k.row,k.leaseId,new Date().toISOString())})){let q=`bundle lease lost for ${m.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return qt(i,n,t.prompt,q,"unavailable"),u=An(q,null),{status:"error",errorKind:"provider",message:q,teamChatLogId:null,messageId:null}}}else{let k=await tb(r,h,m.alias);if(k.busy){let C=await rb(r,h,m.alias);return C+=await nb(r,h,m.alias),qt(i,n,t.prompt,C,"unavailable"),u=fl(C,null),{status:"busy",message:C,teamChatLogId:null}}v=k.idleReclaim}if(T!==null&&T.teamfile!==h){let k=await j(r,C=>Vc(C,{root:p,sender:T,receiverTeamfile:h,receiverAlias:m.alias,now:new Date}));if(k.stop){let C=Yc(k.chain);return qt(i,n,t.prompt,C,"cycle"),u=An(C,null),{status:"error",errorKind:"cycle",message:C,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let k=await gb(r,{receiver_teamfile:h,receiver_alias:m.alias,sender_teamfile:T?.teamfile??h,sender_alias:T?.alias??"operator",...v?{force:!0,reclaimReason:"session-idle"}:{}});if(!k.acquired){let C=Ep(h,m.alias,k.current);return C+=` ${dl(cl({holderPid:k.current.holder_pid,since:k.current.started_at}))}`,qt(i,n,t.prompt,C,"unavailable"),u=fl(C,null),{status:"busy",message:C,teamChatLogId:null}}s={row:k.lease,leaseId:k.leaseId},a=as(C=>j(r,q=>q.heartbeatAgentInflight(s.row,s.leaseId,C)),{intervalMs:gp,onError:C=>{te()&&xe(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:C instanceof Error?C.message:String(C)}))}})}let w=await mp({sender:T??{teamfile:h,alias:"operator"},receiver:{teamfile:h,alias:m.alias,provider:m.provider,sessionId:m.sessionid,cwd:m.sessiondir,...m.model!==void 0?{model:m.model}:{},...m.effort!==void 0?{effort:m.effort}:{},...m.isLead!==void 0?{isLead:m.isLead}:{}},newMessage:t.prompt,newMessageFrom:T===null?"operator":`${T.teamfile}:${T.alias}`,io:r,permissionMode:t.permissionMode,...t.expectedSession!==void 0?{requireResume:!0}:{},...t.bundleSession!==void 0?{bundleSession:t.bundleSession}:{},env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:k=>e({kind:"delta",chunk:k}),onProgress:k=>e({kind:"progress",alias:m.alias,event:k}),onPromptBuilt:async k=>{d=k,l===null&&(l=await yb(r,{...n,message:k}),l!==null&&(t.onAccepted?.(rt(l)),i!==null&&await ab(r,i,l))),i!==null&&await ob(r,i,k)}});d=w.prompt;let b=w.status==="stalled",S=w.status==="empty",I=null,x=b?`provider stalled${w.stalledAfterMs!==void 0?` after ${w.stalledAfterMs}ms`:""}`:S?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":w.status==="error"?w.error??w.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=b||S||w.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await hp(r,l,{...n,message:d,response:w.receipt,status:R,error_detail:x}),c=!0,I=l):I=await Tb(r,{...n,message:d,response:w.receipt,status:R,error_detail:x});let P=w.status!=="error"?w.warnings:void 0;if(b||S){let k=x;qt(i,n,d,k,"error"),u=An(k,I,w.receipt,P)}else u=cb(w.receipt,I,P);return{status:b?"stalled":S?"empty":"ok",replyText:w.receipt,wroteDelta:w.wroteDelta,teamChatLogId:I,messageId:I===null?null:rt(I),durationMs:w.durationMs}}catch(m){let h=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await hp(r,l,{...n,message:d,response:null,status:"error",error_detail:h}),c=!0),qt(i,n,d,h,"error"),u=An(h,l),{status:"error",errorKind:m instanceof he?"target":"provider",message:h,teamChatLogId:l,messageId:l===null?null:rt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await Eb(r,n,rt(l)),s!==null&&await _b(r,s.row,s.leaseId),i!==null&&await ib(r,i,u??An("chat turn exited without a terminal outcome",null))}}function eb(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function tb(t,e,r){let n=await j(t,i=>(gs(i,e,r),ls(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await j(t,i=>op(i,n,e,r));return{busy:!s,idleReclaim:s}}async function rb(t,e,r){let n=await yp(t,e,r);if(n!==null)return xn(n);let s=await j(t,i=>i.getAgentInflight(e,r));return s!==null?Ep(e,r,s):`${r} is busy; wait and retry`}async function nb(t,e,r){let n=await j(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${dl(cl({holderPid:n.holder_pid,since:n.started_at}))}`}async function sb(t,e){try{return(await j(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:db(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return te()&&xe(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function ib(t,e,r){try{await j(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){te()&&xe(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function ob(t,e,r){try{await j(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){te()&&xe(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function ab(t,e,r){try{await j(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){te()&&xe(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function lb(t,e){if(e===null)return;let r=setInterval(()=>{j(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{te()&&xe(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},gp);return r.unref?.(),r}function _p(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function cb(t,e,r){return{status:"done",result_summary:kn(t),error:null,team_chat_log_id:e,..._p(r)}}function fl(t,e){return{status:"busy",result_summary:kn(t),error:t,team_chat_log_id:e}}function An(t,e,r,n){return{status:"error",result_summary:kn(r===void 0?t:r),error:t,team_chat_log_id:e,..._p(n)}}function kn(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function db(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function ub(t,e){let r=hi(e,t);if(r.ok)return{sender:gi(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(pi("chat"))}async function mb(t,e){if(e.explicitRoot!==void 0)return await j(t,n=>Xe(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await j(t,n=>Kc(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function fb(t,e){return await j(t,r=>qc({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:pb(r,e.sender.teamfile,e.receiverTeamfile)}))}function pb(t,e,r){return{teams:[e,r].map(s=>hb(s,t))}}function hb(t,e){let r=rr(t,e),n=tr(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function gb(t,e){return await j(t,r=>{let n=te(),s=lr(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:mt(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&xe(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:pp(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&xe(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:pp(s.current)})),{acquired:!1,current:s.current})})}async function yp(t,e,r){return await j(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(ul(o).live)return o;let l=n.getAgentInflight(e,r);if(n.clearTerminalLock(e,r,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&n.clearObservedTerminalAgentInflight(e,r,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=n.getTerminalLock(e,r);return s===null?null:ul(s).live?s:null})}function pp(t){return t===null?null:{sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,holder_pid:t.holder_pid,started_at:t.started_at}}async function _b(t,e,r){try{await j(t,n=>{n.releaseAgentInflight(e,r)})}catch(n){t.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
2129
|
-
`)}}function
|
|
2130
|
-
`),null}}async function
|
|
2131
|
-
`)}}async function
|
|
2132
|
-
`)}}async function
|
|
2133
|
-
`),null}}function qt(t,e,r,n,s){t!==null||e===null||N({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:kn(r)})}function Nn(t){return t.length<=fp?{text:t,truncated:!1}:{text:t.slice(0,fp),truncated:!0}}Lt();et();import{createHash as vI}from"node:crypto";import{accessSync as bI,constants as rh,existsSync as II,readFileSync as Nl,realpathSync as Rl,statSync as xI,writeFileSync as nh}from"node:fs";import{dirname as Yt,resolve as sh}from"node:path";import{spawnSync as xl}from"node:child_process";import{existsSync as Jp,readFileSync as Vp}from"node:fs";import{homedir as Kp}from"node:os";import{resolve as bl}from"node:path";import{mkdirSync as Ap,readFileSync as wb,renameSync as Sb,writeFileSync as vb,existsSync as kp}from"node:fs";import{homedir as bb}from"node:os";import{dirname as Np,join as _i,resolve as yi}from"node:path";import{fileURLToPath as Ib}from"node:url";var xb="https://lmctl.com/dataset/model_list.json",Ab="https://lmctl.com/dataset/aliases.json",kb=1e3,Nb=1e4,Tp=6*60*60*1e3;function Rb(){return _i(bb(),".lmctl","cache","lmprice")}var gl="model_list.json",_l="aliases.json",Rp="meta.json",Lb="model_list.meta.json";function Nr(t,e){return _i(t,e)}function Gt(t){try{return JSON.parse(wb(t,"utf-8"))}catch{return null}}function Lp(t,e){let r=`${t}.tmp-${process.pid}`;vb(r,e),Sb(r,t)}function hl(t){return t===null||typeof t=="number"}function Ei(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.schema_version!==1||!Array.isArray(e.records)||e.records.length===0?!1:e.records.every(r=>{if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.source!="string"||typeof n.source_model_id!="string"||typeof n.pricing!="object"||n.pricing===null)return!1;let s=n.pricing;return hl(s.input_per_1m_tokens)&&hl(s.output_per_1m_tokens)&&hl(s.input_cache_read_per_1m_tokens)})}var Cb=new Set(["established","asserted","unresolved"]);function Ti(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.schema_version!==1||!Array.isArray(e.standards)||!Array.isArray(e.aliases))return!1;let r=e.standards.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.standard_slug=="string"&&(i.catalog_record_id===null||typeof i.catalog_record_id=="string")}),n=e.aliases.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.alias=="string"&&(i.standard_slug===null||typeof i.standard_slug=="string")&&typeof i.evidence=="string"&&Cb.has(i.evidence)});return r&&n}function Ob(t){let e=Gt(Nr(t,Rp)),r={etag:typeof e?.model_list?.etag=="string"?e.model_list.etag:null,last_checked:typeof e?.model_list?.last_checked=="string"?e.model_list.last_checked:null},n={etag:typeof e?.aliases?.etag=="string"?e.aliases.etag:null,last_checked:typeof e?.aliases?.last_checked=="string"?e.aliases.last_checked:null};if(e===null){let s=Gt(Nr(t,Lb));s&&(r.etag=typeof s.etag=="string"?s.etag:null,r.last_checked=typeof s.fetchedAt=="string"?s.fetchedAt:null)}return{model_list:r,aliases:n}}function Db(t){let e=Ob(t),r=Gt(Nr(t,gl)),n=Gt(Nr(t,_l));return{catalog:Ei(r)?r:null,aliases:Ti(n)?n:null,meta:e}}function Mb(t,e){try{Ap(t,{recursive:!0}),Lp(Nr(t,Rp),JSON.stringify(e))}catch{}}function wp(t,e,r){try{Ap(t,{recursive:!0}),Lp(Nr(t,e),JSON.stringify(r))}catch{}}function Fb(t,e){let r=Pb(t),n=r?[yi(r,"data",e)]:[yi(t,"..","..","data",e)];for(let s of n)if(kp(s))return s;return null}function Pb(t){let e=yi(t);for(;;){if(kp(yi(e,"package.json")))return e;let r=Np(e);if(r===e)return null;e=r}}function Sp(t,e,r){let n=r!==void 0?r:Fb(t,e);return n===null?null:Gt(n)}function $b(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Tp;let e=Number(t);return!Number.isFinite(e)||e<0?Tp:e*1e3}function Ub(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function vp(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(kb)});if(!s.ok)return{kind:"failed"};let i=s.headers.get("etag");if(r!==null&&i!==null&&i===n)return{kind:"match"};let o=await t(e,{signal:AbortSignal.timeout(Nb)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}var yl=null;var bp=null;function Cp(t={}){return Object.keys(t).length===0?(bp??=Ip(t),bp):Ip(t)}async function Ip(t){let e=Np(Ib(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:Ub();if(r!==null&&r!==""){let _=Gt(_i(r,gl)),T=Gt(_i(r,_l));if(Ei(_)&&Ti(T)){let p={catalog:_,aliases:T,source:"pinned",generatedAt:_.generated_at??null};return yl=p.generatedAt,p}return xp(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??Rb(),i=t.now??Date.now(),o=t.ttlMs??$b(),a=Db(s),l=(_,T)=>_!==null&&T.last_checked!==null&&i-Date.parse(T.last_checked)<o,c=a.catalog,u=a.aliases,d=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},h=!1;if(!l(c,a.meta.model_list)){let _=await vp(n,xb,c,a.meta.model_list.etag);_.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),h=!0):_.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),h=!0,Ei(_.payload)&&(c=_.payload,_.etag!==null&&(m.model_list.etag=_.etag),wp(s,gl,c),d=!0))}if(!l(u,a.meta.aliases)){let _=await vp(n,Ab,u,a.meta.aliases.etag);_.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),h=!0):_.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),h=!0,Ti(_.payload)&&(u=_.payload,_.etag!==null&&(m.aliases.etag=_.etag),wp(s,_l,u),d=!0))}if((h||d)&&Mb(s,m),c!==null||u!==null){let _={catalog:c,aliases:u,source:d?"network":"cache",generatedAt:c?.generated_at??null};return yl=_.generatedAt,_}return xp(t,e)}function xp(t,e){let r=Sp(e,"price-data.json",t.bundledPath),n=Sp(e,"price-aliases.json",t.bundledAliasesPath),s=Ei(r)?r:null,i=Ti(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return yl=o.generatedAt,o}function Vt(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function Jt(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Vt(r)}function Dp(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Vt(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function jb(t,e){let r=new Set,n=l=>{r.add(Vt(l))},s=t.trim().toLowerCase(),i=null,o=s.indexOf(":");o>0&&!s.slice(0,o).includes("/")&&(i=s.slice(0,o),n(s),s=s.slice(o+1)),n(s);let a=s.slice(s.lastIndexOf("/")+1);n(a);for(let l of e)n(`${l}/${a}`);return i!==null&&n(`${i}/${a}`),[...r]}function Rr(t){let e=n=>!(n.mode!==void 0&&n.mode!==null&&n.mode!=="chat"||t.nonChatName&&t.nonChatName.test(n.source_model_id.toLowerCase())),r=n=>e(n)&&t.family.test(n.source_model_id.toLowerCase());return{firstPartyProviders:t.firstPartyProviders,isChatModel:e,coversRecord:r,normalize:n=>jb(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=Dp(n);return s.some(o=>i.has(o))}}}var Mp=Rr({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),Fp=Rr({vendorPrefixes:["openai"],family:/(^|\/)(gpt-|o\d|chatgpt|ft:gpt)|openai\//,firstPartyProviders:["openai"],nonChatName:/(^|[-/])(tts|transcribe(?:-\w+)?|realtime(?:-\w+)?|search(?:-\w+)*|image(?:-\w+)?|audio(?:-\w+)?|whisper(?:-\w+)?|dall-e(?:-\w+)?|embedding|moderation)(-|$)/}),Pp=Rr({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),$p=Rr({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Up=Rr({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),jp=Rr({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),Hb=/\s*\(([^()]+)\)\s*$/;function Bb(t){let e=t.trim(),r=Hb.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}var Wb={"gemini 3.8 flash":"gemini-3.8-flash","gemini 3.7 flash":"gemini-3.7-flash","gemini 3.6 flash":"gemini-3.6-flash","gemini 3.1 pro":"gemini/gemini-3.1-pro-preview","claude sonnet 4.6":"claude-sonnet-4-6"},Xb=["gemini","google","vertex_ai-language-models","anthropic"],qb={normalize(t){let{model:e}=Bb(t),r=Wb[e.toLowerCase()];return r===void 0?[]:[Vt(r)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let r=Dp(t);return e.some(n=>r.has(n))}},Rn={claude:Mp,codex:Fp,gemini:Pp,agy:qb,kimi:$p,qwen:Up,hermes:jp},Op={claude:Mp.firstPartyProviders,codex:Fp.firstPartyProviders,gemini:Pp.firstPartyProviders,agy:Xb,kimi:$p.firstPartyProviders,qwen:Up.firstPartyProviders,hermes:jp.firstPartyProviders};function Gb(t,e,r){let n=e.trim().toLowerCase(),s=Vt(n);if(r.records.some(o=>o.source_model_id.toLowerCase()===n&&t.matchRow(o,[s])))return!0;let i=t.normalize(e);return i.length>0&&r.records.some(o=>t.matchRow(o,i))}function Jb(t,e,r){let n=[];for(let[s,i]of Object.entries(Rn))s!==r&&Gb(i,t,e)&&n.push(s);return n}function wi(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function Vb(t,e){return t.input_per_1m_tokens===e.input_per_1m_tokens&&t.output_per_1m_tokens===e.output_per_1m_tokens&&t.input_cache_read_per_1m_tokens===e.input_cache_read_per_1m_tokens}function Kb(t){let e=new Map,r=[];for(let n of t){let s=n.source_model_id.toLowerCase(),i=s.lastIndexOf("/"),o=i===-1?"":s.slice(0,i+1),a=i===-1?s:s.slice(i+1),l=`${n.source}:${o}${Vt(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!Vb(c.pricing,n.pricing)){r.push(n);continue}/\d\.\d/.test(c.source_model_id)&&!/\d\.\d/.test(n.source_model_id)&&e.set(l,n)}return[...e.values(),...r]}function Yb(t){return{route:t.record_id??`${t.source}:${t.source_model_id}`,source:t.source,sourceModelId:t.source_model_id,provider:t.provider??null,pricing:t.pricing,estimated:t.source==="manual"}}function Hp(t,e){return t.map(Yb).sort((r,n)=>{let s=wi(r.source)-wi(n.source);if(s!==0)return s;let i=r.provider!==null&&e.includes(r.provider)?0:1,o=n.provider!==null&&e.includes(n.provider)?0:1;return i!==o?i-o:r.sourceModelId.localeCompare(n.sourceModelId)})}function zb(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function Qb(t,e,r){let n=Kb(t),s=Hp(n,r),o=n.find(a=>(a.record_id??`${a.source}:${a.source_model_id}`)===s[0].route)?.context_window?.input_tokens??void 0;return{id:s[0].sourceModelId,normalizedId:e,offers:s,...o!=null?{contextWindow:o}:{}}}function El(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=Qb(t,e,r),s=n.offers.find(zb);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}var Tl=[];function Zb(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function eI(t,e,r){let n=t.standard_slug;if(e===null||e.catalog_record_id===null)return{kind:"known-unpriced",id:n};let s=e.catalog_record_id.toLowerCase(),i=r.records.find(l=>(l.record_id??`${l.source}:${l.source_model_id}`).toLowerCase()===s);if(!i)return{kind:"known-unpriced",id:n};let o=Jt(i),a=r.records.filter(l=>Jt(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:El(a,o,Tl)}function tI(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let T=[e.trim().toLowerCase()];T.push(`${t.toLowerCase()}/${T[0]}`);let p=n.aliases.find(f=>T.includes(f.alias.toLowerCase()));if(p){if(p.evidence==="unresolved"||p.standard_slug===null)return{state:{kind:"unresolved",alias:p.alias},viaAlias:!0,pinRoute:null};let f=Zb(n,p.standard_slug);return{state:eI(p,f,r),viaAlias:!0,pinRoute:f?.catalog_record_id?.toLowerCase()??null}}}let s=Rn[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=T=>({state:T,viaAlias:!1,pinRoute:null}),l=Vt(i),c=r.records.filter(T=>T.source_model_id.toLowerCase()===i&&s.matchRow(T,[l]));if(c.length>0){let T=Jt(c[0]),p=r.records.filter(f=>s.matchRow(f,[T])&&Jt(f)===T);return a(El(p.length>0?p:c,T,Op[t]??Tl))}let u=r.records.filter(T=>s.matchRow(T,o));if(u.length===0){let T=Jb(e,r,t);return T.length>0?a({kind:"wrong-provider",declared:e,otherProviders:T}):a({kind:"unknown",declared:e})}let d=new Map;for(let T of u){let p=Jt(T),f=d.get(p);f?f.push(T):d.set(p,[T])}let m=Op[t]??Tl,h=null,_=null;for(let T of d.values()){let p=Hp(T,m);(_===null||rI(p[0],_[0],m)<0)&&(h=T,_=p)}return a(El(h,Jt(h[0]),m))}function Bp(t,e,r,n){return tI(t,e,r,n).state}function Wp(t,e){let r=Rn[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(Jt(s));return n.size}function rI(t,e,r){let n=wi(t.source)-wi(e.source);if(n!==0)return n;let s=t.provider!==null&&r.includes(t.provider)?0:1,i=e.provider!==null&&r.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var Yp=new Set(Object.keys(Rn).filter(t=>t!=="codex"&&t!=="kimi")),nI=/\d\.(?=\d)/,Xp=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],qp=["deepseek-flash","deepseek-pro"],Gp="gpt-5.3-codex-spark",sI=15e3;function Lr(t,e){return e.code==="ETIMEDOUT"?`${t} did not respond within lint's own spawn timeout (${e.message}) \u2014 this does not mean the provider itself is unreachable, only that this specific check didn't finish in time.`:`${t} could not be run: ${e.message}`}function iI(){let t=xl("agy",["models"],{encoding:"utf-8",timeout:sI});return{status:t.status,stdout:t.stdout??"",error:t.error}}var wl=null;function oI(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim(),s=n.indexOf(" ");if(s<0)continue;let i=n.slice(s+1).trim();i&&e.push(i)}return e}function aI(t){if(!t&&wl)return wl;let e=s=>(t||(wl=s),s),r;try{r=(t??iI)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Lr("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Lr("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=oI(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}var lI=5e3;function cI(){let t=xl("codex",["debug","models"],{encoding:"utf-8",timeout:lI});return{status:t.status,stdout:t.stdout??"",error:t.error}}var Sl=null;function dI(t){let e;try{e=JSON.parse(t)}catch{return}let r=e.models;if(!Array.isArray(r))return;let n=[];for(let s of r){if(!s||typeof s!="object")continue;let{slug:i,visibility:o}=s;typeof i=="string"&&o==="list"&&n.push(i)}return n}function uI(t){if(!t&&Sl)return Sl;let e=s=>(t||(Sl=s),s),r;try{r=(t??cI)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Lr("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Lr("codex debug models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`codex debug models exited with status ${r.status??"unknown"}`});let n=dI(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}var mI=5e3;function fI(t){let e=xl("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:mI});return{status:e.status,stdout:e.stdout??"",error:e.error}}var vl=new Map;function pI(t,e){if(!e&&vl.has(t))return vl.get(t);let r=o=>(e||vl.set(t,o),o),n=t?`opencode models ${t}`:"opencode models",s;try{s=(e??fI)(t)}catch(o){return r({available:!1,models:[],reason:o instanceof Error?Lr(n,o):`${n} could not be run: ${String(o)}`})}if(s.error)return r({available:!1,models:[],reason:Lr(n,s.error)});if(s.status!==0)return r({available:!1,models:[],reason:`${n} exited with status ${s.status??"unknown"}`});let i=s.stdout.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0);return i.length===0?r({available:!1,models:[],reason:`${n} returned no models`}):r({available:!0,models:i})}function Al(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model)continue;let i=_I(e.opencodeConfigPath);if(!i.available){r.push(`[${n.alias}] model="${n.model}" cannot be verified for opencode: ${i.reason}.`);continue}if(i.models.includes(n.model)||/^github-copilot\/(gpt|gemini|o[0-9])/.test(n.model))continue;if(!n.model.includes("/")){let l=i.models.filter(c=>c.endsWith(`/${n.model}`));r.push(l.length>0?`[${n.alias}] model="${n.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model>. Your opencode.json declares it as ${l.join(" / ")}; set model=${l[0]}.`:`[${n.alias}] model="${n.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model> (e.g. github-copilot/${n.model}). Declare it in ~/.config/opencode/opencode.json (see https://lmctl.com/examples/opencode.json).`);continue}let o=n.model.slice(0,n.model.indexOf("/")),a=pI(o,e.opencodeModelsRunner);if(a.available&&a.models.includes(n.model))continue;if(a.available&&!a.models.includes(n.model)){r.push(`[${n.alias}] model="${n.model}" was not found in opencode's LOCALLY-VISIBLE live catalog for "${o}" (checked \`opencode models ${o}\`) -- this is unresolved, not a confirmed unavailability: it could mean opencode genuinely doesn't serve this model, OR that your local catalog/auth for "${o}" is stale/incomplete. Declaring it in opencode.json may or may not help; if it doesn't, check whether a non-opencode provider serves this model directly (e.g. \`lmctl lint\` with model= against provider=codex/claude/gemini/agy).`);continue}r.push(`[${n.alias}] model="${n.model}" is not declared in your opencode.json. opencode resolves github-copilot GPT/Gemini config-free, but copilot Claude and custom providers must be declared \u2014 copy https://lmctl.com/examples/opencode.json to ~/.config/opencode/opencode.json and adjust for your account.`);continue}if(s==="kimi"){if(!n.model)continue;let i=hI(e.kimiConfigPath);i.available?i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not declared in Kimi's [models] config. Valid configured models: ${Ln(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for kimi: ${i.reason}.`);continue}if(s==="agy"){if(!n.model)continue;let i=aI(e.agyModelsRunner);i.available?i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in agy's live model catalog (\`agy models\`). Valid models: ${Ln(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||qp.includes(n.model))continue;Xp.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${Ln(Xp)}. Valid server-resolved aliases (DeepSeek resolves these to its current model server-side -- pinning to a specific version instead is a DOWNGRADE, not a safer choice): ${Ln(qp)}. The catalog is patchable via dsh profile overlays \u2014 a model added that way warns here even though it may resolve.`);continue}if(s==="hermes"){if(!n.model)continue;let i=n.model.indexOf(":");(i<=0||i===n.model.length-1)&&r.push(`[${n.alias}] model="${n.model}" should use <provider>:<model> from Hermes's ACP catalog. lmctl checks the shape only; provider and model availability are resolved by Hermes.`);continue}if(s!=="pi"){if(s==="codex"){if(!n.model)continue;n.model===Gp&&r.push(`[${n.alias}] model="${Gp}" is banned as a build model (operator, 2026-09-06) -- it's a fast/cheap classification model, not intended for build work, and there's no cost reason left to reach for it. Use model=gpt-5.6-sol (or leave model= unset) for build work; if this member genuinely does non-build/classification work, this warning can be ignored.`);let i=uI(e.codexModelsRunner);if(!i.available){r.push(`[${n.alias}] model="${n.model}" cannot be verified for codex: ${i.reason}.`);continue}i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in codex's live model catalog (\`codex debug models\`). Valid models: ${Ln(i.models)}`);continue}n.model&&(Yp.has(s)||r.push(`[${n.alias}] model="${n.model}" cannot be verified for provider "${s}": no model validation path exists for this provider.`))}}}return r}async function zp(t,e={}){let r=t.filter(o=>o.model!==void 0&&Yp.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await Cp();if(n.catalog===null)return{warnings:[],errors:[]};let s=[],i=[];for(let o of r){let a=o.provider.trim().toLowerCase(),l=o.model,c=Bp(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let u=Wp(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${u} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&nI.test(l)){let u=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${u}" instead.`)}}return{warnings:s,errors:i}}async function Qp(t,e={}){return(await zp(t,e)).warnings}async function Zp(t,e={}){return(await zp(t,e)).errors}function hI(t){let e=process.env.KIMI_CODE_HOME||bl(Kp(),".kimi-code"),r=t??bl(e,"config.toml");if(!Jp(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=Vp(r,"utf-8")}catch(i){return{available:!1,models:[],reason:`${r} could not be read: ${i instanceof Error?i.message:String(i)}`}}let s=new Set;for(let i of n.split(/\r?\n/)){if(/^\s*\[/.test(i)&&!/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.test(i))return{available:!1,models:[],reason:`${r} has an invalid TOML table header`};let o=/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(i);if(!o)continue;let a=gI(o[1]);if(o[1].trim().startsWith("models")&&a===null)return{available:!1,models:[],reason:`${r} has an invalid [models] table header`};a?.[0]==="models"&&a.length>=2&&s.add(a[1])}return s.size===0?{available:!1,models:[],reason:`${r} has no [models] entries`}:{available:!0,models:[...s].sort()}}function gI(t){let e=[],r=0;for(;r<t.length;){for(;/\s/.test(t[r]??"");)r++;if(r>=t.length)break;let n="",s=t[r]==='"'||t[r]==="'"?t[r++]:void 0;if(s){for(;r<t.length&&t[r]!==s;)s==='"'&&t[r]==="\\"&&r+1<t.length&&r++,n+=t[r++];if(t[r]!==s)return null;r++}else{for(;r<t.length&&t[r]!==".";)n+=t[r++];n=n.trim()}if(!n)return null;for(e.push(n);/\s/.test(t[r]??"");)r++;if(r>=t.length)break;if(t[r]!==".")return null;r++}return e.length>0?e:null}function _I(t){let e=t??bl(Kp(),".config","opencode","opencode.json");if(!Jp(e))return{available:!0,models:[]};let r;try{r=JSON.parse(Vp(e,"utf-8"))}catch(n){return{available:!1,models:[],reason:`${e} could not be parsed: ${n instanceof Error?n.message:String(n)}`}}return{available:!0,models:yI(r)}}function yI(t){if(!Il(t))return[];let e=Si(t.provider)??Si(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Il(s))continue;let i=Si(s.models)??Si(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function Si(t){return Il(t)?t:null}function Il(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ln(t){return t.length>0?t.join(", "):"(none)"}Do();Xo();mi();_r();Xr();et();import{homedir as EI}from"node:os";var TI={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>Wr(t.teamfile),home:()=>EI(),date:t=>t.date},wI=/{{\s*([A-Za-z0-9_-]+)\s*}}/g;function eh(t,e){let r=new Set;return{text:t.replace(wI,(s,i)=>{let o=i.trim(),a=TI[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function th(t){return{workdir:t.workdir,teamfile:t.teamfile,date:SI(t.date)}}function SI(t){return t.toISOString().slice(0,10)}es();Gi();we();var Cn=5;var AI='notice: member "%s" uses provider=gemini \u2014 the Gemini CLI requires an API/enterprise Google account; personal Google subscriptions should use provider=agy (Antigravity).',kI={existsSync:II,statSync:xI,accessSync:bI},NI=async t=>{let{seed:e}=await Promise.resolve().then(()=>(In(),ep)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},Cr=kI,RI=Ps,ih,oh,vi;function ah(t){return Qp(t,vi!==void 0?{snapshot:vi}:{})}function lh(t){return Zp(t,vi!==void 0?{snapshot:vi}:{})}async function LI(t,e,r){let n=t.filter(i=>i.teamfile===void 0&&i.provider.trim().toLowerCase()==="opencode"&&i.model!==void 0&&i.model.length>0);return(await Promise.all(n.map(async i=>({member:i,result:await RI({cwd:i.sessiondir??e,model:i.model,...i.effort!==void 0?{effort:i.effort}:{},...r!==void 0?{env:r}:{}})})))).flatMap(({member:i,result:o})=>o.status==="rejected"?[`[${i.alias}] ${o.option}="${o.value}" rejected by opencode: ${o.error}`]:[])}function CI(t,e){let r=Yt(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=sh(o);if(n.has(a))continue;let l=OI(a);l!==void 0&&(n.add(a),s.push(`${i.alias}: sessiondir ${a} is not writable (seed would fail: ${l}) \u2014 fix permissions or set a writable sessiondir`))}return s}function OI(t){try{if(Cr.existsSync(t)){if(!Cr.statSync(t).isDirectory())return"ENOTDIR";Cr.accessSync(t,rh.W_OK);return}let e=MI(t);if(e===void 0)return;if(!Cr.statSync(e).isDirectory())return"ENOTDIR";Cr.accessSync(e,rh.W_OK);return}catch(e){return FI(e)??"permission check failed"}}function DI(t){let e=sh(t);try{return Rl(e)}catch{return e}}function MI(t){let e=t;for(;;){try{if(Cr.existsSync(e))return e}catch{return}let r=Yt(e);if(r===e)return;e=r}}function FI(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}async function PI(t,e){let r;try{r=await j(e,l=>Xe(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let n;try{n=$e(r)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=ji(n,Yt(r));e.stderr.write(`notice: checking teamfile and models ...
|
|
2134
|
-
`);let i=
|
|
2135
|
-
`);for(let l of n.members)
|
|
2125
|
+
Consulted ${au(st())}
|
|
2126
|
+
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function gi(t,e){let r=ub(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function ub(t,e){let r=t[So];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=nr(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===r&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}Lt();function _i(t){let e=Vn(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}xn();z();fr();Qr();Mt();Ft();var $M=60*60*1e3,mb=2e3,fb=5e3;function pl(t,e,r){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=$t({path:st()})),s),o=()=>{if(s===null)return;let a=s;s=null;try{a.close()}catch{}};return{hasOutstandingWork:()=>i().listAgentInflight().some(a=>a.sender_teamfile===e.teamfile&&a.sender_alias===e.alias&&!(a.receiver_teamfile===e.teamfile&&a.receiver_alias===e.alias)&&a.holder_pid!==null&&Ee(a.holder_pid)),pollMs:mb,settleMs:fb,maxHoldMs:dr(r),onHold:()=>N({event:"delivery_hold_open_started",receiver:n}),onRelease:a=>{o(),!(!a.held&&a.reason==="cleared")&&N({event:"delivery_hold_open_released",receiver:n,elapsed_ms:a.elapsedMs,held:a.held,reason:a.reason})}}}async function hp(t){let e=pb(t.newMessage,{newMessageFrom:t.newMessageFrom??hb(t.sender)});if(e.length===0)throw new Error(`no message to deliver for ${t.sender.teamfile}:${t.sender.alias} -> ${t.receiver.teamfile}:${t.receiver.alias}`);let r=!1,n=te(),s=0,i=0,o=0,a={provider:t.receiver.provider,sessionId:t.receiver.sessionId,cwd:t.receiver.cwd,prompt:e,permissionMode:t.permissionMode,env:t.env,onDelta:c=>{r=!0,n&&(s+=1,o=Buffer.byteLength(c,"utf8"),i+=o),t.onDelta?.(c)},onProgress:c=>t.onProgress?.(c)};t.receiver.model!==void 0&&(a.model=t.receiver.model),t.receiver.effort!==void 0&&(a.effort=t.receiver.effort),a.alias=t.receiver.alias,a.isLead=t.receiver.isLead,t.idleTimeoutMs!==void 0&&(a.timeoutMs=t.idleTimeoutMs),t.requireResume!==void 0&&(a.requireResume=t.requireResume),t.bundleSession!==void 0&&(a.bundleSession=t.bundleSession),a.holdOpen=pl(t.io,t.receiver,t.env),await t.onPromptBuilt?.(e);let l=await In(a);if(t.requireResume&&l.sessionId!==t.receiver.sessionId)throw new Error(`provider session changed: expected ${t.receiver.sessionId}, received ${l.sessionId??"(missing)"}`);return n&&xe(JSON.stringify({event:"chat_return",alias:t.receiver.alias,provider:t.receiver.provider,streamed:r,blockCount:s,streamedBytes:i,resultTextBytes:Buffer.byteLength(l.text,"utf8"),lastChunkBytes:o,tailPreview:l.text.slice(-200)})),l.status==="stalled"?{status:"stalled",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,stalledAfterMs:l.stalledAfterMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:l.status==="empty"?{status:"empty",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:{status:"ok",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}}function pb(t,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,t].join(`
|
|
2127
|
+
`)}function hb(t){return`${t.teamfile}:${t.alias}`}ms();var gp=256*1024,Ep=3e4;async function gl(t){let e=t.onEvent??(()=>{}),r=gb(t.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,u=null,d=t.prompt;try{let m=await j(r,k=>tt(t.teamfile,t.alias,k));if(t.expectedSession!==void 0&&(m.provider!==t.expectedSession.provider||m.sessionid!==t.expectedSession.sessionid))throw new he(`session changed for ${m.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${m.provider}:${m.sessionid}`);let h=m.teamfile,_=await j(r,k=>Ab(k,t.env??process.env)),T=_.sender,p=await kb(r,{explicitRoot:t.rootFlag,sender:T,receiverTeamfile:h,operatorOrigin:_.origin==="operator"}),f=T===null?null:await Nb(r,{rootTeamfile:p,sender:T,receiverTeamfile:h,receiverAlias:m.alias});f!==null&&!f.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${f.reason}
|
|
2128
|
+
`});let y=t.env??process.env,g=await j(r,k=>k.getRootTeam(p)?.name??null);g!==null&&(y.LMBEE_TEAM_NAME=g),i=await Tb(r,{receiverTeamfile:h,receiverAlias:m.alias,sender:T,rootTeamfile:p,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:t.prompt,origin:_.origin,parentInvocationId:_r(y.LMCTL_INVOCATION_ID)}),o=bb(r,i),i!==null&&(y.LMCTL_INVOCATION_ID=String(i));try{ir(r,$e(h),h)}catch{}n={root_teamfile:p,sender_teamfile:T?.teamfile??null,sender_alias:T?.alias??null,receiver_teamfile:h,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:_.origin,message_type:t.messageType??null,policy:f};let E=await wp(r,h,m.alias);if(E!==null){let k=An(E);return Gt(i,n,t.prompt,k,"unavailable"),u=hl(k,null),{status:"busy",message:k,teamChatLogId:null}}let v=!1;if(t.heldLease!==void 0){let k=t.heldLease;if(!await j(r,q=>{let K=q.getAgentInflight(h,m.alias);return K===null||K.sender_teamfile!==k.row.sender_teamfile||K.sender_alias!==k.row.sender_alias||K.started_at!==k.row.started_at||K.holder_pid!==process.pid?!1:q.heartbeatAgentInflight(k.row,k.leaseId,new Date().toISOString())})){let q=`bundle lease lost for ${m.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return Gt(i,n,t.prompt,q,"unavailable"),u=kn(q,null),{status:"error",errorKind:"provider",message:q,teamChatLogId:null,messageId:null}}}else{let k=await _b(r,h,m.alias);if(k.busy){let C=await yb(r,h,m.alias);return C+=await Eb(r,h,m.alias),Gt(i,n,t.prompt,C,"unavailable"),u=hl(C,null),{status:"busy",message:C,teamChatLogId:null}}v=k.idleReclaim}if(T!==null&&T.teamfile!==h){let k=await j(r,C=>zc(C,{root:p,sender:T,receiverTeamfile:h,receiverAlias:m.alias,now:new Date}));if(k.stop){let C=Zc(k.chain);return Gt(i,n,t.prompt,C,"cycle"),u=kn(C,null),{status:"error",errorKind:"cycle",message:C,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let k=await Cb(r,{receiver_teamfile:h,receiver_alias:m.alias,sender_teamfile:T?.teamfile??h,sender_alias:T?.alias??"operator",...v?{force:!0,reclaimReason:"session-idle"}:{}});if(!k.acquired){let C=Sp(h,m.alias,k.current);return C+=` ${ml(ul({holderPid:k.current.holder_pid,since:k.current.started_at}))}`,Gt(i,n,t.prompt,C,"unavailable"),u=hl(C,null),{status:"busy",message:C,teamChatLogId:null}}s={row:k.lease,leaseId:k.leaseId},a=ls(C=>j(r,q=>q.heartbeatAgentInflight(s.row,s.leaseId,C)),{intervalMs:Ep,onError:C=>{te()&&xe(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:C instanceof Error?C.message:String(C)}))}})}let w=await hp({sender:T??{teamfile:h,alias:"operator"},receiver:{teamfile:h,alias:m.alias,provider:m.provider,sessionId:m.sessionid,cwd:m.sessiondir,...m.model!==void 0?{model:m.model}:{},...m.effort!==void 0?{effort:m.effort}:{},...m.isLead!==void 0?{isLead:m.isLead}:{}},newMessage:t.prompt,newMessageFrom:T===null?"operator":`${T.teamfile}:${T.alias}`,io:r,permissionMode:t.permissionMode,...t.expectedSession!==void 0?{requireResume:!0}:{},...t.bundleSession!==void 0?{bundleSession:t.bundleSession}:{},env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:k=>e({kind:"delta",chunk:k}),onProgress:k=>e({kind:"progress",alias:m.alias,event:k}),onPromptBuilt:async k=>{d=k,l===null&&(l=await Db(r,{...n,message:k}),l!==null&&(t.onAccepted?.(rt(l)),i!==null&&await vb(r,i,l))),i!==null&&await Sb(r,i,k)}});d=w.prompt;let b=w.status==="stalled",S=w.status==="empty",I=null,x=b?`provider stalled${w.stalledAfterMs!==void 0?` after ${w.stalledAfterMs}ms`:""}`:S?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":w.status==="error"?w.error??w.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=b||S||w.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await yp(r,l,{...n,message:d,response:w.receipt,status:R,error_detail:x}),c=!0,I=l):I=await Fb(r,{...n,message:d,response:w.receipt,status:R,error_detail:x});let P=w.status!=="error"?w.warnings:void 0;if(b||S){let k=x;Gt(i,n,d,k,"error"),u=kn(k,I,w.receipt,P)}else u=Ib(w.receipt,I,P);return{status:b?"stalled":S?"empty":"ok",replyText:w.receipt,wroteDelta:w.wroteDelta,teamChatLogId:I,messageId:I===null?null:rt(I),durationMs:w.durationMs}}catch(m){let h=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await yp(r,l,{...n,message:d,response:null,status:"error",error_detail:h}),c=!0),Gt(i,n,d,h,"error"),u=kn(h,l),{status:"error",errorKind:m instanceof he?"target":"provider",message:h,teamChatLogId:l,messageId:l===null?null:rt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await Mb(r,n,rt(l)),s!==null&&await Ob(r,s.row,s.leaseId),i!==null&&await wb(r,i,u??kn("chat turn exited without a terminal outcome",null))}}function gb(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function _b(t,e,r){let n=await j(t,i=>(_s(i,e,r),cs(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await j(t,i=>cp(i,n,e,r));return{busy:!s,idleReclaim:s}}async function yb(t,e,r){let n=await wp(t,e,r);if(n!==null)return An(n);let s=await j(t,i=>i.getAgentInflight(e,r));return s!==null?Sp(e,r,s):`${r} is busy; wait and retry`}async function Eb(t,e,r){let n=await j(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${ml(ul({holderPid:n.holder_pid,since:n.started_at}))}`}async function Tb(t,e){try{return(await j(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:xb(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return te()&&xe(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function wb(t,e,r){try{await j(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){te()&&xe(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Sb(t,e,r){try{await j(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){te()&&xe(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function vb(t,e,r){try{await j(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){te()&&xe(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function bb(t,e){if(e===null)return;let r=setInterval(()=>{j(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{te()&&xe(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Ep);return r.unref?.(),r}function Tp(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function Ib(t,e,r){return{status:"done",result_summary:Nn(t),error:null,team_chat_log_id:e,...Tp(r)}}function hl(t,e){return{status:"busy",result_summary:Nn(t),error:t,team_chat_log_id:e}}function kn(t,e,r,n){return{status:"error",result_summary:Nn(r===void 0?t:r),error:t,team_chat_log_id:e,...Tp(n)}}function Nn(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function xb(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function Ab(t,e){let r=gi(e,t);if(r.ok)return{sender:_i(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(hi("chat"))}async function kb(t,e){if(e.explicitRoot!==void 0)return await j(t,n=>Xe(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await j(t,n=>Qc(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function Nb(t,e){return await j(t,r=>Kc({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:Rb(r,e.sender.teamfile,e.receiverTeamfile)}))}function Rb(t,e,r){return{teams:[e,r].map(s=>Lb(s,t))}}function Lb(t,e){let r=nr(t,e),n=rr(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function Cb(t,e){return await j(t,r=>{let n=te(),s=cr(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:mt(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&xe(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:_p(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&xe(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:_p(s.current)})),{acquired:!1,current:s.current})})}async function wp(t,e,r){return await j(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(fl(o).live)return o;let l=n.getAgentInflight(e,r);if(n.clearTerminalLock(e,r,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&n.clearObservedTerminalAgentInflight(e,r,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=n.getTerminalLock(e,r);return s===null?null:fl(s).live?s:null})}function _p(t){return t===null?null:{sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,holder_pid:t.holder_pid,started_at:t.started_at}}async function Ob(t,e,r){try{await j(t,n=>{n.releaseAgentInflight(e,r)})}catch(n){t.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
2129
|
+
`)}}function Sp(t,e,r){return`${e} is servicing ${r.sender_alias} (${r.sender_teamfile}) since ${r.started_at} \u2014 wait and retry, or inspect without waking it: lmctl tail "${t}" ${e}`}async function Db(t,e){let r=Rn(e.message);try{return await j(t,n=>n.beginTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:r.text,response:null,origin:e.origin,status:"running",error_detail:null,truncated:r.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(n){return t.stderr.write(`warning: failed to begin chat log: ${n instanceof Error?n.message:String(n)}
|
|
2130
|
+
`),null}}async function yp(t,e,r){let n=Rn(r.message),s=r.response===null?null:Rn(r.response);try{await j(t,i=>i.finishTeamChatLog(e,{root_teamfile:r.root_teamfile,sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,receiver_teamfile:r.receiver_teamfile,receiver_alias:r.receiver_alias,receiver_provider:r.receiver_provider,receiver_session_id:r.receiver_session_id,provider_prompt:r.message,message:n.text,response:s?.text??null,origin:r.origin,status:r.status,error_detail:r.error_detail,truncated:n.truncated||s?.truncated?1:0,created_at:new Date().toISOString()}))}catch(i){t.stderr.write(`warning: failed to finish chat log ${e}: ${i instanceof Error?i.message:String(i)}
|
|
2131
|
+
`)}}async function Mb(t,e,r){if(e!==null)try{await j(t,n=>{n.clearCurrentlyHandlingMessage(e.receiver_teamfile,e.receiver_alias,r)})}catch(n){t.stderr.write(`warning: failed to clear chat causal pointer: ${n instanceof Error?n.message:String(n)}
|
|
2132
|
+
`)}}async function Fb(t,e){let r=Rn(e.message),n=e.response===null?null:Rn(e.response);try{return await j(t,s=>s.insertTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:r.text,response:n?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(s){return t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
2133
|
+
`),null}}function Gt(t,e,r,n,s){t!==null||e===null||N({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:Nn(r)})}function Rn(t){return t.length<=gp?{text:t,truncated:!1}:{text:t.slice(0,gp),truncated:!0}}Lt();et();import{createHash as UI}from"node:crypto";import{accessSync as jI,constants as ih,existsSync as HI,readFileSync as Ll,realpathSync as Cl,statSync as BI,writeFileSync as oh}from"node:fs";import{dirname as zt,resolve as ah}from"node:path";import{spawnSync as kl}from"node:child_process";import{existsSync as Yp,readFileSync as zp}from"node:fs";import{homedir as Qp}from"node:os";import{resolve as xl}from"node:path";import{mkdirSync as Rp,readFileSync as Pb,renameSync as $b,writeFileSync as Ub,existsSync as Lp}from"node:fs";import{homedir as jb}from"node:os";import{dirname as Cp,join as yi,resolve as Ei}from"node:path";import{fileURLToPath as Hb}from"node:url";var Bb="https://lmctl.com/dataset/model_list.json",Wb="https://lmctl.com/dataset/aliases.json",Xb=1e3,qb=1e4,vp=6*60*60*1e3;function Gb(){return yi(jb(),".lmctl","cache","lmprice")}var yl="model_list.json",El="aliases.json",Op="meta.json",Jb="model_list.meta.json";function Rr(t,e){return yi(t,e)}function Jt(t){try{return JSON.parse(Pb(t,"utf-8"))}catch{return null}}function Dp(t,e){let r=`${t}.tmp-${process.pid}`;Ub(r,e),$b(r,t)}function _l(t){return t===null||typeof t=="number"}function Ti(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.schema_version!==1||!Array.isArray(e.records)||e.records.length===0?!1:e.records.every(r=>{if(typeof r!="object"||r===null)return!1;let n=r;if(typeof n.source!="string"||typeof n.source_model_id!="string"||typeof n.pricing!="object"||n.pricing===null)return!1;let s=n.pricing;return _l(s.input_per_1m_tokens)&&_l(s.output_per_1m_tokens)&&_l(s.input_cache_read_per_1m_tokens)})}var Kb=new Set(["established","asserted","unresolved"]);function wi(t){if(typeof t!="object"||t===null)return!1;let e=t;if(e.schema_version!==1||!Array.isArray(e.standards)||!Array.isArray(e.aliases))return!1;let r=e.standards.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.standard_slug=="string"&&(i.catalog_record_id===null||typeof i.catalog_record_id=="string")}),n=e.aliases.every(s=>{if(typeof s!="object"||s===null)return!1;let i=s;return typeof i.alias=="string"&&(i.standard_slug===null||typeof i.standard_slug=="string")&&typeof i.evidence=="string"&&Kb.has(i.evidence)});return r&&n}function Vb(t){let e=Jt(Rr(t,Op)),r={etag:typeof e?.model_list?.etag=="string"?e.model_list.etag:null,last_checked:typeof e?.model_list?.last_checked=="string"?e.model_list.last_checked:null},n={etag:typeof e?.aliases?.etag=="string"?e.aliases.etag:null,last_checked:typeof e?.aliases?.last_checked=="string"?e.aliases.last_checked:null};if(e===null){let s=Jt(Rr(t,Jb));s&&(r.etag=typeof s.etag=="string"?s.etag:null,r.last_checked=typeof s.fetchedAt=="string"?s.fetchedAt:null)}return{model_list:r,aliases:n}}function Yb(t){let e=Vb(t),r=Jt(Rr(t,yl)),n=Jt(Rr(t,El));return{catalog:Ti(r)?r:null,aliases:wi(n)?n:null,meta:e}}function zb(t,e){try{Rp(t,{recursive:!0}),Dp(Rr(t,Op),JSON.stringify(e))}catch{}}function bp(t,e,r){try{Rp(t,{recursive:!0}),Dp(Rr(t,e),JSON.stringify(r))}catch{}}function Qb(t,e){let r=Zb(t),n=r?[Ei(r,"data",e)]:[Ei(t,"..","..","data",e)];for(let s of n)if(Lp(s))return s;return null}function Zb(t){let e=Ei(t);for(;;){if(Lp(Ei(e,"package.json")))return e;let r=Cp(e);if(r===e)return null;e=r}}function Ip(t,e,r){let n=r!==void 0?r:Qb(t,e);return n===null?null:Jt(n)}function eI(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return vp;let e=Number(t);return!Number.isFinite(e)||e<0?vp:e*1e3}function tI(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function xp(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(Xb)});if(!s.ok)return{kind:"failed"};let i=s.headers.get("etag");if(r!==null&&i!==null&&i===n)return{kind:"match"};let o=await t(e,{signal:AbortSignal.timeout(qb)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}var Tl=null;var Ap=null;function Mp(t={}){return Object.keys(t).length===0?(Ap??=kp(t),Ap):kp(t)}async function kp(t){let e=Cp(Hb(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:tI();if(r!==null&&r!==""){let _=Jt(yi(r,yl)),T=Jt(yi(r,El));if(Ti(_)&&wi(T)){let p={catalog:_,aliases:T,source:"pinned",generatedAt:_.generated_at??null};return Tl=p.generatedAt,p}return Np(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??Gb(),i=t.now??Date.now(),o=t.ttlMs??eI(),a=Yb(s),l=(_,T)=>_!==null&&T.last_checked!==null&&i-Date.parse(T.last_checked)<o,c=a.catalog,u=a.aliases,d=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},h=!1;if(!l(c,a.meta.model_list)){let _=await xp(n,Bb,c,a.meta.model_list.etag);_.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),h=!0):_.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),h=!0,Ti(_.payload)&&(c=_.payload,_.etag!==null&&(m.model_list.etag=_.etag),bp(s,yl,c),d=!0))}if(!l(u,a.meta.aliases)){let _=await xp(n,Wb,u,a.meta.aliases.etag);_.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),h=!0):_.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),h=!0,wi(_.payload)&&(u=_.payload,_.etag!==null&&(m.aliases.etag=_.etag),bp(s,El,u),d=!0))}if((h||d)&&zb(s,m),c!==null||u!==null){let _={catalog:c,aliases:u,source:d?"network":"cache",generatedAt:c?.generated_at??null};return Tl=_.generatedAt,_}return Np(t,e)}function Np(t,e){let r=Ip(e,"price-data.json",t.bundledPath),n=Ip(e,"price-aliases.json",t.bundledAliasesPath),s=Ti(r)?r:null,i=wi(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Tl=o.generatedAt,o}function Vt(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function Kt(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Vt(r)}function Pp(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Vt(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function rI(t,e){let r=new Set,n=l=>{r.add(Vt(l))},s=t.trim().toLowerCase(),i=null,o=s.indexOf(":");o>0&&!s.slice(0,o).includes("/")&&(i=s.slice(0,o),n(s),s=s.slice(o+1)),n(s);let a=s.slice(s.lastIndexOf("/")+1);n(a);for(let l of e)n(`${l}/${a}`);return i!==null&&n(`${i}/${a}`),[...r]}function Lr(t){let e=n=>!(n.mode!==void 0&&n.mode!==null&&n.mode!=="chat"||t.nonChatName&&t.nonChatName.test(n.source_model_id.toLowerCase())),r=n=>e(n)&&t.family.test(n.source_model_id.toLowerCase());return{firstPartyProviders:t.firstPartyProviders,isChatModel:e,coversRecord:r,normalize:n=>rI(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=Pp(n);return s.some(o=>i.has(o))}}}var $p=Lr({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),Up=Lr({vendorPrefixes:["openai"],family:/(^|\/)(gpt-|o\d|chatgpt|ft:gpt)|openai\//,firstPartyProviders:["openai"],nonChatName:/(^|[-/])(tts|transcribe(?:-\w+)?|realtime(?:-\w+)?|search(?:-\w+)*|image(?:-\w+)?|audio(?:-\w+)?|whisper(?:-\w+)?|dall-e(?:-\w+)?|embedding|moderation)(-|$)/}),jp=Lr({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),Hp=Lr({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Bp=Lr({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),Wp=Lr({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),nI=/\s*\(([^()]+)\)\s*$/;function sI(t){let e=t.trim(),r=nI.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}var iI={"gemini 3.8 flash":"gemini-3.8-flash","gemini 3.7 flash":"gemini-3.7-flash","gemini 3.6 flash":"gemini-3.6-flash","gemini 3.1 pro":"gemini/gemini-3.1-pro-preview","claude sonnet 4.6":"claude-sonnet-4-6"},oI=["gemini","google","vertex_ai-language-models","anthropic"],aI={normalize(t){let{model:e}=sI(t),r=iI[e.toLowerCase()];return r===void 0?[]:[Vt(r)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let r=Pp(t);return e.some(n=>r.has(n))}},Ln={claude:$p,codex:Up,gemini:jp,agy:aI,kimi:Hp,qwen:Bp,hermes:Wp},Fp={claude:$p.firstPartyProviders,codex:Up.firstPartyProviders,gemini:jp.firstPartyProviders,agy:oI,kimi:Hp.firstPartyProviders,qwen:Bp.firstPartyProviders,hermes:Wp.firstPartyProviders};function lI(t,e,r){let n=e.trim().toLowerCase(),s=Vt(n);if(r.records.some(o=>o.source_model_id.toLowerCase()===n&&t.matchRow(o,[s])))return!0;let i=t.normalize(e);return i.length>0&&r.records.some(o=>t.matchRow(o,i))}function cI(t,e,r){let n=[];for(let[s,i]of Object.entries(Ln))s!==r&&lI(i,t,e)&&n.push(s);return n}function Si(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function dI(t,e){return t.input_per_1m_tokens===e.input_per_1m_tokens&&t.output_per_1m_tokens===e.output_per_1m_tokens&&t.input_cache_read_per_1m_tokens===e.input_cache_read_per_1m_tokens}function uI(t){let e=new Map,r=[];for(let n of t){let s=n.source_model_id.toLowerCase(),i=s.lastIndexOf("/"),o=i===-1?"":s.slice(0,i+1),a=i===-1?s:s.slice(i+1),l=`${n.source}:${o}${Vt(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!dI(c.pricing,n.pricing)){r.push(n);continue}/\d\.\d/.test(c.source_model_id)&&!/\d\.\d/.test(n.source_model_id)&&e.set(l,n)}return[...e.values(),...r]}function mI(t){return{route:t.record_id??`${t.source}:${t.source_model_id}`,source:t.source,sourceModelId:t.source_model_id,provider:t.provider??null,pricing:t.pricing,estimated:t.source==="manual"}}function Xp(t,e){return t.map(mI).sort((r,n)=>{let s=Si(r.source)-Si(n.source);if(s!==0)return s;let i=r.provider!==null&&e.includes(r.provider)?0:1,o=n.provider!==null&&e.includes(n.provider)?0:1;return i!==o?i-o:r.sourceModelId.localeCompare(n.sourceModelId)})}function fI(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function pI(t,e,r){let n=uI(t),s=Xp(n,r),o=n.find(a=>(a.record_id??`${a.source}:${a.source_model_id}`)===s[0].route)?.context_window?.input_tokens??void 0;return{id:s[0].sourceModelId,normalizedId:e,offers:s,...o!=null?{contextWindow:o}:{}}}function wl(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=pI(t,e,r),s=n.offers.find(fI);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}var Sl=[];function hI(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function gI(t,e,r){let n=t.standard_slug;if(e===null||e.catalog_record_id===null)return{kind:"known-unpriced",id:n};let s=e.catalog_record_id.toLowerCase(),i=r.records.find(l=>(l.record_id??`${l.source}:${l.source_model_id}`).toLowerCase()===s);if(!i)return{kind:"known-unpriced",id:n};let o=Kt(i),a=r.records.filter(l=>Kt(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:wl(a,o,Sl)}function _I(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let T=[e.trim().toLowerCase()];T.push(`${t.toLowerCase()}/${T[0]}`);let p=n.aliases.find(f=>T.includes(f.alias.toLowerCase()));if(p){if(p.evidence==="unresolved"||p.standard_slug===null)return{state:{kind:"unresolved",alias:p.alias},viaAlias:!0,pinRoute:null};let f=hI(n,p.standard_slug);return{state:gI(p,f,r),viaAlias:!0,pinRoute:f?.catalog_record_id?.toLowerCase()??null}}}let s=Ln[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=T=>({state:T,viaAlias:!1,pinRoute:null}),l=Vt(i),c=r.records.filter(T=>T.source_model_id.toLowerCase()===i&&s.matchRow(T,[l]));if(c.length>0){let T=Kt(c[0]),p=r.records.filter(f=>s.matchRow(f,[T])&&Kt(f)===T);return a(wl(p.length>0?p:c,T,Fp[t]??Sl))}let u=r.records.filter(T=>s.matchRow(T,o));if(u.length===0){let T=cI(e,r,t);return T.length>0?a({kind:"wrong-provider",declared:e,otherProviders:T}):a({kind:"unknown",declared:e})}let d=new Map;for(let T of u){let p=Kt(T),f=d.get(p);f?f.push(T):d.set(p,[T])}let m=Fp[t]??Sl,h=null,_=null;for(let T of d.values()){let p=Xp(T,m);(_===null||yI(p[0],_[0],m)<0)&&(h=T,_=p)}return a(wl(h,Kt(h[0]),m))}function qp(t,e,r,n){return _I(t,e,r,n).state}function Gp(t,e){let r=Ln[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(Kt(s));return n.size}function yI(t,e,r){let n=Si(t.source)-Si(e.source);if(n!==0)return n;let s=t.provider!==null&&r.includes(t.provider)?0:1,i=e.provider!==null&&r.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var Zp=new Set(Object.keys(Ln).filter(t=>t!=="codex"&&t!=="kimi")),EI=/\d\.(?=\d)/,Jp=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],Kp=["deepseek-flash","deepseek-pro"],Vp="gpt-5.3-codex-spark",TI=15e3;function Cr(t,e){return e.code==="ETIMEDOUT"?`${t} did not respond within lint's own spawn timeout (${e.message}) \u2014 this does not mean the provider itself is unreachable, only that this specific check didn't finish in time.`:`${t} could not be run: ${e.message}`}function wI(){let t=kl("agy",["models"],{encoding:"utf-8",timeout:TI});return{status:t.status,stdout:t.stdout??"",error:t.error}}var vl=null;function SI(t){let e=[];for(let r of t.split(/\r?\n/)){let n=r.trim(),s=n.indexOf(" ");if(s<0)continue;let i=n.slice(s+1).trim();i&&e.push(i)}return e}function vI(t){if(!t&&vl)return vl;let e=s=>(t||(vl=s),s),r;try{r=(t??wI)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Cr("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Cr("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=SI(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}var bI=5e3;function II(){let t=kl("codex",["debug","models"],{encoding:"utf-8",timeout:bI});return{status:t.status,stdout:t.stdout??"",error:t.error}}var bl=null;function xI(t){let e;try{e=JSON.parse(t)}catch{return}let r=e.models;if(!Array.isArray(r))return;let n=[];for(let s of r){if(!s||typeof s!="object")continue;let{slug:i,visibility:o}=s;typeof i=="string"&&o==="list"&&n.push(i)}return n}function AI(t){if(!t&&bl)return bl;let e=s=>(t||(bl=s),s),r;try{r=(t??II)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Cr("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Cr("codex debug models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`codex debug models exited with status ${r.status??"unknown"}`});let n=xI(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}var kI=5e3;function NI(t){let e=kl("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:kI});return{status:e.status,stdout:e.stdout??"",error:e.error}}var Il=new Map;function RI(t,e){if(!e&&Il.has(t))return Il.get(t);let r=o=>(e||Il.set(t,o),o),n=t?`opencode models ${t}`:"opencode models",s;try{s=(e??NI)(t)}catch(o){return r({available:!1,models:[],reason:o instanceof Error?Cr(n,o):`${n} could not be run: ${String(o)}`})}if(s.error)return r({available:!1,models:[],reason:Cr(n,s.error)});if(s.status!==0)return r({available:!1,models:[],reason:`${n} exited with status ${s.status??"unknown"}`});let i=s.stdout.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0);return i.length===0?r({available:!1,models:[],reason:`${n} returned no models`}):r({available:!0,models:i})}function Nl(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model)continue;let i=OI(e.opencodeConfigPath);if(!i.available){r.push(`[${n.alias}] model="${n.model}" cannot be verified for opencode: ${i.reason}.`);continue}if(i.models.includes(n.model)||/^github-copilot\/(gpt|gemini|o[0-9])/.test(n.model))continue;if(!n.model.includes("/")){let l=i.models.filter(c=>c.endsWith(`/${n.model}`));r.push(l.length>0?`[${n.alias}] model="${n.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model>. Your opencode.json declares it as ${l.join(" / ")}; set model=${l[0]}.`:`[${n.alias}] model="${n.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model> (e.g. github-copilot/${n.model}). Declare it in ~/.config/opencode/opencode.json (see https://lmctl.com/examples/opencode.json).`);continue}let o=n.model.slice(0,n.model.indexOf("/")),a=RI(o,e.opencodeModelsRunner);if(a.available&&a.models.includes(n.model))continue;if(a.available&&!a.models.includes(n.model)){r.push(`[${n.alias}] model="${n.model}" was not found in opencode's LOCALLY-VISIBLE live catalog for "${o}" (checked \`opencode models ${o}\`) -- this is unresolved, not a confirmed unavailability: it could mean opencode genuinely doesn't serve this model, OR that your local catalog/auth for "${o}" is stale/incomplete. Declaring it in opencode.json may or may not help; if it doesn't, check whether a non-opencode provider serves this model directly (e.g. \`lmctl lint\` with model= against provider=codex/claude/gemini/agy).`);continue}r.push(`[${n.alias}] model="${n.model}" is not declared in your opencode.json. opencode resolves github-copilot GPT/Gemini config-free, but copilot Claude and custom providers must be declared \u2014 copy https://lmctl.com/examples/opencode.json to ~/.config/opencode/opencode.json and adjust for your account.`);continue}if(s==="kimi"){if(!n.model)continue;let i=LI(e.kimiConfigPath);i.available?i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not declared in Kimi's [models] config. Valid configured models: ${Cn(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for kimi: ${i.reason}.`);continue}if(s==="agy"){if(!n.model)continue;let i=vI(e.agyModelsRunner);i.available?i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in agy's live model catalog (\`agy models\`). Valid models: ${Cn(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||Kp.includes(n.model))continue;Jp.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${Cn(Jp)}. Valid server-resolved aliases (DeepSeek resolves these to its current model server-side -- pinning to a specific version instead is a DOWNGRADE, not a safer choice): ${Cn(Kp)}. The catalog is patchable via dsh profile overlays \u2014 a model added that way warns here even though it may resolve.`);continue}if(s==="hermes"){if(!n.model)continue;let i=n.model.indexOf(":");(i<=0||i===n.model.length-1)&&r.push(`[${n.alias}] model="${n.model}" should use <provider>:<model> from Hermes's ACP catalog. lmctl checks the shape only; provider and model availability are resolved by Hermes.`);continue}if(s!=="pi"){if(s==="codex"){if(!n.model)continue;n.model===Vp&&r.push(`[${n.alias}] model="${Vp}" is banned as a build model (operator, 2026-09-06) -- it's a fast/cheap classification model, not intended for build work, and there's no cost reason left to reach for it. Use model=gpt-5.6-sol (or leave model= unset) for build work; if this member genuinely does non-build/classification work, this warning can be ignored.`);let i=AI(e.codexModelsRunner);if(!i.available){r.push(`[${n.alias}] model="${n.model}" cannot be verified for codex: ${i.reason}.`);continue}i.models.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in codex's live model catalog (\`codex debug models\`). Valid models: ${Cn(i.models)}`);continue}n.model&&(Zp.has(s)||r.push(`[${n.alias}] model="${n.model}" cannot be verified for provider "${s}": no model validation path exists for this provider.`))}}}return r}async function eh(t,e={}){let r=t.filter(o=>o.model!==void 0&&Zp.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await Mp();if(n.catalog===null)return{warnings:[],errors:[]};let s=[],i=[];for(let o of r){let a=o.provider.trim().toLowerCase(),l=o.model,c=qp(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let u=Gp(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${u} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&EI.test(l)){let u=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${u}" instead.`)}}return{warnings:s,errors:i}}async function th(t,e={}){return(await eh(t,e)).warnings}async function rh(t,e={}){return(await eh(t,e)).errors}function LI(t){let e=process.env.KIMI_CODE_HOME||xl(Qp(),".kimi-code"),r=t??xl(e,"config.toml");if(!Yp(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=zp(r,"utf-8")}catch(i){return{available:!1,models:[],reason:`${r} could not be read: ${i instanceof Error?i.message:String(i)}`}}let s=new Set;for(let i of n.split(/\r?\n/)){if(/^\s*\[/.test(i)&&!/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.test(i))return{available:!1,models:[],reason:`${r} has an invalid TOML table header`};let o=/^\s*\[\s*(.+?)\s*\]\s*(?:#.*)?$/.exec(i);if(!o)continue;let a=CI(o[1]);if(o[1].trim().startsWith("models")&&a===null)return{available:!1,models:[],reason:`${r} has an invalid [models] table header`};a?.[0]==="models"&&a.length>=2&&s.add(a[1])}return s.size===0?{available:!1,models:[],reason:`${r} has no [models] entries`}:{available:!0,models:[...s].sort()}}function CI(t){let e=[],r=0;for(;r<t.length;){for(;/\s/.test(t[r]??"");)r++;if(r>=t.length)break;let n="",s=t[r]==='"'||t[r]==="'"?t[r++]:void 0;if(s){for(;r<t.length&&t[r]!==s;)s==='"'&&t[r]==="\\"&&r+1<t.length&&r++,n+=t[r++];if(t[r]!==s)return null;r++}else{for(;r<t.length&&t[r]!==".";)n+=t[r++];n=n.trim()}if(!n)return null;for(e.push(n);/\s/.test(t[r]??"");)r++;if(r>=t.length)break;if(t[r]!==".")return null;r++}return e.length>0?e:null}function OI(t){let e=t??xl(Qp(),".config","opencode","opencode.json");if(!Yp(e))return{available:!0,models:[]};let r;try{r=JSON.parse(zp(e,"utf-8"))}catch(n){return{available:!1,models:[],reason:`${e} could not be parsed: ${n instanceof Error?n.message:String(n)}`}}return{available:!0,models:DI(r)}}function DI(t){if(!Al(t))return[];let e=vi(t.provider)??vi(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Al(s))continue;let i=vi(s.models)??vi(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function vi(t){return Al(t)?t:null}function Al(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Cn(t){return t.length>0?t.join(", "):"(none)"}Fo();Go();fi();yr();qr();et();import{homedir as MI}from"node:os";var FI={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>Xr(t.teamfile),home:()=>MI(),date:t=>t.date},PI=/{{\s*([A-Za-z0-9_-]+)\s*}}/g;function nh(t,e){let r=new Set;return{text:t.replace(PI,(s,i)=>{let o=i.trim(),a=FI[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function sh(t){return{workdir:t.workdir,teamfile:t.teamfile,date:$I(t.date)}}function $I(t){return t.toISOString().slice(0,10)}ts();Ki();we();var On=5;var WI='notice: member "%s" uses provider=gemini \u2014 the Gemini CLI requires an API/enterprise Google account; personal Google subscriptions should use provider=agy (Antigravity).',XI={existsSync:HI,statSync:BI,accessSync:jI},qI=async t=>{let{seed:e}=await Promise.resolve().then(()=>(xn(),np)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},Or=XI,GI=$s,lh,ch,bi;function dh(t){return th(t,bi!==void 0?{snapshot:bi}:{})}function uh(t){return rh(t,bi!==void 0?{snapshot:bi}:{})}async function JI(t,e,r){let n=t.filter(i=>i.teamfile===void 0&&i.provider.trim().toLowerCase()==="opencode"&&i.model!==void 0&&i.model.length>0);return(await Promise.all(n.map(async i=>({member:i,result:await GI({cwd:i.sessiondir??e,model:i.model,...i.effort!==void 0?{effort:i.effort}:{},...r!==void 0?{env:r}:{}})})))).flatMap(({member:i,result:o})=>o.status==="rejected"?[`[${i.alias}] ${o.option}="${o.value}" rejected by opencode: ${o.error}`]:[])}function KI(t,e){let r=zt(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=ah(o);if(n.has(a))continue;let l=VI(a);l!==void 0&&(n.add(a),s.push(`${i.alias}: sessiondir ${a} is not writable (seed would fail: ${l}) \u2014 fix permissions or set a writable sessiondir`))}return s}function VI(t){try{if(Or.existsSync(t)){if(!Or.statSync(t).isDirectory())return"ENOTDIR";Or.accessSync(t,ih.W_OK);return}let e=zI(t);if(e===void 0)return;if(!Or.statSync(e).isDirectory())return"ENOTDIR";Or.accessSync(e,ih.W_OK);return}catch(e){return QI(e)??"permission check failed"}}function YI(t){let e=ah(t);try{return Cl(e)}catch{return e}}function zI(t){let e=t;for(;;){try{if(Or.existsSync(e))return e}catch{return}let r=zt(e);if(r===e)return;e=r}}function QI(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}async function ZI(t,e){let r;try{r=await j(e,l=>Xe(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let n;try{n=$e(r)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=Bi(n,zt(r));e.stderr.write(`notice: checking teamfile and models ...
|
|
2134
|
+
`);let i=Nl(n.members,{agyModelsRunner:lh,codexModelsRunner:ch});i.push(...await dh(n.members)),s.push(...await uh(n.members));let o=Ll(r,"utf8"),a=nh(o,sh({workdir:zt(r),teamfile:r,date:new Date})).unknownNames;a.length>0&&i.push(`unknown template placeholder${a.length===1?"":"s"}: ${a.map(l=>`{{${l}}}`).join(", ")}`),i.push(...Mo(n.members,zt(r))),i.push(...KI(n.members,r)),i.push(...await JI(n.members,zt(r),e.env));for(let l of s)e.stderr.write(`error: ${l.field}: ${l.message}
|
|
2135
|
+
`);for(let l of n.members)Ol([l],e),l.session!==void 0&&l.session.length<On&&i.push(`${l.alias}: sessionid is shorter than ${On} chars; run lmctl seed to refresh it`);return{ok:!0,result:{config:n,absTeamfile:r,errors:s,warnings:i}}}var ex=/^\[([^\]]+)\]\s+(.*)$/s,tx=/^([^:\s][^:]*):\s+(.*)$/s;function rx(t,e){let r=ex.exec(t);if(r){let s=e.get(r[1].toLowerCase());if(s!==void 0)return{alias:s,message:r[2]}}let n=tx.exec(t);if(n){let s=e.get(n[1].toLowerCase());if(s!==void 0)return{alias:s,message:n[2]}}return{alias:"",message:t}}async function mh(t,e){let r=await ZI(t,e);if(!r.ok)return{status:"error",errors:[{alias:"",message:r.message}],warnings:[],counts:{errors:1,warnings:0}};let{config:n,errors:s,warnings:i}=r.result,o=new Map(n.members.map(c=>[c.alias.toLowerCase(),c.alias])),a=s.map(c=>({alias:o.get(c.field.toLowerCase())??"",message:c.message})),l=i.map(c=>rx(c,o));for(let c of l)e.stderr.write(`warning: ${c.alias?`${c.alias}: `:""}${c.message}
|
|
2136
2136
|
`);return e.stderr.write(`notice: ${a.length} error${a.length===1?"":"s"}, ${l.length} warning${l.length===1?"":"s"}
|
|
2137
|
-
`),{status:a.length>0?"error":"ok",errors:a,warnings:l,counts:{errors:a.length,warnings:l.length}}}function
|
|
2137
|
+
`),{status:a.length>0?"error":"ok",errors:a,warnings:l,counts:{errors:a.length,warnings:l.length}}}function nx(t,e,r,n){if(e.preamble===void 0)return t.toLowerCase()!=="lead"?void 0:`${X}
|
|
2138
2138
|
|
|
2139
2139
|
Teamfile ${r}:
|
|
2140
2140
|
${n}
|
|
2141
2141
|
|
|
2142
|
-
After this seed finishes, use \`lmctl prompt ${JSON.stringify(r)} <alias> "<message>"\` to send a message. Do not run or use lmctl prompt during this seed. Reply only with the ACK above and wait.`;if(typeof e.preamble=="string")return e.preamble;for(let[s,i]of Object.entries(e.preamble))if(s.toLowerCase()===t.toLowerCase())return i}async function
|
|
2143
|
-
`),c=a,u=
|
|
2144
|
-
`);return 1}try{
|
|
2145
|
-
`);for(let g of
|
|
2146
|
-
`);for(let g of await
|
|
2147
|
-
`);for(let g of
|
|
2148
|
-
`);let m=await
|
|
2149
|
-
`);return 1}let h=r.replaceSession;if(h){let g=o.members.find(E=>E.alias.toLowerCase()===h.alias.toLowerCase());if(!g||g.teamfile||g.session!==h.sessionid)return
|
|
2150
|
-
`),1;for(let g of o.members){if(g.teamfile!==void 0||h&&g.alias.toLowerCase()!==h.alias.toLowerCase())continue;if(!h&&g.session!==void 0&&g.session.length>=
|
|
2142
|
+
After this seed finishes, use \`lmctl prompt ${JSON.stringify(r)} <alias> "<message>"\` to send a message. Do not run or use lmctl prompt during this seed. Reply only with the ACK above and wait.`;if(typeof e.preamble=="string")return e.preamble;for(let[s,i]of Object.entries(e.preamble))if(s.toLowerCase()===t.toLowerCase())return i}async function fh(t,e,r={}){let n;try{n=await j(e,g=>Xe(t,g))}catch(g){return Yt(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let s;try{s=Cl(n)}catch(g){return Yt(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let i=zt(n),o;try{o=$e(n)}catch(g){return Yt(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let a=Ll(n,"utf8"),l=a.split(`
|
|
2143
|
+
`),c=a,u=ax(l),d=Bi(o,i);if(d.length>0){Ol(o.members,e);for(let g of d)e.stderr.write(`error: ${g.field}: ${g.message}
|
|
2144
|
+
`);return 1}try{ir(e,o,n)}catch{}Ol(o.members,e),e.stderr.write(`notice: checking teamfile and models ...
|
|
2145
|
+
`);for(let g of Nl(o.members,{agyModelsRunner:lh,codexModelsRunner:ch}))e.stderr.write(`warning: ${g}
|
|
2146
|
+
`);for(let g of await dh(o.members))e.stderr.write(`warning: ${g}
|
|
2147
|
+
`);for(let g of Mo(o.members,i))e.stderr.write(`warning: ${g}
|
|
2148
|
+
`);let m=await uh(o.members);if(m.length>0){for(let g of m)e.stderr.write(`error: ${g.field}: ${g.message}
|
|
2149
|
+
`);return 1}let h=r.replaceSession;if(h){let g=o.members.find(E=>E.alias.toLowerCase()===h.alias.toLowerCase());if(!g||g.teamfile||g.session!==h.sessionid)return Yt(e,"Session binding changed; refresh cancelled.")}let _=0,T=o.members.filter(g=>g.teamfile!==void 0?!1:h?g.alias.toLowerCase()===h.alias.toLowerCase():g.session===void 0||g.session.length<On);for(let g of T)if(!ux(g.provider))return e.stderr.write(`error: ${g.alias}: invalid provider "${g.provider}"
|
|
2150
|
+
`),1;for(let g of o.members){if(g.teamfile!==void 0||h&&g.alias.toLowerCase()!==h.alias.toLowerCase())continue;if(!h&&g.session!==void 0&&g.session.length>=On){e.stderr.write(`warning: ${g.alias}: existing sessionid preserved; skipping
|
|
2151
2151
|
`);continue}let E=g.sessiondir??i;e.stderr.write(`${g.alias}: launching ${g.provider} seed session; this can take several seconds
|
|
2152
|
-
`);let v=
|
|
2152
|
+
`);let v=gr(e,I=>`${g.alias}: still launching (${I}s elapsed)
|
|
2153
2153
|
`),w=h?l.map((I,x)=>x===u.get(g.alias.toLowerCase())?I.replace(/\s+sessionid=(?:"[^"]*"|\S+)/g,""):I).join(`
|
|
2154
2154
|
`):l.join(`
|
|
2155
|
-
`),b=
|
|
2156
|
-
`);if(I.error!==void 0||I.sessionId===void 0||I.sessionId.length<
|
|
2155
|
+
`),b=nx(g.alias,r,n,w),S;try{S=Ic(n,g.alias)}catch(I){return v.stop(),Yt(e,I instanceof Error?I.message:String(I))}try{let I;try{I=await qI({provider:g.provider,cwd:E,...g.model!==void 0?{model:g.model}:{},...g.effort!==void 0?{effort:g.effort}:{},...b!==void 0?{prompt:b}:{}})}finally{v.stop()}for(let C of I.warnings??[])e.stderr.write(`warning: ${g.alias}: ${C}
|
|
2156
|
+
`);if(I.error!==void 0||I.sessionId===void 0||I.sessionId.length<On){let C=`provider did not report a sessionid; no new session was found for ${E} (possible provider workspace/cwd mismatch)`;return e.stderr.write(`error: ${g.alias}: seed failed${I.error!==void 0?`: ${I.error}`:`; ${C}`}
|
|
2157
2157
|
`),1}let x=u.get(g.alias.toLowerCase());if(x===void 0)return e.stderr.write(`error: ${g.alias}: could not find matching _MEMBER_ line to update
|
|
2158
|
-
`),1;let R=
|
|
2159
|
-
`),
|
|
2158
|
+
`),1;let R=YI(E),P=Rl(l[x],"sessionid",I.sessionId);P=Rl(P,"sessiondir",R);let k=g.model;if(g.model===void 0){let C;try{C=(await Nr(I.sessionId,g.provider))?.model}catch{C=void 0}C!==void 0&&C.length>0&&(P=Rl(P,"model",C),k=C)}if((h||r.guardFile)&&Ll(n,"utf8")!==c)return Yt(e,`Teamfile changed during seeding; new session ${I.sessionId} was not attached. Existing bindings preserved.`);l[x]=P,_+=1,c=l.join(`
|
|
2159
|
+
`),oh(n,c,"utf8"),e.stdout.write(`${g.alias}: seeded ${I.sessionId} provider=${g.provider} sessiondir=${R} model=${k?JSON.stringify(k):"default (not reported)"}
|
|
2160
2160
|
`)}finally{S()}}let p=l.join(`
|
|
2161
|
-
`),f=
|
|
2162
|
-
`);let y=new Date().toISOString();try{await j(e,g=>{
|
|
2161
|
+
`),f=dx(p,Cl(n));f!==p&&oh(n,f,"utf8"),_===0&&e.stdout.write(`no members needed seeding
|
|
2162
|
+
`);let y=new Date().toISOString();try{await j(e,g=>{ox(g,{teamfilePath:s,name:o.name,rawText:f,now:y})})}catch(g){return Yt(e,g instanceof Error?g.message:String(g))}return 0}function sx(t){return UI("sha256").update(t).digest("hex")}function ix(t,e){return{teamfile_path:e.teamfilePath,name:e.name,raw_text:e.rawText,raw_sha256:sx(e.rawText),registered_at:t?.registered_at??e.now,last_seeded_at:e.now}}function ox(t,e){let r=Jn(e.rawText,e.teamfilePath);qi(t,e.teamfilePath,r);let n=ix(t.getRootTeam(e.teamfilePath),e);return t.upsertRootTeam(n),n}function ax(t){let e=new Map;for(let r=0;r<t.length;r+=1){let n=t[r];if(!/^\s*_MEMBER_\s+\S/.test(n))continue;let s=lx(n,"alias");s!==void 0&&e.set(s.toLowerCase(),r)}return e}function lx(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function Rl(t,e,r){let n=`${e}=${cx(r)}`,s=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return s.test(t)?t.replace(s,(i,o)=>`${o}${n}`):`${t.trimEnd()} ${n}`}function cx(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function dx(t,e){let r=`#teamfile: ${e}`,n=t.indexOf(`
|
|
2163
2163
|
`),s=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1):"";return s===r?t:s.startsWith("#teamfile:")?i.length>0?`${r}
|
|
2164
2164
|
${i}`:`${r}
|
|
2165
2165
|
`:t.length>0?`${r}
|
|
2166
2166
|
${t}`:`${r}
|
|
2167
|
-
`}function
|
|
2168
|
-
`),1}function
|
|
2169
|
-
`),r.provider==="gemini"&&e.stderr.write(`${
|
|
2170
|
-
`)}et();var
|
|
2171
|
-
${i}`)}function Dr(t,e,r=[]){let n;try{let i=JSON.parse(e);n=typeof i?.error=="string"?i.error:i?.error?.message??i?.message??i?.detail}catch{/^\s*[<{[]/.test(e)||(n=e.trim())}if(typeof n!="string"||!n.trim())return t;let s=Or(n,r);return{...t,detail:s,provider_message:s}}import{spawnSync as QI}from"node:child_process";import{readdirSync as ZI,readFileSync as ex}from"node:fs";import{join as tx}from"node:path";var gh="ANTIGRAVITY_LS_ADDRESS",_h="ANTIGRAVITY_CSRF_TOKEN",rx="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",nx=["-p","/usage"],sx=(t,e)=>{let r=QI("agy",nx,{encoding:"utf8",timeout:t,maxBuffer:16777216,env:e,stdio:["ignore","pipe","ignore"]});return{status:r.status,stdout:typeof r.stdout=="string"?r.stdout:"",error:r.error}},ix=async(t,e,r)=>{let n=await fetch(t,{method:"POST",headers:e,body:"{}",signal:AbortSignal.timeout(r)});return{status:n.status,body:await n.text()}},ox=sx,ax=ix;function lx(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function cx(t){let e=t.trim().toLowerCase(),r={"gemini models":"gemini","claude and gpt models":"3p",gemini:"gemini","3p models":"3p","3p":"3p"};return r[e]?r[e]:e.replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function dx(t){let e=t.toLowerCase();return e.includes("weekly")?"weekly":e.includes("five hour")||e.includes("5-hour")||e.includes("5 hour")?"five_hour":e.includes("monthly")||e.includes("month")?"monthly":null}function ux(t){let e={weekly:"weekly",five_hour:"5h",monthly:"monthly"},r=[];for(let n of t.split(/\r?\n/)){let s=n.trim().split(" ").map(l=>l.trim());if(s.length<3||!s[0]||!s[1])continue;let i=dx(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=Se(o/100);r.push(Re({bucket_id:`${cx(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:Se(1-a),remaining_fraction:a,resets_at_iso:s[3]||null,raw_value:o,raw_scale:"remaining_percent"}))}return r.sort((n,s)=>String(n.group_name??"").localeCompare(String(s.group_name??""))||String(n.bucket_id??"").localeCompare(String(s.bucket_id??"")))}function On(t,e,r){return Le("agy","provider_unavailable",t,e,"agy_cli_print")}function mx(t,e,r={}){try{let n=ox(Math.max(t,60)*1e3,lx(e));if(Me(r,"agy_cli_print",n.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),n.error?.code==="ENOENT")return On("agy_not_found","the agy CLI is not on PATH",t);if(n.error?.code==="ETIMEDOUT")return On("cli_timeout","agy -p /usage did not finish in time",t);if(n.error)return On("cli_failed",n.error.message,t);let s=ux(n.stdout??"");return s.length===0?On("cli_unparseable",`exit ${n.status??1}; no buckets parsed from CLI output`,t):ge("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(n){return On("cli_failed",n instanceof Error?n.message:String(n),t)}}function fx(t){let e=[],r=new Set,n=(s,i,o)=>{!s||!i||r.has(`${s}\0${i}`)||(r.add(`${s}\0${i}`),e.push([s,i,o]))};n(t[gh],t[_h],-1);try{for(let s of ZI("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of ex(tx("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}n(i[gh],i[_h],Number(s))}catch{}}catch{}return e}function px(t){if(typeof t!="object"||t===null)return null;let e=t.response;if(typeof e!="object"||e===null)return null;let r=e.groups;if(!Array.isArray(r))return null;let n=[];for(let s of r){if(typeof s!="object"||s===null)continue;let i=s,o=typeof i.displayName=="string"?i.displayName:null;if(Array.isArray(i.buckets))for(let a of i.buckets){if(typeof a!="object"||a===null)continue;let l=a,c=ze(l.remainingFraction,"fraction");n.push(Re({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:ph(l.window),used_fraction:c===null?null:Se(1-c),remaining_fraction:c,resets_at_iso:l.resetTime??null,raw_value:l.remainingFraction??null,raw_scale:"remaining_fraction"}))}}return n.length===0?null:(n.sort((s,i)=>String(s.group_name??"").localeCompare(String(i.group_name??""))||String(s.bucket_id??"").localeCompare(String(i.bucket_id??""))),ge("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n}))}async function hx(t,e,r={}){let n=fx(e);if(n.length===0)return Le("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let s=[];for(let[i,o,a]of n)try{let l=await ax(`http://${i}${rx}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":o},t*1e3);if(Me(r,"agy_connect_rpc",l.body,[o],l.status),l.status===200){let c;try{c=JSON.parse(l.body)}catch{s.push(`pid=${a}: unparseable response`);continue}let u=px(c);if(u)return u;s.push(`pid=${a}: response had no quota groups`)}else l.status===401||l.status===403?s.push(`pid=${a}: HTTP ${l.status} unauthorized`):s.push(`pid=${a}: HTTP ${l.status}`)}catch(l){s.push(`pid=${a}: ${l instanceof Error?l.message:String(l)}`)}return Le("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${s.slice(0,5).join("; ")}`,"agy_connect_rpc",n.map(([,i])=>i))}async function yh(t){let e=mx(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let r=await hx(t.timeoutSeconds,t.env,t);return r.status==="ok"?r:Le("agy","provider_unavailable","cli_and_language_server_unavailable",`cli: ${String(e.reason??e.status)} (${String(e.detail??"no detail")}); connect: ${String(r.reason??r.status)} (${String(r.detail??"no detail")})`,"agy_cli_print")}import{spawnSync as kh}from"node:child_process";import{randomUUID as wh}from"node:crypto";import{mkdirSync as gx,readFileSync as Cl,realpathSync as _x,renameSync as yx,rmSync as Ol,statSync as Eh,writeFileSync as Sh}from"node:fs";import{homedir as Ex}from"node:os";import{join as Dl}from"node:path";import{setTimeout as Tx}from"node:timers/promises";var wx="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Sx="https://console.anthropic.com/v1/oauth/token",vx=3e5;function Pl(t){return Dl(t.CLAUDE_CONFIG_DIR??Dl(t.HOME??Ex(),".claude"),".credentials.json")}function Ml(t){let e=JSON.parse(Cl(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function Fl(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function vh(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=Pl(t);try{let r=Fl(Ml(e));return typeof r?.accessToken=="string"&&r.accessToken?{oauth:r,path:_x(e)}:{error:"not_claude_ai_subscriber"}}catch(r){return r.code==="ENOENT"?{error:t.ANTHROPIC_API_KEY?"not_claude_ai_subscriber":"no_credentials_found"}:{error:"credentials_unreadable"}}}function bi(t){return typeof t.expiresAt=="number"&&Date.now()+vx>=t.expiresAt}function Th(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function bx(t,e){let r=`${t}.lmctl-refresh.lock`,n=Dl(r,"owner.json"),s=wh();for(;;){e.throwIfAborted();try{gx(r,{mode:448});try{Sh(n,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Ol(r,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(Cl(n,"utf8")).token===s&&Ol(r,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(Cl(n,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-Eh(r).mtimeMs>6e4}catch{try{o=Date.now()-Eh(r).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await Tx(50,void 0,{signal:e})}}}async function bh(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let r=await bx(t.path,e);try{let n=Fl(Ml(t.path));if(!n||typeof n.accessToken!="string")throw new Error("credentials_changed");if(!Th(n,t.oauth)&&!bi(n))return n;if(typeof n.refreshToken!="string"||!n.refreshToken)throw new Error("no_refresh_token");let s=await fetch(Sx,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:n.refreshToken,client_id:wx})});if(!s.ok)throw new Error(`refresh_http_${s.status}`);let i=await s.json();if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||i.refresh_token!==void 0&&(typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)))throw new Error("invalid_refresh_response");let o=Math.floor(Date.now()+i.expires_in*1e3);if(!Number.isSafeInteger(o)||o<=Date.now())throw new Error("invalid_refresh_response");let a=Ml(t.path),l=Fl(a);if(!l||!Th(n,l)){if(l&&typeof l.accessToken=="string"&&!bi(l))return l;throw new Error("credentials_changed")}let c={...l,accessToken:i.access_token,refreshToken:i.refresh_token??n.refreshToken,expiresAt:o,...typeof i.scope=="string"?{scopes:i.scope.split(/\s+/).filter(Boolean)}:{}},u=`${t.path}.${wh()}.tmp`;try{Sh(u,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),yx(u,t.path)}finally{Ol(u,{force:!0})}return c}finally{r()}}var Ix="https://api.anthropic.com",xx="oauth-2025-04-20",Ih="user:profile";function Ax(t){let e=String(t??"").toLowerCase();return e.includes("session")||e.includes("five")||e.includes("5h")?"five_hour":e.includes("week")||e.includes("seven")||e.includes("7d")?"weekly":e.includes("month")||e.includes("30d")?"monthly":"unknown"}var pe={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};function Nh(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function kx(t){try{let e=kh("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:Nh(t)}),r=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(r)return`claude-code/${r}`}catch{}return"claude-code/unknown"}function He(t,e,r,n="claude_oauth_api",s){return Le("claude",t,e,r,n,void 0,s)}function Nx(t){let e=t.get("retry-after");if(!e)return;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:void 0}function Rx(t){if(!t)return;let e=/^([A-Za-z]{3,9})\s+(\d{1,2}),?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?$/i.exec(t.trim());if(!e)return;let r=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"].indexOf(e[1].slice(0,3).toLowerCase());if(r<0)return;let n=Number(e[3]),s=Number(e[4]??0);(e[5]??"").toLowerCase()==="pm"&&n!==12&&(n+=12),(e[5]??"").toLowerCase()==="am"&&n===12&&(n=0);let i=new Date(Date.UTC(new Date().getUTCFullYear(),r,Number(e[2]),n,s));return Number.isFinite(i.getTime())?Math.floor(i.getTime()/1e3):void 0}var Lx=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/;function Cx(t){let e=[];for(let r of t.split(/\r?\n/)){let n=Lx.exec(r.trim());if(!n)continue;let s=n[1].trim(),o=s.toLowerCase()==="session",a=/\(([^)]+)\)/.exec(s)?.[1]?.trim()??s,l=o?"session":a.toLowerCase()==="all models"?"week-all-models":`week-scoped-${a}`,c=o?"five_hour":"weekly";e.push(Re({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:ze(Number(n[2]),"percent"),raw_value:Number(n[2]),raw_scale:"used_percent",resets_at:Rx(n[3])}))}return e.sort((r,n)=>String(r.window_type).localeCompare(String(n.window_type))||String(r.bucket_id).localeCompare(String(n.bucket_id)))}function Ox(t){let e={},r;for(let n of t.split(/\r?\n/)){let s=/^Last\s+(\S+)\s*[·-]\s*(\d+)\s+requests?\s*[·-]\s*(\d+)\s+sessions?\s*$/.exec(n.trim());if(s){r={requests:Number(s[2]),sessions:Number(s[3])},e[`window_${s[1].toLowerCase()}`]=r;continue}let i=/^\s+(\d+)%\s+of your usage\s+(.+?)\s*$/.exec(n);if(!i||!r)continue;let o=i[2].toLowerCase(),a=o.includes(">150k context")?"pct_high_context":o.includes("active for 8+ hours")?"pct_long_sessions":o.includes("subagent-heavy")?"pct_subagent_heavy":o.includes("ran in parallel")?"pct_parallel_sessions":void 0;a&&(r[a]=Number(i[1]))}return e}function xh(t){if(!t||typeof t!="object")return;let e=t,r=e.limit&&typeof e.limit=="object"?e.limit:{},n=e.used&&typeof e.used=="object"?e.used:{},s=r.exponent??n.exponent??2,i=l=>l==null||!Number.isFinite(Number(l))?void 0:(Number(l)/10**Number(s)).toFixed(2),o=ze(e.percent,"percent"),a={limit_usd:i(r.amount_minor),used_usd:i(n.amount_minor),remaining_fraction:o==null?void 0:Math.max(0,1-o),resets_at_iso:e.resets_at};return Object.values(a).every(l=>l==null)?void 0:a}async function Ah(t,e,r,n={}){try{let s=kh("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(r,60)*1e3,input:"",env:Nh(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";Me(n,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=Cx(i);if(!o.length)return;let a=Ox(i);return ge("claude",pe.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:o,...Object.keys(a).length?{characteristics:a}:{}})}catch{return}}async function Rh({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s=vh(e);if(s.error==="not_claude_ai_subscriber")return He(pe.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return He(pe.unavailable,"credentials_missing",`credentials file not found: ${Pl(e)}`);if(s.error)return He(pe.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(Ih))return He(pe.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${Ih} scope required by the usage endpoint`);let a=new AbortController,l=setTimeout(()=>a.abort(),t*1e3),c,u;try{let p=!1,f=async()=>{try{i=await bh({...s,oauth:i},a.signal),p=!0}catch(g){let E=g instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(g.message)?g.message:"refresh_failed";if(E==="refresh_http_429")return He(pe.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(E==="refresh_lock_stale")return He(pe.expired,"oauth_refresh_locked","a previous Claude credential refresh exited without releasing its lock; remove the stale .credentials.json.lmctl-refresh.lock directory before retrying");let v=E==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(E);return He(v?pe.expired:pe.unavailable,v?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${E})${v?"; renew Claude login":"; try again later"}`)}};if(bi(i)){let g=await f();if(g)return g}let y=()=>fetch(`${Ix}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":xx,"Content-Type":"application/json","User-Agent":kx(e)},signal:a.signal});if(c=await y(),u=await c.text(),Me({debug:r,onRawResponse:n},"claude_oauth_api",u,[i.accessToken,i.refreshToken],c.status),c.status===401&&!p&&s.path&&i.refreshToken){let g=await f();if(g)return g;c=await y(),u=await c.text(),Me({debug:r,onRawResponse:n},"claude_oauth_api",u,[i.accessToken,i.refreshToken],c.status)}}catch(p){let f=await Ah(i,e,t,{debug:r,onRawResponse:n});return f||He(pe.unavailable,"request_failed",`${p instanceof Error?p.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let d=(...p)=>Dr(He(...p),u,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return d(pe.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return d(pe.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let p=Nx(c.headers),f=await Ah(i,e,t,{debug:r,onRawResponse:n});return f||d(pe.throttled,"rate_limited",`usage endpoint rate limited${p==null?"":`; retry after ${p}s`}`,"claude_oauth_api",p)}if(c.status!==200)return d(pe.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let m;try{m=JSON.parse(u)}catch{return He(pe.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!m||typeof m!="object"||Array.isArray(m))return He(pe.unavailable,"malformed_response","response was not an object");let h=m,_=Array.isArray(h.limits)?h.limits:[],T=_.length?_.flatMap(p=>{if(!p||typeof p!="object")return[];let f=p.kind,y=Ax(f==="session"?"session":f),g=p.scope?.model?.display_name,E=f==="session"?"session":f==="weekly_all"?"week-all-models":`week-scoped-${g||f}`;return[Re({bucket_id:E,group_name:f==="session"?"session":"weekly",window_type:y,used_fraction:ze(p.percent,"percent"),resets_at_iso:p.resets_at,raw_value:p.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(p=>{let f=h[p];return!f||typeof f!="object"?[]:[Re({bucket_id:p==="five_hour"?"session":"week-all-models",group_name:p==="five_hour"?"session":"weekly",window_type:p==="five_hour"?"five_hour":"weekly",used_fraction:ze(f.utilization,"percent"),resets_at_iso:f.resets_at,raw_value:f.utilization,raw_scale:"used_percent"})]});return ge("claude",pe.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:T.sort((p,f)=>String(p.window_type).localeCompare(String(f.window_type))||String(p.bucket_id).localeCompare(String(f.bucket_id))),...xh(h.spend)?{spend_control:xh(h.spend)}:{}})}import{readFileSync as Dx}from"node:fs";import{homedir as Mx}from"node:os";import{join as Fx}from"node:path";var Px="https://chatgpt.com/backend-api",$x="codex-cli";function Fe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Lh(t){let e=typeof t=="number"?t:Number(t);if(!Number.isFinite(e)||e<=0)return"unknown";let r=e/60;return r>=240&&r<=360?"five_hour":r>=9e3&&r<=11500?"weekly":r>=38e3&&r<=46e3?"monthly":"unknown"}function Ch(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function Ux(t){if(t.CODEX_ACCESS_TOKEN)return{token:t.CODEX_ACCESS_TOKEN,accountId:t.CODEX_ACCOUNT_ID};let e=t.CODEX_AUTH_PATH||Fx(Mx(),".codex","auth.json");try{let r=JSON.parse(Dx(e,"utf8")),n=Fe(r)&&Fe(r.tokens)?r.tokens:void 0,s=n?.access_token,i=n?.account_id;return{token:typeof s=="string"?s:void 0,accountId:typeof i=="string"?i:void 0}}catch{return{}}}function jx(t){if(Fe(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function Hx(t){let e=[],r=Fe(t.rate_limit)?t.rate_limit:{},n=typeof r.allowed=="boolean"?r.allowed:void 0,s=typeof r.limit_reached=="boolean"?r.limit_reached:void 0;for(let o of["primary_window","secondary_window"]){let a=Fe(r[o])?r[o]:void 0;if(!a)continue;let l=Lh(a.limit_window_seconds);e.push(Re({bucket_id:`codex-${Ch(l)}`,group_name:"codex",window_type:l,used_fraction:ze(a.used_percent,"percent"),resets_at:a.reset_at,raw_value:a.used_percent,raw_scale:"used_percent",...n===void 0?{}:{allowed:n},...s===void 0?{}:{limit_reached:s}}))}let i=Array.isArray(t.additional_rate_limits)?t.additional_rate_limits:[];for(let o of i){if(!Fe(o))continue;let a=Fe(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,u=c||l||"additional",d=typeof a.allowed=="boolean"?a.allowed:void 0,m=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let h of["primary_window","secondary_window"]){let _=Fe(a[h])?a[h]:void 0;if(!_)continue;let T=Lh(_.limit_window_seconds);e.push(Re({bucket_id:`${u}-${Ch(T)}`,group_name:l||u,window_type:T,used_fraction:ze(_.used_percent,"percent"),resets_at:_.reset_at,raw_value:_.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...d===void 0?{}:{allowed:d},...m===void 0?{}:{limit_reached:m}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function Bx(t){let e=Fe(t.rate_limit)?t.rate_limit:{},r=typeof e.allowed=="boolean"?e.allowed:void 0,n=Fe(t.spend_control)?t.spend_control:void 0,s=Fe(t.credits)?t.credits:void 0;return ge("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...r===void 0?{}:{ordinary_usage_allowed:r},buckets:Hx(t),...s?{credits:jx(s)}:{},...n?{spend_control:n}:{}})}async function Oh(t){let{timeoutSeconds:e,env:r,debug:n,onRawResponse:s}=t,i=Ux(r);if(!i.token)return ge("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:"no access_token in ~/.codex/auth.json (or $CODEX_ACCESS_TOKEN)"});let o=new AbortController,a=setTimeout(()=>o.abort(),Math.ceil(e*1e3));try{let l={Authorization:`Bearer ${i.token}`,"User-Agent":$x,"Content-Type":"application/json",Accept:"application/json"};i.accountId&&(l["ChatGPT-Account-Id"]=i.accountId);let c=(r.CODEX_BASE_URL||Px).replace(/\/$/,""),u=await fetch(`${c}/wham/usage`,{headers:l,signal:o.signal}),d=await u.text();Me({debug:n,onRawResponse:s},"codex_http",d,[i.token],u.status);let m=(_,T)=>Dr(ge("codex",_,T),d,[i.token]);if(u.status===401)return m("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(u.status===429){let _=u.headers.get("retry-after"),T=_===null?void 0:Number.parseInt(_,10);return m("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...T!==void 0&&Number.isFinite(T)&&T>=0?{retry_after_seconds:T}:{}})}if(!u.ok)return m("provider_unavailable",{source:"codex_http",reason:`http_${u.status}`,detail:"codex usage endpoint returned an unexpected status"});let h;try{h=JSON.parse(d)}catch(_){return ge("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:Or(String(_),[i.token])})}return Fe(h)?Bx(h):ge("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(l){let c=l instanceof Error?`${l.name}: ${l.message}`:String(l);return ge("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:Or(c,[i.token])})}finally{clearTimeout(a)}}import{createHash as Wx,randomUUID as Xx}from"node:crypto";import{readFileSync as $h,openSync as qx,fsyncSync as Gx,closeSync as Jx,mkdirSync as Dh,writeFileSync as Uh,renameSync as Vx,rmSync as Kx,rmdirSync as Yx,statSync as $l,utimesSync as zx}from"node:fs";import{homedir as Qx}from"node:os";import{basename as Zx,dirname as eA,join as Ii}from"node:path";import{setTimeout as jh}from"node:timers/promises";var Mh="https://api.kimi.com/coding/v1",Ul="https://auth.kimi.com",tA="17e5f671-d194-4dfb-9706-5516cb48c098",Fh=t=>t.trim().replace(/\/+$/,"");function rA(t){let e;try{e=$h(t,"utf8")}catch(s){if(s.code==="ENOENT")return{};throw new Error("config_unreadable")}let r={},n="other";for(let s of e.split(/\r?\n/)){let i=/^\s*\[providers\.(?:"managed:kimi-code"|'managed:kimi-code')(\.oauth)?\]\s*(?:#.*)?$/.exec(s);if(i){n=i[1]?"oauth.":"";continue}if(/^\s*\[/.test(s)){if(s.includes("managed:kimi-code"))throw new Error("config_format_unsupported");n="other";continue}if(n==="other")continue;if(/^\s*oauth\s*=/.test(s))throw new Error("config_format_unsupported");let o=/^\s*(base_url|oauth_host|storage|key)\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(s);if(!o&&/^\s*(base_url|oauth_host|storage|key)\s*=/.test(s))throw new Error("config_malformed");if(o)try{r[n+o[1]]=o[2].startsWith('"')?JSON.parse(o[2]):o[2].slice(1,-1)}catch{throw new Error("config_malformed")}}return r}function xi(t){let e;try{e=JSON.parse($h(t,"utf8"))}catch(r){throw new Error(r.code==="ENOENT"?"credentials_missing":"credentials_malformed")}if(e&&typeof e=="object"&&e.access_token===""&&e.refresh_token==="")throw new Error("credentials_revoked");if(!e||typeof e!="object"||Array.isArray(e)||typeof e.access_token!="string"||!e.access_token.trim())throw new Error("credentials_malformed");return e}function Hh(t){let e=t.KIMI_CODE_HOME??Ii(t.HOME??Qx(),".kimi-code"),r=rA(t.KIMI_CODE_CONFIG_PATH??Ii(e,"config.toml")),n=t.KIMI_CODE_BASE_URL!==void 0||t.KIMI_CODE_OAUTH_HOST!==void 0||t.KIMI_OAUTH_HOST!==void 0,s=Fh(t.KIMI_CODE_BASE_URL??r.base_url??Mh),i=Fh(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(n?Ul:r["oauth.oauth_host"]??Ul)),o=s===Mh&&i===Ul?"kimi-code":`kimi-code-env-${Wx("sha256").update(JSON.stringify({oauthHost:i,baseUrl:s})).digest("hex").slice(0,16)}`;if(!t.KIMI_CREDENTIALS_PATH&&!n&&r["oauth.key"]===`oauth/${o}`&&r["oauth.storage"]&&r["oauth.storage"]!=="file")throw new Error("credential_storage_unsupported");let a=t.KIMI_CREDENTIALS_PATH??Ii(e,"credentials",`${o}.json`),l=xi(a),c=a,u=Zx(a,".json");return{home:e,path:c,lockTarget:Ii(e,"oauth",u),baseUrl:s,oauthHost:i,token:l}}function Ai(t){if(typeof t.expires_at!="number")return!1;let e=typeof t.expires_in=="number"?t.expires_in:0;return t.expires_at-Date.now()/1e3<Math.max(300,e*.5)}function Ph(t,e){return t.access_token===e.access_token&&t.refresh_token===e.refresh_token&&t.expires_at===e.expires_at&&t.expires_in===e.expires_in}async function nA(t,e){Dh(eA(t),{recursive:!0}),Uh(t,"",{flag:"a",mode:384});let r=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{Dh(r);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-$l(r).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await jh(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let n=$l(r),s=()=>{let o;try{o=$l(r)}catch{throw new Error("refresh_lock_lost")}if(o.ino!==n.ino||o.dev!==n.dev)throw new Error("refresh_lock_lost")},i=setInterval(()=>{try{s();let o=new Date;zx(r,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),Yx(r)}catch{}}}}async function Bh(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let r=await nA(t.lockTarget,e);try{let n=xi(t.path);if(!Ph(n,t.token)&&!Ai(n))return n;if(typeof n.refresh_token!="string"||!n.refresh_token)throw new Error("no_refresh_token");let s;for(let d=0;d<3;d++){try{if(s=await fetch(`${t.oauthHost}/api/oauth/token`,{method:"POST",signal:e,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":"lmctl"},body:new URLSearchParams({client_id:tA,grant_type:"refresh_token",refresh_token:n.refresh_token})}),![429,500,502,503,504].includes(s.status)||d===2)break;await s.body?.cancel()}catch{if(e.aborted||d===2)throw new Error("refresh_request_failed")}await jh(1e3*2**d,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let d=xi(t.path);if(d.refresh_token!==n.refresh_token)return d}catch{}throw new Error(`refresh_http_${s.status}`)}let i=await s.json(),o=Number(i?.expires_in);if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)||!Number.isFinite(o)||o<=0)throw new Error("invalid_refresh_response");let a=Math.floor(Date.now()/1e3)+o;if(!Number.isSafeInteger(a))throw new Error("invalid_refresh_response");r.assertOwned();let l=xi(t.path);if(!Ph(l,n)){if(!Ai(l))return l;throw new Error("credentials_changed")}let c={...l,access_token:i.access_token,refresh_token:i.refresh_token,expires_at:a,expires_in:o,...typeof i.scope=="string"?{scope:i.scope}:{},...typeof i.token_type=="string"?{token_type:i.token_type}:{}},u=`${t.path}.${Xx()}.tmp`;try{let d=qx(u,"wx",384);try{Uh(d,JSON.stringify(c,null,2)+`
|
|
2172
|
-
`),Gx(d)}finally{Jx(d)}r.assertOwned(),Vx(u,t.path)}finally{Kx(u,{force:!0})}return c}finally{r.release()}}async function Wh({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s;try{s=Hh(e)}catch(T){let p=T instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(T.message)?T.message:"credentials_unreadable";return Le("kimi",p==="credentials_revoked"?"auth_expired":"provider_unavailable",p,p==="credentials_revoked"?"Kimi login was revoked; run kimi login":p.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let T=!1,p=async()=>{i=await Bh({...s,token:i},o.signal),T=!0};Ai(i)&&await p();let f=()=>fetch(`${s.baseUrl}/usages`,{headers:{Authorization:`Bearer ${i.access_token}`,Accept:"application/json"},signal:o.signal});l=await f(),c=await l.text(),Me({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!T&&i.refresh_token&&(await p(),l=await f(),c=await l.text(),Me({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(T){let p=T instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(T.message)?T.message:"request_failed",f=p==="credentials_revoked"||p==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(p),y=p==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":f?`Kimi credential renewal failed (${p}); run kimi login`:`Kimi quota request failed (${p})`;return Le("kimi",f?"auth_expired":"provider_unavailable",p,y,"kimi_http")}finally{clearTimeout(a)}let u=(T,p,f)=>Dr(Le("kimi",T,p,p,"kimi_http",[],f),c,[i.access_token]);if(l.status===401)return u("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return u("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let T=hh(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",T)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return Le("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return Le("kimi","provider_unavailable","malformed_response","response was not an object");let m=[],h=new Set;function _(T){let p=String(T.bucket_id),f=p,y=2;for(;h.has(p);)p=`${f}-${y}`,y++;h.add(p),T.bucket_id=p,m.push(Re(T))}if(Array.isArray(d.limits))for(let T of d.limits){if(!T||typeof T!="object")continue;let p=T.window,f=T.detail;if(!p||typeof p!="object"||!f||typeof f!="object")continue;let y=0;if(p.timeUnit==="TIME_UNIT_MINUTE")y=Number(p.duration);else if(p.timeUnit==="TIME_UNIT_HOUR")y=Number(p.duration)*60;else if(p.timeUnit==="TIME_UNIT_DAY")y=Number(p.duration)*1440;else if(p.timeUnit==="TIME_UNIT_WEEK")y=Number(p.duration)*10080;else if(p.timeUnit==="TIME_UNIT_MONTH")y=Number(p.duration)*43200;else continue;let g=fh(y),E="window";g==="five_hour"&&(E="5h"),g==="weekly"&&(E="weekly"),g==="monthly"&&(E="monthly"),f.used===void 0&&(f.used=0),f.limit===void 0&&(f.limit=0);let v=Number(f.used),w=Number(f.limit);if(!Number.isFinite(v)||!Number.isFinite(w)||w<=0||v<0)continue;let b=Math.max(0,w-v);if(f.remaining!==void 0){let S=Number(f.remaining);Number.isFinite(S)&&(b=S)}_({bucket_id:`kimi-${E}`,window_type:g,used_fraction:Se(v/w),remaining_fraction:Se(b/w),resets_at_iso:f.resetTime,raw_value:(Number.isInteger(v),v),raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let T=d.usage.used,p=d.usage.limit;if(T!==void 0&&p!==void 0){let f=Number(T),y=Number(p);if(Number.isFinite(f)&&Number.isFinite(y)&&y>0&&f>=0){let g=Math.max(0,y-f);if(d.usage.remaining!==void 0){let E=Number(d.usage.remaining);Number.isFinite(E)&&(g=E)}_({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:Se(f/y),remaining_fraction:Se(g/y),resets_at_iso:d.usage.resetTime,raw_value:(Number.isInteger(f),f),raw_scale:"count"})}}}if(d.usages&&typeof d.usages=="object"){let T=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:p,id:f,type:y}of T){let g=d.usages[p];if(!g||typeof g!="object"||g.used_ratio==null||g.used_ratio===""||typeof g.used_ratio=="boolean")continue;let E=Number(g.used_ratio);if(!Number.isFinite(E)||E<0)continue;let v=new RegExp(`^${f}(?:-\\d+)?$`);for(let w=m.length-1;w>=0;w--)v.test(String(m[w].bucket_id))&&m.splice(w,1);h.add(f),m.push(Re({bucket_id:f,window_type:y,used_fraction:Se(E),resets_at_iso:typeof g.reset_time=="string"&&g.reset_time?g.reset_time:null,raw_value:E,raw_scale:"ratio"}))}}return ge("kimi","ok",{source:"kimi_http",buckets:m})}var Xh=["all","codex","agy","claude","kimi"],sA=15;async function qh(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let a of e)if(!Xh.includes(a))return{status:"error",error:`unknown provider: ${a} (valid targets: ${Xh.join(", ")})`,readings:[]};let r=t.timeoutSeconds??sA;if(!Number.isFinite(r)||r<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=t.env??process.env,s=new Set(e.includes("all")?["codex","agy","claude","kimi"]:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${r}s per provider) ...`);let o=Object.entries({codex:Oh,agy:yh,claude:Rh,kimi:Wh}).filter(([a])=>s.has(a)).map(async([,a])=>{let l=[],c=await a({timeoutSeconds:r,env:n,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:u=>l.push(u)}:{}});return t.includeRaw?{...c,raw_responses:l}:c});try{return{status:"ok",readings:(await Promise.all(o)).filter(Boolean)}}catch(a){return{status:"error",error:String(a),readings:[]}}}Eo();In();_r();mr();zr();Mt();fi();ts();rs();import{execFile as iA}from"node:child_process";import{mkdtempSync as oA,realpathSync as jl,rmSync as aA,statSync as zh}from"node:fs";import{tmpdir as Qh}from"node:os";import{isAbsolute as Hl,join as Gh,relative as lA}from"node:path";import{promisify as cA}from"node:util";var dA=cA(iA),uA=[{name:"lmbee_queue_list",category:"Queue Management",signature:"lmbee_queue_list(snapshot_db, team = null, options = null)",description:"Lists queue rows from a temporary lmbee database copy, read directly (no lmbee executable needed).",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"},{name:"options",type:"map",description:`Optional { scope, limit, after_id }: scope "recent" (default) is the newest 30 rows; scope "unfinished" is every genuinely open row (lmauto's listUnfinishedQueue predicate); scope "all" is every row. limit (1-200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:"{ queue: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; each row carries hasAnswer (current, non-superseded answer)"},example:'page = lmbee_queue_list("/tmp/lmbee-copy/state.db", null, {"scope":"unfinished","limit":200});'},{name:"lmbee_queue_get",category:"Queue Management",signature:"lmbee_queue_get(snapshot_db, id)",description:"Gets one queue row from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer queue ID"}],returns:{type:"map",description:"{ queue: row, hasAnswer: boolean } or a queue_not_found error object"},example:'item = lmbee_queue_get("/tmp/lmbee-copy/state.db", 7);'},{name:"lmbee_queue_stats",category:"Queue Management",signature:"lmbee_queue_stats(snapshot_db, team = null)",description:"Reads per-recipient queue counts from a temporary lmbee database copy, without a row window.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"}],returns:{type:"map",description:"{ stats: [...] } most-stale-first; team_progress-sourced fields (escalationAttemptCount, lastEscalationAttemptTs, quota*) default to 0/null when the snapshot predates that table"},example:'counts = lmbee_queue_stats("/tmp/lmbee-copy/state.db", "worker");'},{name:"lmbee_snapshot",category:"Queue Management",signature:"lmbee_snapshot(source_db)",description:"Creates a WAL-aware temporary database backup, removed when the script ends.",parameters:[{name:"source_db",type:"string",description:"Absolute path to an existing lmbee database"}],returns:{type:"string",description:"Temporary snapshot path for lmbee queue functions"},example:'snapshot = lmbee_snapshot(env("HOME") + "/.lmbee/state.db");'}];function Zh(t){if(typeof t!="string"||!t||!Hl(t))throw new Error("lmbee: snapshot_db must be an absolute path to a temporary database copy");let e;try{e=jl(t);let n=zh(e);if(!n.isFile()||n.nlink!==1)throw new Error("not a standalone file")}catch{throw new Error("lmbee: snapshot_db must be an existing temporary database copy")}let r=lA(jl(Qh()),e);if(!r||r===".."||r.startsWith("../")||Hl(r))throw new Error("lmbee: snapshot_db must be a temporary database copy inside the system temp directory");return e}function Jh(t){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error("lmbee: team must be a nonempty string");return t}}function mA(t){if(t==null)return{scope:"recent",limit:200};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.scope??"recent";if(r!=="recent"&&r!=="unfinished"&&r!=="all")throw new Error("lmbee: scope must be recent, unfinished, or all");let n=e.limit??200;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let s=e.after_id;if(s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0))throw new Error("lmbee: after_id must be a positive integer");if(r==="recent"&&(e.limit!==void 0||s!==void 0))throw new Error("lmbee: limit and after_id require unfinished or all scope");return{scope:r,limit:n,afterId:s}}var fA=["id","from_id","to_id","status","created_ts","expects_response","in_reply_to","retracted_ts","escalation_claimed_ts"],pA=["prompt_queue_id","superseded_at"],hA=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],gA=`q.status != 'merged'
|
|
2167
|
+
`}function ux(t){return t==="claude"||t==="codex"||t==="gemini"||t==="copilot"||t==="opencode"||t==="lmplayer"||t==="qwen"||t==="agy"||t==="kimi"||t==="dsh"||t==="hermes"||t==="pi"||t==="ClaudeMock"}function Yt(t,e){return t.stderr.write(`error: ${e}
|
|
2168
|
+
`),1}function Ol(t,e){for(let r of t)r.teamfile!==void 0&&e.stderr.write(`warning: member "${r.alias}" uses deprecated member-level teamfile=; cross-team calls now work at runtime without _CONNECT_
|
|
2169
|
+
`),r.provider==="gemini"&&e.stderr.write(`${WI.replace("%s",r.alias)}
|
|
2170
|
+
`)}et();var mx="https://lmctl.com/schemas/lmratelimit-v1.json";function Se(t){if(t==null||typeof t=="boolean")return null;let e=Number(t);return Number.isFinite(e)?Math.round(Math.min(1,Math.max(0,e))*1e6)/1e6:null}function ze(t,e){if(t==null||typeof t=="boolean")return null;let r=Number(t);return Se(e==="percent"?r/100:r)}function ph(t){if(t==null||typeof t=="boolean")return null;let e=Number(t);if(!Number.isFinite(e))return null;try{return new Date(Math.trunc(e)*1e3).toISOString().replace(".000Z","Z")}catch{return null}}function hh(t){if(typeof t!="string"||t.trim()==="")return null;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):null}function gh(t){let e=Number(t);return Number.isFinite(e)?e===300||e>=240&&e<=360?"five_hour":e===10080||e>=9e3&&e<=11500?"weekly":e===43200||e===44640||e>=38e3&&e<=46e3?"monthly":"unknown":"unknown"}function _h(t){let e=String(t??"").trim().toLowerCase().replace(/-/g,"_").split("_").filter(Boolean);for(let r of[e[0],e.at(-1)]){if(r?.startsWith("5h")||r?.startsWith("five")||r==="session")return"five_hour";if(r?.startsWith("7d")||r?.startsWith("seven")||r?.startsWith("week"))return"weekly";if(r?.startsWith("30d")||r?.startsWith("month"))return"monthly"}return"unknown"}var fx=[/sk-ant-[A-Za-z0-9_-]{4,}/g,/sk-[A-Za-z0-9_-]{16,}/g,/\bbearer\s+[A-Za-z0-9._-]{8,}/gi,/\boat01[-_][A-Za-z0-9_-]{8,}/g,/\bcsrf[-_][A-Za-z0-9_-]{4,}/gi,/\b(?:csrf[-_]?token|x-codeium-csrf-token)\s*[:=]\s*['"]?[A-Za-z0-9._-]{4,}/gi];function Dr(t,e=[]){let r=t==null?"":String(t);for(let n of e)typeof n=="string"&&n.length>=4&&(r=r.replaceAll(n,"***REDACTED***"));for(let n of fx)r=r.replace(n,"***REDACTED***");return r}function Re(t){let e=Se(t.used_fraction),r=Se(t.remaining_fraction),n=t.resets_at==null?hh(t.resets_at_iso):Number(t.resets_at),s=t.resets_at_iso==null?ph(n):ph(hh(t.resets_at_iso)),i={bucket_id:t.bucket_id,...t.group_name!=null?{group_name:t.group_name}:{},window_type:t.window_type??"unknown",used_fraction:e??(r===null?null:Se(1-r)),remaining_fraction:r??(e===null?null:Se(1-e)),resets_at:n==null||!Number.isFinite(n)?null:Math.trunc(n),resets_at_iso:s,is_exhausted:t.is_exhausted??(r!==null?r<=0:e!==null?e>=1:null)};for(let o of["raw_value","raw_scale","limit_name","metered_feature","allowed","limit_reached"])t[o]!=null&&(i[o]=t[o]);return i}function ge(t,e,r={}){let n={$schema:mx,provider:t,status:e,source:r.source??null,read_at:r.read_at??Math.floor(Date.now()/1e3),account_id:r.account_id??null,plan_type:r.plan_type??null,ordinary_usage_allowed:r.ordinary_usage_allowed??null,buckets:r.buckets??[]};for(let s of["credits","spend_control","characteristics","reason","detail","retry_after_seconds"])r[s]!=null&&(n[s]=r[s]);return n}function Le(t,e,r,n,s,i=[],o){return ge(t,e,{source:s??null,reason:r,...n==null?{}:{detail:Dr(n,i)},...o==null?{}:{retry_after_seconds:o}})}function yh(t){let e=t.get("retry-after");if(e===null)return null;let r=Number.parseFloat(e);return Number.isFinite(r)&&r>=0?Math.trunc(r):null}function Me(t,e,r,n=[],s){if(!t.debug&&!t.onRawResponse)return;let i=Dr(r,[...n].filter(o=>typeof o=="string")).replace(/("(?:access[_-]?token|refresh[_-]?token|authorization|api[_-]?key|password)"\s*:\s*")[^"\r\n]*(")/gi,"$1***REDACTED***$2");t.onRawResponse?.({source:e,...s===void 0?{}:{http_status:s},text:i}),t.debug?.(`[debug] ${e}${s===void 0?"":` HTTP ${s}`} raw response:
|
|
2171
|
+
${i}`)}function Mr(t,e,r=[]){let n;try{let i=JSON.parse(e);n=typeof i?.error=="string"?i.error:i?.error?.message??i?.message??i?.detail}catch{/^\s*[<{[]/.test(e)||(n=e.trim())}if(typeof n!="string"||!n.trim())return t;let s=Dr(n,r);return{...t,detail:s,provider_message:s}}import{spawnSync as px}from"node:child_process";import{readdirSync as hx,readFileSync as gx}from"node:fs";import{join as _x}from"node:path";var Eh="ANTIGRAVITY_LS_ADDRESS",Th="ANTIGRAVITY_CSRF_TOKEN",yx="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",Ex=["-p","/usage"],Tx=(t,e)=>{let r=px("agy",Ex,{encoding:"utf8",timeout:t,maxBuffer:16777216,env:e,stdio:["ignore","pipe","ignore"]});return{status:r.status,stdout:typeof r.stdout=="string"?r.stdout:"",error:r.error}},wx=async(t,e,r)=>{let n=await fetch(t,{method:"POST",headers:e,body:"{}",signal:AbortSignal.timeout(r)});return{status:n.status,body:await n.text()}},Sx=Tx,vx=wx;function bx(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function Ix(t){let e=t.trim().toLowerCase(),r={"gemini models":"gemini","claude and gpt models":"3p",gemini:"gemini","3p models":"3p","3p":"3p"};return r[e]?r[e]:e.replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function xx(t){let e=t.toLowerCase();return e.includes("weekly")?"weekly":e.includes("five hour")||e.includes("5-hour")||e.includes("5 hour")?"five_hour":e.includes("monthly")||e.includes("month")?"monthly":null}function Ax(t){let e={weekly:"weekly",five_hour:"5h",monthly:"monthly"},r=[];for(let n of t.split(/\r?\n/)){let s=n.trim().split(" ").map(l=>l.trim());if(s.length<3||!s[0]||!s[1])continue;let i=xx(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=Se(o/100);r.push(Re({bucket_id:`${Ix(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:Se(1-a),remaining_fraction:a,resets_at_iso:s[3]||null,raw_value:o,raw_scale:"remaining_percent"}))}return r.sort((n,s)=>String(n.group_name??"").localeCompare(String(s.group_name??""))||String(n.bucket_id??"").localeCompare(String(s.bucket_id??"")))}function Dn(t,e,r){return Le("agy","provider_unavailable",t,e,"agy_cli_print")}function kx(t,e,r={}){try{let n=Sx(Math.max(t,60)*1e3,bx(e));if(Me(r,"agy_cli_print",n.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),n.error?.code==="ENOENT")return Dn("agy_not_found","the agy CLI is not on PATH",t);if(n.error?.code==="ETIMEDOUT")return Dn("cli_timeout","agy -p /usage did not finish in time",t);if(n.error)return Dn("cli_failed",n.error.message,t);let s=Ax(n.stdout??"");return s.length===0?Dn("cli_unparseable",`exit ${n.status??1}; no buckets parsed from CLI output`,t):ge("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(n){return Dn("cli_failed",n instanceof Error?n.message:String(n),t)}}function Nx(t){let e=[],r=new Set,n=(s,i,o)=>{!s||!i||r.has(`${s}\0${i}`)||(r.add(`${s}\0${i}`),e.push([s,i,o]))};n(t[Eh],t[Th],-1);try{for(let s of hx("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of gx(_x("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}n(i[Eh],i[Th],Number(s))}catch{}}catch{}return e}function Rx(t){if(typeof t!="object"||t===null)return null;let e=t.response;if(typeof e!="object"||e===null)return null;let r=e.groups;if(!Array.isArray(r))return null;let n=[];for(let s of r){if(typeof s!="object"||s===null)continue;let i=s,o=typeof i.displayName=="string"?i.displayName:null;if(Array.isArray(i.buckets))for(let a of i.buckets){if(typeof a!="object"||a===null)continue;let l=a,c=ze(l.remainingFraction,"fraction");n.push(Re({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:_h(l.window),used_fraction:c===null?null:Se(1-c),remaining_fraction:c,resets_at_iso:l.resetTime??null,raw_value:l.remainingFraction??null,raw_scale:"remaining_fraction"}))}}return n.length===0?null:(n.sort((s,i)=>String(s.group_name??"").localeCompare(String(i.group_name??""))||String(s.bucket_id??"").localeCompare(String(i.bucket_id??""))),ge("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n}))}async function Lx(t,e,r={}){let n=Nx(e);if(n.length===0)return Le("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let s=[];for(let[i,o,a]of n)try{let l=await vx(`http://${i}${yx}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":o},t*1e3);if(Me(r,"agy_connect_rpc",l.body,[o],l.status),l.status===200){let c;try{c=JSON.parse(l.body)}catch{s.push(`pid=${a}: unparseable response`);continue}let u=Rx(c);if(u)return u;s.push(`pid=${a}: response had no quota groups`)}else l.status===401||l.status===403?s.push(`pid=${a}: HTTP ${l.status} unauthorized`):s.push(`pid=${a}: HTTP ${l.status}`)}catch(l){s.push(`pid=${a}: ${l instanceof Error?l.message:String(l)}`)}return Le("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${s.slice(0,5).join("; ")}`,"agy_connect_rpc",n.map(([,i])=>i))}async function wh(t){let e=kx(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let r=await Lx(t.timeoutSeconds,t.env,t);return r.status==="ok"?r:Le("agy","provider_unavailable","cli_and_language_server_unavailable",`cli: ${String(e.reason??e.status)} (${String(e.detail??"no detail")}); connect: ${String(r.reason??r.status)} (${String(r.detail??"no detail")})`,"agy_cli_print")}import{spawnSync as Lh}from"node:child_process";import{randomUUID as bh}from"node:crypto";import{mkdirSync as Cx,readFileSync as Dl,realpathSync as Ox,renameSync as Dx,rmSync as Ml,statSync as Sh,writeFileSync as Ih}from"node:fs";import{homedir as Mx}from"node:os";import{join as Fl}from"node:path";import{setTimeout as Fx}from"node:timers/promises";var Px="9d1c250a-e61b-44d9-88ed-5944d1962f5e",$x="https://console.anthropic.com/v1/oauth/token",Ux=3e5;function Ul(t){return Fl(t.CLAUDE_CONFIG_DIR??Fl(t.HOME??Mx(),".claude"),".credentials.json")}function Pl(t){let e=JSON.parse(Dl(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function $l(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function xh(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=Ul(t);try{let r=$l(Pl(e));return typeof r?.accessToken=="string"&&r.accessToken?{oauth:r,path:Ox(e)}:{error:"not_claude_ai_subscriber"}}catch(r){return r.code==="ENOENT"?{error:t.ANTHROPIC_API_KEY?"not_claude_ai_subscriber":"no_credentials_found"}:{error:"credentials_unreadable"}}}function Ii(t){return typeof t.expiresAt=="number"&&Date.now()+Ux>=t.expiresAt}function vh(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function jx(t,e){let r=`${t}.lmctl-refresh.lock`,n=Fl(r,"owner.json"),s=bh();for(;;){e.throwIfAborted();try{Cx(r,{mode:448});try{Ih(n,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Ml(r,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(Dl(n,"utf8")).token===s&&Ml(r,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(Dl(n,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-Sh(r).mtimeMs>6e4}catch{try{o=Date.now()-Sh(r).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await Fx(50,void 0,{signal:e})}}}async function Ah(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let r=await jx(t.path,e);try{let n=$l(Pl(t.path));if(!n||typeof n.accessToken!="string")throw new Error("credentials_changed");if(!vh(n,t.oauth)&&!Ii(n))return n;if(typeof n.refreshToken!="string"||!n.refreshToken)throw new Error("no_refresh_token");let s=await fetch($x,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:n.refreshToken,client_id:Px})});if(!s.ok)throw new Error(`refresh_http_${s.status}`);let i=await s.json();if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||i.refresh_token!==void 0&&(typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)))throw new Error("invalid_refresh_response");let o=Math.floor(Date.now()+i.expires_in*1e3);if(!Number.isSafeInteger(o)||o<=Date.now())throw new Error("invalid_refresh_response");let a=Pl(t.path),l=$l(a);if(!l||!vh(n,l)){if(l&&typeof l.accessToken=="string"&&!Ii(l))return l;throw new Error("credentials_changed")}let c={...l,accessToken:i.access_token,refreshToken:i.refresh_token??n.refreshToken,expiresAt:o,...typeof i.scope=="string"?{scopes:i.scope.split(/\s+/).filter(Boolean)}:{}},u=`${t.path}.${bh()}.tmp`;try{Ih(u,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),Dx(u,t.path)}finally{Ml(u,{force:!0})}return c}finally{r()}}var Hx="https://api.anthropic.com",Bx="oauth-2025-04-20",kh="user:profile";function Wx(t){let e=String(t??"").toLowerCase();return e.includes("session")||e.includes("five")||e.includes("5h")?"five_hour":e.includes("week")||e.includes("seven")||e.includes("7d")?"weekly":e.includes("month")||e.includes("30d")?"monthly":"unknown"}var pe={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};function Ch(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function Xx(t){try{let e=Lh("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:Ch(t)}),r=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(r)return`claude-code/${r}`}catch{}return"claude-code/unknown"}function He(t,e,r,n="claude_oauth_api",s){return Le("claude",t,e,r,n,void 0,s)}function qx(t){let e=t.get("retry-after");if(!e)return;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:void 0}function Gx(t){if(!t)return;let e=/^([A-Za-z]{3,9})\s+(\d{1,2}),?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?$/i.exec(t.trim());if(!e)return;let r=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"].indexOf(e[1].slice(0,3).toLowerCase());if(r<0)return;let n=Number(e[3]),s=Number(e[4]??0);(e[5]??"").toLowerCase()==="pm"&&n!==12&&(n+=12),(e[5]??"").toLowerCase()==="am"&&n===12&&(n=0);let i=new Date(Date.UTC(new Date().getUTCFullYear(),r,Number(e[2]),n,s));return Number.isFinite(i.getTime())?Math.floor(i.getTime()/1e3):void 0}var Jx=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/;function Kx(t){let e=[];for(let r of t.split(/\r?\n/)){let n=Jx.exec(r.trim());if(!n)continue;let s=n[1].trim(),o=s.toLowerCase()==="session",a=/\(([^)]+)\)/.exec(s)?.[1]?.trim()??s,l=o?"session":a.toLowerCase()==="all models"?"week-all-models":`week-scoped-${a}`,c=o?"five_hour":"weekly";e.push(Re({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:ze(Number(n[2]),"percent"),raw_value:Number(n[2]),raw_scale:"used_percent",resets_at:Gx(n[3])}))}return e.sort((r,n)=>String(r.window_type).localeCompare(String(n.window_type))||String(r.bucket_id).localeCompare(String(n.bucket_id)))}function Vx(t){let e={},r;for(let n of t.split(/\r?\n/)){let s=/^Last\s+(\S+)\s*[·-]\s*(\d+)\s+requests?\s*[·-]\s*(\d+)\s+sessions?\s*$/.exec(n.trim());if(s){r={requests:Number(s[2]),sessions:Number(s[3])},e[`window_${s[1].toLowerCase()}`]=r;continue}let i=/^\s+(\d+)%\s+of your usage\s+(.+?)\s*$/.exec(n);if(!i||!r)continue;let o=i[2].toLowerCase(),a=o.includes(">150k context")?"pct_high_context":o.includes("active for 8+ hours")?"pct_long_sessions":o.includes("subagent-heavy")?"pct_subagent_heavy":o.includes("ran in parallel")?"pct_parallel_sessions":void 0;a&&(r[a]=Number(i[1]))}return e}function Nh(t){if(!t||typeof t!="object")return;let e=t,r=e.limit&&typeof e.limit=="object"?e.limit:{},n=e.used&&typeof e.used=="object"?e.used:{},s=r.exponent??n.exponent??2,i=l=>l==null||!Number.isFinite(Number(l))?void 0:(Number(l)/10**Number(s)).toFixed(2),o=ze(e.percent,"percent"),a={limit_usd:i(r.amount_minor),used_usd:i(n.amount_minor),remaining_fraction:o==null?void 0:Math.max(0,1-o),resets_at_iso:e.resets_at};return Object.values(a).every(l=>l==null)?void 0:a}async function Rh(t,e,r,n={}){try{let s=Lh("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(r,60)*1e3,input:"",env:Ch(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";Me(n,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=Kx(i);if(!o.length)return;let a=Vx(i);return ge("claude",pe.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:o,...Object.keys(a).length?{characteristics:a}:{}})}catch{return}}async function Oh({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s=xh(e);if(s.error==="not_claude_ai_subscriber")return He(pe.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return He(pe.unavailable,"credentials_missing",`credentials file not found: ${Ul(e)}`);if(s.error)return He(pe.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(kh))return He(pe.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${kh} scope required by the usage endpoint`);let a=new AbortController,l=setTimeout(()=>a.abort(),t*1e3),c,u;try{let p=!1,f=async()=>{try{i=await Ah({...s,oauth:i},a.signal),p=!0}catch(g){let E=g instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(g.message)?g.message:"refresh_failed";if(E==="refresh_http_429")return He(pe.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(E==="refresh_lock_stale")return He(pe.expired,"oauth_refresh_locked","a previous Claude credential refresh exited without releasing its lock; remove the stale .credentials.json.lmctl-refresh.lock directory before retrying");let v=E==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(E);return He(v?pe.expired:pe.unavailable,v?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${E})${v?"; renew Claude login":"; try again later"}`)}};if(Ii(i)){let g=await f();if(g)return g}let y=()=>fetch(`${Hx}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":Bx,"Content-Type":"application/json","User-Agent":Xx(e)},signal:a.signal});if(c=await y(),u=await c.text(),Me({debug:r,onRawResponse:n},"claude_oauth_api",u,[i.accessToken,i.refreshToken],c.status),c.status===401&&!p&&s.path&&i.refreshToken){let g=await f();if(g)return g;c=await y(),u=await c.text(),Me({debug:r,onRawResponse:n},"claude_oauth_api",u,[i.accessToken,i.refreshToken],c.status)}}catch(p){let f=await Rh(i,e,t,{debug:r,onRawResponse:n});return f||He(pe.unavailable,"request_failed",`${p instanceof Error?p.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let d=(...p)=>Mr(He(...p),u,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return d(pe.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return d(pe.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let p=qx(c.headers),f=await Rh(i,e,t,{debug:r,onRawResponse:n});return f||d(pe.throttled,"rate_limited",`usage endpoint rate limited${p==null?"":`; retry after ${p}s`}`,"claude_oauth_api",p)}if(c.status!==200)return d(pe.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let m;try{m=JSON.parse(u)}catch{return He(pe.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!m||typeof m!="object"||Array.isArray(m))return He(pe.unavailable,"malformed_response","response was not an object");let h=m,_=Array.isArray(h.limits)?h.limits:[],T=_.length?_.flatMap(p=>{if(!p||typeof p!="object")return[];let f=p.kind,y=Wx(f==="session"?"session":f),g=p.scope?.model?.display_name,E=f==="session"?"session":f==="weekly_all"?"week-all-models":`week-scoped-${g||f}`;return[Re({bucket_id:E,group_name:f==="session"?"session":"weekly",window_type:y,used_fraction:ze(p.percent,"percent"),resets_at_iso:p.resets_at,raw_value:p.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(p=>{let f=h[p];return!f||typeof f!="object"?[]:[Re({bucket_id:p==="five_hour"?"session":"week-all-models",group_name:p==="five_hour"?"session":"weekly",window_type:p==="five_hour"?"five_hour":"weekly",used_fraction:ze(f.utilization,"percent"),resets_at_iso:f.resets_at,raw_value:f.utilization,raw_scale:"used_percent"})]});return ge("claude",pe.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:T.sort((p,f)=>String(p.window_type).localeCompare(String(f.window_type))||String(p.bucket_id).localeCompare(String(f.bucket_id))),...Nh(h.spend)?{spend_control:Nh(h.spend)}:{}})}import{readFileSync as Yx}from"node:fs";import{homedir as zx}from"node:os";import{join as Qx}from"node:path";var Zx="https://chatgpt.com/backend-api",eA="codex-cli";function Fe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Dh(t){let e=typeof t=="number"?t:Number(t);if(!Number.isFinite(e)||e<=0)return"unknown";let r=e/60;return r>=240&&r<=360?"five_hour":r>=9e3&&r<=11500?"weekly":r>=38e3&&r<=46e3?"monthly":"unknown"}function Mh(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function tA(t){if(t.CODEX_ACCESS_TOKEN)return{token:t.CODEX_ACCESS_TOKEN,accountId:t.CODEX_ACCOUNT_ID};let e=t.CODEX_AUTH_PATH||Qx(zx(),".codex","auth.json");try{let r=JSON.parse(Yx(e,"utf8")),n=Fe(r)&&Fe(r.tokens)?r.tokens:void 0,s=n?.access_token,i=n?.account_id;return{token:typeof s=="string"?s:void 0,accountId:typeof i=="string"?i:void 0}}catch{return{}}}function rA(t){if(Fe(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function nA(t){let e=[],r=Fe(t.rate_limit)?t.rate_limit:{},n=typeof r.allowed=="boolean"?r.allowed:void 0,s=typeof r.limit_reached=="boolean"?r.limit_reached:void 0;for(let o of["primary_window","secondary_window"]){let a=Fe(r[o])?r[o]:void 0;if(!a)continue;let l=Dh(a.limit_window_seconds);e.push(Re({bucket_id:`codex-${Mh(l)}`,group_name:"codex",window_type:l,used_fraction:ze(a.used_percent,"percent"),resets_at:a.reset_at,raw_value:a.used_percent,raw_scale:"used_percent",...n===void 0?{}:{allowed:n},...s===void 0?{}:{limit_reached:s}}))}let i=Array.isArray(t.additional_rate_limits)?t.additional_rate_limits:[];for(let o of i){if(!Fe(o))continue;let a=Fe(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,u=c||l||"additional",d=typeof a.allowed=="boolean"?a.allowed:void 0,m=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let h of["primary_window","secondary_window"]){let _=Fe(a[h])?a[h]:void 0;if(!_)continue;let T=Dh(_.limit_window_seconds);e.push(Re({bucket_id:`${u}-${Mh(T)}`,group_name:l||u,window_type:T,used_fraction:ze(_.used_percent,"percent"),resets_at:_.reset_at,raw_value:_.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...d===void 0?{}:{allowed:d},...m===void 0?{}:{limit_reached:m}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function sA(t){let e=Fe(t.rate_limit)?t.rate_limit:{},r=typeof e.allowed=="boolean"?e.allowed:void 0,n=Fe(t.spend_control)?t.spend_control:void 0,s=Fe(t.credits)?t.credits:void 0;return ge("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...r===void 0?{}:{ordinary_usage_allowed:r},buckets:nA(t),...s?{credits:rA(s)}:{},...n?{spend_control:n}:{}})}async function Fh(t){let{timeoutSeconds:e,env:r,debug:n,onRawResponse:s}=t,i=tA(r);if(!i.token)return ge("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:"no access_token in ~/.codex/auth.json (or $CODEX_ACCESS_TOKEN)"});let o=new AbortController,a=setTimeout(()=>o.abort(),Math.ceil(e*1e3));try{let l={Authorization:`Bearer ${i.token}`,"User-Agent":eA,"Content-Type":"application/json",Accept:"application/json"};i.accountId&&(l["ChatGPT-Account-Id"]=i.accountId);let c=(r.CODEX_BASE_URL||Zx).replace(/\/$/,""),u=await fetch(`${c}/wham/usage`,{headers:l,signal:o.signal}),d=await u.text();Me({debug:n,onRawResponse:s},"codex_http",d,[i.token],u.status);let m=(_,T)=>Mr(ge("codex",_,T),d,[i.token]);if(u.status===401)return m("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(u.status===429){let _=u.headers.get("retry-after"),T=_===null?void 0:Number.parseInt(_,10);return m("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...T!==void 0&&Number.isFinite(T)&&T>=0?{retry_after_seconds:T}:{}})}if(!u.ok)return m("provider_unavailable",{source:"codex_http",reason:`http_${u.status}`,detail:"codex usage endpoint returned an unexpected status"});let h;try{h=JSON.parse(d)}catch(_){return ge("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:Dr(String(_),[i.token])})}return Fe(h)?sA(h):ge("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(l){let c=l instanceof Error?`${l.name}: ${l.message}`:String(l);return ge("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:Dr(c,[i.token])})}finally{clearTimeout(a)}}import{createHash as iA,randomUUID as oA}from"node:crypto";import{readFileSync as Hh,openSync as aA,fsyncSync as lA,closeSync as cA,mkdirSync as Ph,writeFileSync as Bh,renameSync as dA,rmSync as uA,rmdirSync as mA,statSync as jl,utimesSync as fA}from"node:fs";import{homedir as pA}from"node:os";import{basename as hA,dirname as gA,join as xi}from"node:path";import{setTimeout as Wh}from"node:timers/promises";var $h="https://api.kimi.com/coding/v1",Hl="https://auth.kimi.com",_A="17e5f671-d194-4dfb-9706-5516cb48c098",Uh=t=>t.trim().replace(/\/+$/,"");function yA(t){let e;try{e=Hh(t,"utf8")}catch(s){if(s.code==="ENOENT")return{};throw new Error("config_unreadable")}let r={},n="other";for(let s of e.split(/\r?\n/)){let i=/^\s*\[providers\.(?:"managed:kimi-code"|'managed:kimi-code')(\.oauth)?\]\s*(?:#.*)?$/.exec(s);if(i){n=i[1]?"oauth.":"";continue}if(/^\s*\[/.test(s)){if(s.includes("managed:kimi-code"))throw new Error("config_format_unsupported");n="other";continue}if(n==="other")continue;if(/^\s*oauth\s*=/.test(s))throw new Error("config_format_unsupported");let o=/^\s*(base_url|oauth_host|storage|key)\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(s);if(!o&&/^\s*(base_url|oauth_host|storage|key)\s*=/.test(s))throw new Error("config_malformed");if(o)try{r[n+o[1]]=o[2].startsWith('"')?JSON.parse(o[2]):o[2].slice(1,-1)}catch{throw new Error("config_malformed")}}return r}function Ai(t){let e;try{e=JSON.parse(Hh(t,"utf8"))}catch(r){throw new Error(r.code==="ENOENT"?"credentials_missing":"credentials_malformed")}if(e&&typeof e=="object"&&e.access_token===""&&e.refresh_token==="")throw new Error("credentials_revoked");if(!e||typeof e!="object"||Array.isArray(e)||typeof e.access_token!="string"||!e.access_token.trim())throw new Error("credentials_malformed");return e}function Xh(t){let e=t.KIMI_CODE_HOME??xi(t.HOME??pA(),".kimi-code"),r=yA(t.KIMI_CODE_CONFIG_PATH??xi(e,"config.toml")),n=t.KIMI_CODE_BASE_URL!==void 0||t.KIMI_CODE_OAUTH_HOST!==void 0||t.KIMI_OAUTH_HOST!==void 0,s=Uh(t.KIMI_CODE_BASE_URL??r.base_url??$h),i=Uh(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(n?Hl:r["oauth.oauth_host"]??Hl)),o=s===$h&&i===Hl?"kimi-code":`kimi-code-env-${iA("sha256").update(JSON.stringify({oauthHost:i,baseUrl:s})).digest("hex").slice(0,16)}`;if(!t.KIMI_CREDENTIALS_PATH&&!n&&r["oauth.key"]===`oauth/${o}`&&r["oauth.storage"]&&r["oauth.storage"]!=="file")throw new Error("credential_storage_unsupported");let a=t.KIMI_CREDENTIALS_PATH??xi(e,"credentials",`${o}.json`),l=Ai(a),c=a,u=hA(a,".json");return{home:e,path:c,lockTarget:xi(e,"oauth",u),baseUrl:s,oauthHost:i,token:l}}function ki(t){if(typeof t.expires_at!="number")return!1;let e=typeof t.expires_in=="number"?t.expires_in:0;return t.expires_at-Date.now()/1e3<Math.max(300,e*.5)}function jh(t,e){return t.access_token===e.access_token&&t.refresh_token===e.refresh_token&&t.expires_at===e.expires_at&&t.expires_in===e.expires_in}async function EA(t,e){Ph(gA(t),{recursive:!0}),Bh(t,"",{flag:"a",mode:384});let r=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{Ph(r);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-jl(r).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await Wh(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let n=jl(r),s=()=>{let o;try{o=jl(r)}catch{throw new Error("refresh_lock_lost")}if(o.ino!==n.ino||o.dev!==n.dev)throw new Error("refresh_lock_lost")},i=setInterval(()=>{try{s();let o=new Date;fA(r,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),mA(r)}catch{}}}}async function qh(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let r=await EA(t.lockTarget,e);try{let n=Ai(t.path);if(!jh(n,t.token)&&!ki(n))return n;if(typeof n.refresh_token!="string"||!n.refresh_token)throw new Error("no_refresh_token");let s;for(let d=0;d<3;d++){try{if(s=await fetch(`${t.oauthHost}/api/oauth/token`,{method:"POST",signal:e,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":"lmctl"},body:new URLSearchParams({client_id:_A,grant_type:"refresh_token",refresh_token:n.refresh_token})}),![429,500,502,503,504].includes(s.status)||d===2)break;await s.body?.cancel()}catch{if(e.aborted||d===2)throw new Error("refresh_request_failed")}await Wh(1e3*2**d,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let d=Ai(t.path);if(d.refresh_token!==n.refresh_token)return d}catch{}throw new Error(`refresh_http_${s.status}`)}let i=await s.json(),o=Number(i?.expires_in);if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)||!Number.isFinite(o)||o<=0)throw new Error("invalid_refresh_response");let a=Math.floor(Date.now()/1e3)+o;if(!Number.isSafeInteger(a))throw new Error("invalid_refresh_response");r.assertOwned();let l=Ai(t.path);if(!jh(l,n)){if(!ki(l))return l;throw new Error("credentials_changed")}let c={...l,access_token:i.access_token,refresh_token:i.refresh_token,expires_at:a,expires_in:o,...typeof i.scope=="string"?{scope:i.scope}:{},...typeof i.token_type=="string"?{token_type:i.token_type}:{}},u=`${t.path}.${oA()}.tmp`;try{let d=aA(u,"wx",384);try{Bh(d,JSON.stringify(c,null,2)+`
|
|
2172
|
+
`),lA(d)}finally{cA(d)}r.assertOwned(),dA(u,t.path)}finally{uA(u,{force:!0})}return c}finally{r.release()}}function Gh(t){let e=o=>{if(typeof o!="number"&&typeof o!="string"||typeof o=="string"&&o.trim()==="")return;let a=Number(o);return Number.isFinite(a)&&a>=0?a:void 0},r=e(t.limit),n=e(t.used),s=e(t.remaining);if(r===void 0||r<=0||n===void 0&&(s===void 0||s>r))return;let i=n??r-s;return{used:i,limit:r,remaining:Math.max(0,r-i)}}async function Jh({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s;try{s=Xh(e)}catch(T){let p=T instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(T.message)?T.message:"credentials_unreadable";return Le("kimi",p==="credentials_revoked"?"auth_expired":"provider_unavailable",p,p==="credentials_revoked"?"Kimi login was revoked; run kimi login":p.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let T=!1,p=async()=>{i=await qh({...s,token:i},o.signal),T=!0};ki(i)&&await p();let f=()=>fetch(`${s.baseUrl}/usages`,{headers:{Authorization:`Bearer ${i.access_token}`,Accept:"application/json"},signal:o.signal});l=await f(),c=await l.text(),Me({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!T&&i.refresh_token&&(await p(),l=await f(),c=await l.text(),Me({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(T){let p=T instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(T.message)?T.message:"request_failed",f=p==="credentials_revoked"||p==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(p),y=p==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":f?`Kimi credential renewal failed (${p}); run kimi login`:`Kimi quota request failed (${p})`;return Le("kimi",f?"auth_expired":"provider_unavailable",p,y,"kimi_http")}finally{clearTimeout(a)}let u=(T,p,f)=>Mr(Le("kimi",T,p,p,"kimi_http",[],f),c,[i.access_token]);if(l.status===401)return u("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return u("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let T=yh(l.headers);return u("reader_throttled","HTTP 429 from Kimi usage endpoint",T)}if(l.status!==200)return u("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let d;try{d=JSON.parse(c)}catch{return Le("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!d||typeof d!="object")return Le("kimi","provider_unavailable","malformed_response","response was not an object");let m=[],h=new Set;function _(T){let p=String(T.bucket_id),f=p,y=2;for(;h.has(p);)p=`${f}-${y}`,y++;h.add(p),T.bucket_id=p,m.push(Re(T))}if(Array.isArray(d.limits))for(let T of d.limits){if(!T||typeof T!="object")continue;let p=T.window,f=T.detail;if(!p||typeof p!="object"||!f||typeof f!="object")continue;let y=0;if(p.timeUnit==="TIME_UNIT_MINUTE")y=Number(p.duration);else if(p.timeUnit==="TIME_UNIT_HOUR")y=Number(p.duration)*60;else if(p.timeUnit==="TIME_UNIT_DAY")y=Number(p.duration)*1440;else if(p.timeUnit==="TIME_UNIT_WEEK")y=Number(p.duration)*10080;else if(p.timeUnit==="TIME_UNIT_MONTH")y=Number(p.duration)*43200;else continue;let g=gh(y),E="window";g==="five_hour"&&(E="5h"),g==="weekly"&&(E="weekly"),g==="monthly"&&(E="monthly");let v=Gh(f);if(!v)continue;let{used:w,limit:b,remaining:S}=v;_({bucket_id:`kimi-${E}`,window_type:g,used_fraction:Se(w/b),remaining_fraction:Se(S/b),resets_at_iso:f.resetTime,raw_value:w,raw_scale:"count"})}if(d.usage&&typeof d.usage=="object"){let T=Gh(d.usage);T&&_({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:Se(T.used/T.limit),remaining_fraction:Se(T.remaining/T.limit),resets_at_iso:d.usage.resetTime,raw_value:T.used,raw_scale:"count"})}if(d.usages&&typeof d.usages=="object"){let T=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:p,id:f,type:y}of T){let g=d.usages[p];if(!g||typeof g!="object"||g.used_ratio==null||g.used_ratio===""||typeof g.used_ratio=="boolean")continue;let E=Number(g.used_ratio);!Number.isFinite(E)||E<0||h.has(f)||(h.add(f),m.push(Re({bucket_id:f,window_type:y,used_fraction:Se(E),resets_at_iso:typeof g.reset_time=="string"&&g.reset_time?g.reset_time:null,raw_value:E,raw_scale:"ratio"})))}}return ge("kimi","ok",{source:"kimi_http",buckets:m})}var Kh=["all","codex","agy","claude","kimi"],TA=15;async function Vh(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let a of e)if(!Kh.includes(a))return{status:"error",error:`unknown provider: ${a} (valid targets: ${Kh.join(", ")})`,readings:[]};let r=t.timeoutSeconds??TA;if(!Number.isFinite(r)||r<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=t.env??process.env,s=new Set(e.includes("all")?["codex","agy","claude","kimi"]:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${r}s per provider) ...`);let o=Object.entries({codex:Fh,agy:wh,claude:Oh,kimi:Jh}).filter(([a])=>s.has(a)).map(async([,a])=>{let l=[],c=await a({timeoutSeconds:r,env:n,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:u=>l.push(u)}:{}});return t.includeRaw?{...c,raw_responses:l}:c});try{return{status:"ok",readings:(await Promise.all(o)).filter(Boolean)}}catch(a){return{status:"error",error:String(a),readings:[]}}}wo();xn();yr();fr();Qr();Ft();pi();rs();ns();import{execFile as wA}from"node:child_process";import{mkdtempSync as SA,realpathSync as Xl,rmSync as vA,statSync as ng}from"node:fs";import{tmpdir as sg}from"node:os";import{isAbsolute as ql,join as Yh,relative as bA}from"node:path";import{promisify as IA}from"node:util";var xA=IA(wA),AA=[{name:"lmbee_queue_list",category:"Queue Management",signature:"lmbee_queue_list(snapshot_db, team = null, options = null)",description:"Lists queue rows from a temporary lmbee database copy, read directly (no lmbee executable needed).",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"},{name:"options",type:"map",description:`Optional { scope, limit, after_id }: scope "recent" (default) is the newest 30 rows; scope "unfinished" is every genuinely open row (lmauto's listUnfinishedQueue predicate); scope "all" is every row. limit (1-200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:"{ queue: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; each row carries hasAnswer (current, non-superseded answer)"},example:'page = lmbee_queue_list("/tmp/lmbee-copy/state.db", null, {"scope":"unfinished","limit":200});'},{name:"lmbee_queue_get",category:"Queue Management",signature:"lmbee_queue_get(snapshot_db, id)",description:"Gets one queue row from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer queue ID"}],returns:{type:"map",description:"{ queue: row, hasAnswer: boolean } or a queue_not_found error object"},example:'item = lmbee_queue_get("/tmp/lmbee-copy/state.db", 7);'},{name:"lmbee_queue_stats",category:"Queue Management",signature:"lmbee_queue_stats(snapshot_db, team = null)",description:"Reads per-recipient queue counts from a temporary lmbee database copy, without a row window.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"}],returns:{type:"map",description:"{ stats: [...] } most-stale-first; team_progress-sourced fields (escalationAttemptCount, lastEscalationAttemptTs, quota*) default to 0/null when the snapshot predates that table"},example:'counts = lmbee_queue_stats("/tmp/lmbee-copy/state.db", "worker");'},{name:"lmbee_tasks",category:"Queue Management",signature:"lmbee_tasks(snapshot_db, options = null)",description:"Lists task-ledger rows (lmauto entities: epics, tasks, subtasks) from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:`Optional { scope, status, owner, team, limit, after_id }: scope "recent" (default) is the newest 30 rows and is NOT pageable (limit/after_id require unfinished or all; use a paged scope to traverse completely); scope "unfinished" excludes rows whose normalized status (trim, lowercase, separators to hyphens -- lmauto's normalizeStatus) is done/closed/cancelled, the audit terminal set -- a deliberate bridge choice, since lmauto itself uses done/closed for epic completeness and done-only for dependency satisfaction; scope "all" is every row. status exact-matches the stored value with the ARGUMENT trimmed (lmauto listEntities). owner exact-matches owner_alias; alias-only is a cross-team match -- add team (exact match on the stored canonical team path) to pin one team. limit (1-200, default 200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:`{ tasks: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; rows carry id, kind, project, parent_id, title, status, owner_team_path, owner_alias, created_at, updated_at -- updated_at is the entity's own update time, NOT "last activity" (delivery bookkeeping deliberately does not touch it)`},example:'tasks = lmbee_tasks("/tmp/lmbee-copy/state.db", {"scope":"unfinished","owner":"worker","limit":50});'},{name:"lmbee_task_get",category:"Queue Management",signature:"lmbee_task_get(snapshot_db, id)",description:'Gets one task-ledger row with its direct children, so "does this parent still have open children" is a single field.',parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer entity ID"}],returns:{type:"map",description:"{ task, children, open_children } or a task_not_found error object; children is id-ascending and DIRECT only, and open_children counts those direct children whose normalized status is not done/closed/cancelled -- it claims nothing about grandchildren"},example:'t = lmbee_task_get("/tmp/lmbee-copy/state.db", 12);'},{name:"lmbee_cron_list",category:"Queue Management",signature:"lmbee_cron_list(snapshot_db, options = null)",description:"Lists cron jobs from a temporary lmbee database copy. Jobs are operator-created and few, so there is deliberately no paging.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:"Optional { enabled }: true/false to filter; omitted lists all"}],returns:{type:"map",description:'{ jobs: [...] } by ascending id, with enabled as a real boolean. Two traps: legacy command/enqueue jobs NEVER write cron_runs -- for them "did it run" is last_fired_ts/last_fire_status/last_fire_error on this row; and running_since_ts non-null means a legacy execution is currently claimed'},example:'jobs = lmbee_cron_list("/tmp/lmbee-copy/state.db", {"enabled":true});'},{name:"lmbee_cron_runs",category:"Queue Management",signature:"lmbee_cron_runs(snapshot_db, options = null)",description:"Lists cron run-ledger rows (run-based job kinds: script/session/miniplayer) from a temporary lmbee database copy, newest-first.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:"Optional { job_id, status, limit, after_id }: status is one of pending/running/succeeded/failed/escalated; limit (1-200) defaults to 50 -- the ledger only grows, so page with after_id rather than reading unbounded"}],returns:{type:"map",description:"{ runs: [...], meta: { next_cursor } }. Outcome (status) and execution liveness (execution_state) are SEPARATE: succeeded can coexist with an active execution fence. An empty result does NOT mean a job never ran -- legacy command/enqueue jobs write nothing here; check the job row via lmbee_cron_list. run_token_hash is never returned (lmbee's own public projection)"},example:'runs = lmbee_cron_runs("/tmp/lmbee-copy/state.db", {"job_id":3,"limit":50});'},{name:"lmbee_snapshot",category:"Queue Management",signature:"lmbee_snapshot(source_db)",description:"Creates a WAL-aware temporary database backup, removed when the script ends.",parameters:[{name:"source_db",type:"string",description:"Absolute path to an existing lmbee database"}],returns:{type:"string",description:"Temporary snapshot path for lmbee queue functions"},example:'snapshot = lmbee_snapshot(env("HOME") + "/.lmbee/state.db");'}];function ig(t){if(typeof t!="string"||!t||!ql(t))throw new Error("lmbee: snapshot_db must be an absolute path to a temporary database copy");let e;try{e=Xl(t);let n=ng(e);if(!n.isFile()||n.nlink!==1)throw new Error("not a standalone file")}catch{throw new Error("lmbee: snapshot_db must be an existing temporary database copy")}let r=bA(Xl(sg()),e);if(!r||r===".."||r.startsWith("../")||ql(r))throw new Error("lmbee: snapshot_db must be a temporary database copy inside the system temp directory");return e}function zh(t){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error("lmbee: team must be a nonempty string");return t}}function kA(t){if(t==null)return{scope:"recent",limit:200};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.scope??"recent";if(r!=="recent"&&r!=="unfinished"&&r!=="all")throw new Error("lmbee: scope must be recent, unfinished, or all");let n=e.limit??200;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let s=e.after_id;if(s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0))throw new Error("lmbee: after_id must be a positive integer");if(r==="recent"&&(e.limit!==void 0||s!==void 0))throw new Error("lmbee: limit and after_id require unfinished or all scope");return{scope:r,limit:n,afterId:s}}var NA=["id","from_id","to_id","status","created_ts","expects_response","in_reply_to","retracted_ts","escalation_claimed_ts"],RA=["prompt_queue_id","superseded_at"],LA=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],og=["id","kind","project","parent_id","title","status","owner_team_path","owner_alias","created_at","updated_at"],Ni=og.join(", "),CA="replace(replace(lower(trim(status, char(9, 10, 11, 12, 13, 32, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279))), ' ', '-'), '_', '-')",ag=`${CA} NOT IN ('done', 'closed', 'cancelled')`,lg=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","session_teamfile","session_alias","session_seeded_at","session_generation","enabled","last_checked_ts","last_fired_ts","last_fire_status","last_fire_error","running_systemd_unit","timezone","running_since_ts","created_at","updated_at","revision"],Qh=lg.join(", "),cg=["id","job_id","status","execution_state","trigger_kind","config_snapshot","execution_identity","pid","summary","artifacts","escalation_reason","escalation_action","escalation_owner","escalation_resolved_at","escalation_resolution","escalation_resolution_actor","escalation_resolution_note","execution_gone_at","execution_uncertain_reason","execution_confirmation_note","reported_at","created_at","started_at","finished_at","updated_at"],OA=cg.join(", "),DA=new Set(["pending","running","succeeded","failed","escalated"]),MA=`q.status != 'merged'
|
|
2173
2173
|
AND q.retracted_ts IS NULL
|
|
2174
2174
|
AND NOT EXISTS (SELECT 1 FROM answers r WHERE r.prompt_queue_id = q.id)
|
|
2175
|
-
AND NOT ((q.expects_response = 0 OR q.in_reply_to IS NOT NULL) AND q.status IN ('sent', 'retrieved'))`,
|
|
2176
|
-
`)}}function
|
|
2177
|
-
`),null}}function
|
|
2175
|
+
AND NOT ((q.expects_response = 0 OR q.in_reply_to IS NOT NULL) AND q.status IN ('sent', 'retrieved'))`,Zh="EXISTS (SELECT 1 FROM answers a WHERE a.prompt_queue_id = q.id AND a.superseded_at IS NULL)";function dg(t,e){let r=t.prepare(`SELECT name FROM pragma_table_info('${e}')`).all();return new Set(r.map(n=>n.name))}function ug(t,e,r){let n=dg(t,e);if(n.size===0)throw new Error(`lmbee: snapshot schema incompatible: missing table '${e}' (expected the lmbee schema; its absence is not an empty result)`);let s=r.filter(i=>!n.has(i));if(s.length>0)throw new Error(`lmbee: snapshot schema incompatible: table '${e}' is missing column(s): ${s.join(", ")}`)}var Bl=[["queue",NA],["answers",RA]],eg=[["entities",og]],FA=[["cron_jobs",lg]],PA=[["cron_runs",cg]];function $A(t,e){let r=ig(t),n=new ar(r,{readonly:!0,fileMustExist:!0});try{for(let[s,i]of e)ug(n,s,[...i])}catch(s){throw n.close(),s}return n}function tg(t){return{...t,hasAnswer:t.hasAnswer===1}}function UA(t,e,r){let n=[],s=[];e!==void 0&&(n.push("q.to_id = ?"),s.push(e)),r.scope==="unfinished"&&n.push(MA),r.afterId!==void 0&&(n.push("q.id < ?"),s.push(r.afterId));let i=n.length>0?`WHERE ${n.join(" AND ")}`:"";if(r.scope==="recent")return{queue:t.prepare(`SELECT q.*, ${Zh} AS hasAnswer FROM queue q ${i} ORDER BY q.id DESC LIMIT 30`).all(...s).map(tg)};let o=t.prepare(`SELECT q.*, ${Zh} AS hasAnswer FROM queue q ${i} ORDER BY q.id DESC LIMIT ?`).all(...s,r.limit+1),a=o.length>r.limit;return a&&(o.length=r.limit),{queue:o.map(tg),meta:{next_cursor:a?o[o.length-1].id:null}}}function jA(t,e){let r=t.prepare("SELECT * FROM queue WHERE id = ?").get(e);if(r==null)return{error:{code:"queue_not_found",message:`no queue entry ${e}`}};let n=t.prepare("SELECT 1 AS x FROM answers WHERE prompt_queue_id = ? AND superseded_at IS NULL").get(e);return{queue:r,hasAnswer:n!=null}}function rg(t,e){let r=t-Date.parse(e);return Number.isFinite(r)?r:null}function HA(t,e){let r=Date.now(),n=(m,h)=>e?t.prepare(`SELECT to_id, ${h} AS ts FROM queue WHERE status = ? AND to_id = ?`).all(m,e):t.prepare(`SELECT to_id, ${h} AS ts FROM queue WHERE status = ?`).all(m),s=m=>{let h=new Map;for(let _ of m){let T=h.get(_.to_id);T?T.push(_.ts):h.set(_.to_id,[_.ts])}return h},i=m=>{let h=m.reduce((_,T)=>_===null||T!==null&&T<_?T:_,null);return h===null?0:rg(r,h)},o=s(n("pending","created_ts")),a=s(n("escalating","escalation_claimed_ts")),l=new Map;if(dg(t,"team_progress").size>0){ug(t,"team_progress",LA);let m=e?t.prepare("SELECT * FROM team_progress WHERE team = ?").all(e):t.prepare("SELECT * FROM team_progress").all();for(let h of m)l.set(h.team,h)}let c=m=>({escalationAttemptCount:m?.escalation_attempt_count??0,lastEscalationAttemptTs:m?.last_escalation_attempt_ts??null,quotaExhaustedLastSeenAgeMs:m?.quota_exhausted_last_seen_ts?rg(r,m.quota_exhausted_last_seen_ts):null,quotaExhaustedMessage:m?.quota_exhausted_message??null}),u=new Set([...o.keys(),...a.keys()]),d=[...u].map(m=>{let h=o.get(m)??[],_=a.get(m)??[];return{toId:m,pendingCount:h.length,oldestPendingAgeMs:h.length>0?i(h):null,escalatingCount:_.length,oldestEscalatingAgeMs:_.length>0?i(_):null,...c(l.get(m))}});for(let m of l.values())u.has(m.team)||m.escalation_attempt_count<=0||d.push({toId:m.team,pendingCount:0,oldestPendingAgeMs:null,escalatingCount:0,oldestEscalatingAgeMs:null,...c(m)});return d.sort((m,h)=>(h.oldestPendingAgeMs??-1)-(m.oldestPendingAgeMs??-1)),{stats:d}}function Wl(t,e){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error(`lmbee: ${e} must be a nonempty string`);return t}}function BA(t){if(t==null)return{scope:"recent",limit:200};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.scope??"recent";if(r!=="recent"&&r!=="unfinished"&&r!=="all")throw new Error("lmbee: scope must be recent, unfinished, or all");let n=e.limit??200;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let s=e.after_id;if(s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0))throw new Error("lmbee: after_id must be a positive integer");if(r==="recent"&&(e.limit!==void 0||s!==void 0))throw new Error("lmbee: limit and after_id require unfinished or all scope");let i=Wl(e.status,"status")?.trim(),o=Wl(e.owner,"owner"),a=Wl(e.team,"team");return{scope:r,limit:n,afterId:s,status:i,owner:o,team:a}}function WA(t,e){let r=[],n=[];e.scope==="unfinished"&&r.push(ag),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.owner!==void 0&&(r.push("owner_alias = ?"),n.push(e.owner)),e.team!==void 0&&(r.push("owner_team_path = ?"),n.push(e.team)),e.afterId!==void 0&&(r.push("id < ?"),n.push(e.afterId));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"";if(e.scope==="recent")return{tasks:t.prepare(`SELECT ${Ni} FROM entities ${s} ORDER BY id DESC LIMIT 30`).all(...n)};let i=t.prepare(`SELECT ${Ni} FROM entities ${s} ORDER BY id DESC LIMIT ?`).all(...n,e.limit+1),o=i.length>e.limit;return o&&(i.length=e.limit),{tasks:i,meta:{next_cursor:o?i[i.length-1].id:null}}}function XA(t,e){let r=t.prepare(`SELECT ${Ni} FROM entities WHERE id = ?`).get(e);if(r==null)return{error:{code:"task_not_found",message:`no task ${e}`}};let n=t.prepare(`SELECT ${Ni} FROM entities WHERE parent_id = ? ORDER BY id ASC`).all(e),s=t.prepare(`SELECT COUNT(*) AS n FROM entities WHERE parent_id = ? AND ${ag}`).get(e);return{task:r,children:n,open_children:s.n}}function qA(t){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t.enabled;if(e!==void 0&&typeof e!="boolean")throw new Error("lmbee: enabled must be a boolean");return{enabled:e}}function GA(t,e){return{jobs:(e.enabled===void 0?t.prepare(`SELECT ${Qh} FROM cron_jobs ORDER BY id ASC`).all():t.prepare(`SELECT ${Qh} FROM cron_jobs WHERE enabled = ? ORDER BY id ASC`).all(e.enabled?1:0)).map(n=>({...n,enabled:n.enabled===1}))}}function JA(t){if(t==null)return{limit:50};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.job_id;if(r!==void 0&&(typeof r!="number"||!Number.isSafeInteger(r)||r<=0))throw new Error("lmbee: job_id must be a positive integer");let n=e.status;if(n!==void 0&&(typeof n!="string"||!DA.has(n)))throw new Error("lmbee: status must be pending, running, succeeded, failed, or escalated");let s=e.limit??50;if(typeof s!="number"||!Number.isSafeInteger(s)||s<1||s>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let i=e.after_id;if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<=0))throw new Error("lmbee: after_id must be a positive integer");return{jobId:r,status:n,limit:s,afterId:i}}function KA(t,e){let r=[],n=[];e.jobId!==void 0&&(r.push("job_id = ?"),n.push(e.jobId)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.afterId!==void 0&&(r.push("id < ?"),n.push(e.afterId));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"",i=t.prepare(`SELECT ${OA} FROM cron_runs ${s} ORDER BY id DESC LIMIT ?`).all(...n,e.limit+1),o=i.length>e.limit;return o&&(i.length=e.limit),{runs:i,meta:{next_cursor:o?i[i.length-1].id:null}}}function mg(t,e=()=>{}){let r=(s,i,o)=>{let a=$A(s,i);try{return o(a)}finally{a.close()}},n=async s=>{if(typeof s!="string"||!ql(s))throw new Error("lmbee: source_db must be an absolute path");let i;try{if(i=Xl(s),!ng(i).isFile())throw new Error("not a file")}catch{throw new Error("lmbee: source_db must be an existing database file")}let o=SA(Yh(sg(),"lmctl-lmbee-snapshot-")),a=Yh(o,"state.db");try{return await xA("sqlite3",["-readonly",i,`.backup "${a.replaceAll('"','""')}"`],{env:t,timeout:12e4,maxBuffer:1048576}),ig(a),e(o),a}catch(l){vA(o,{recursive:!0,force:!0});let c=l;throw c.code==="ENOENT"?new Error("sqlite3 executable not found on PATH"):new Error(`lmbee snapshot failed: ${c.stderr?.trim()||c.message}`)}};return{name:"lmbee",description:"Read-only queue, task-ledger, and cron queries against temporary lmbee database copies",docs:AA,register(s){s.registerFunction("lmbee_queue_list",(i,o,a)=>r(i,Bl,l=>UA(l,zh(o),kA(a))),{min:1,max:3}),s.registerFunction("lmbee_queue_get",(i,o)=>{if(typeof o!="number"||!Number.isSafeInteger(o)||o<=0)throw new Error("lmbee: id must be a positive integer");return r(i,Bl,a=>jA(a,o))},2),s.registerFunction("lmbee_queue_stats",(i,o)=>r(i,Bl,a=>HA(a,zh(o))),{min:1,max:2}),s.registerFunction("lmbee_tasks",(i,o)=>r(i,eg,a=>WA(a,BA(o))),{min:1,max:2}),s.registerFunction("lmbee_task_get",(i,o)=>{if(typeof o!="number"||!Number.isSafeInteger(o)||o<=0)throw new Error("lmbee: id must be a positive integer");return r(i,eg,a=>XA(a,o))},2),s.registerFunction("lmbee_cron_list",(i,o)=>r(i,FA,a=>GA(a,qA(o))),{min:1,max:2}),s.registerFunction("lmbee_cron_runs",(i,o)=>r(i,PA,a=>KA(a,JA(o))),{min:1,max:2}),s.registerFunction("lmbee_snapshot",n,1)}}}var Fr=class{batchHandles=new Map;temporaryDirectories=new Set;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}registerTemporaryDirectory(e){this.temporaryDirectories.add(e)}removeTemporaryDirectories(){for(let e of this.temporaryDirectories)ck(e,{recursive:!0,force:!0}),this.temporaryDirectories.delete(e)}async forceCloseAll(e){try{for(let r of this.getOpenBatches())await bg(r,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}finally{this.removeTemporaryDirectories()}}};async function uk(t){let e=t.provider.trim().toLowerCase();return ci.includes(e)||Eu().tools[e]?.agent!==void 0||!li.includes(e)?!1:ui().includes(e)}async function Jl(t,e){try{await j(t,r=>{r.releaseAgentInflight(e.row,e.leaseId)})}catch(r){t.stderr.write(`warning: failed to release batch bundle lease: ${r instanceof Error?r.message:String(r)}
|
|
2176
|
+
`)}}function mk(t,e){let r=gi(t,e);if(r.ok)return _i(r.identity);if(r.reason==="unset")return null;throw new Error(hi("batch"))}async function fk(t,e){try{let{member:r}=e;return await j(t,n=>n.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:r.teamfile,from_identity:`${r.teamfile}:batch`,target_teamfile:r.teamfile,target_alias:r.alias,root_teamfile:r.teamfile,cwd:r.sessiondir,command:`lmctl batch ${r.teamfile} ${r.alias} ${e.batchfile}`,holder_pid:process.pid,launch_source:"exec",parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({batchfile:e.batchfile,prompt_count:e.promptCount,provider:r.provider,sessionid:r.sessionid,...r.model!==void 0?{model:r.model}:{}})}).id)}catch(r){return t.stderr.write(`warning: failed to start batch root invocation: ${r instanceof Error?r.message:String(r)}
|
|
2177
|
+
`),null}}function pk(t,e,r,n){try{if(t.dal!==void 0){t.dal.finishTrackedInvocation(e,r);return}let s=$t({path:st(n?.LMCTL_DB)});try{s.finishTrackedInvocation(e,r)}finally{s.close()}}catch{}}async function bg(t,e,r,n){if(!t.closed&&(t.closed=!0,t.kind!=="agent")){if(t.bundleSession)try{await t.bundleSession.close()}catch{}if(t.heartbeatTimer&&t.heartbeatTimer.stop(),t.heldLease&&await Jl(e,t.heldLease),t.rootId!==null){let s=r==="done"?{status:"done",exit_code:0,result_summary:`batch completed ${t.promptCount}/${t.promptCount} prompts`}:{status:t.rootFinish.status??(r==="cancelled"?"cancelled":"error"),exit_code:1,error:n??t.rootFinish.error,result_summary:t.rootFinish.result_summary};try{await j(e,i=>{i.finishTrackedInvocation(t.rootId,s)})}catch(i){e.stderr.write(`warning: failed to finish batch root invocation: ${i instanceof Error?i.message:String(i)}
|
|
2178
2178
|
`)}}r==="done"&&e.stderr.write(`batch ${_t()}: completed ${t.promptCount}/${t.promptCount} prompts
|
|
2179
|
-
`)}}var ql=[{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_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_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_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:"{ status, code } after the TUI exits"},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"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 HA(t){for(let e of ql)t.registerFunctionDoc(e)}function pg(t={}){let e=new Ze;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+`
|
|
2179
|
+
`)}}var Kl=[{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_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_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_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:"{ status, code } after the TUI exits"},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"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 hk(t){for(let e of Kl)t.registerFunctionDoc(e)}function Ig(t={}){let e=new Ze;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+`
|
|
2180
2180
|
`),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+`
|
|
2181
|
-
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=
|
|
2182
|
-
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(t.env?.LMCTL_NON_INTERACTIVE==="1"||
|
|
2181
|
+
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=Hr(s,i);return n.stdout.write(o+`
|
|
2182
|
+
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(t.env?.LMCTL_NON_INTERACTIVE==="1"||hr(n))throw new Error("prompt_human is disabled in non-interactive mode");if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return Wr(s,i,o)}return Br(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 xg(t,e,r,n=process.env){t.registerFunction("lm_exit",(p=0)=>{let f=Math.floor(Number(p)),y=Number.isFinite(f)&&f>=0&&f<=255?f:1;throw new ve(y)},{min:0,max:1},"Exits the LMScript execution with an exit code"),t.registerFunction("lm_log",(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return e.stderr.write(f+(f.endsWith(`
|
|
2183
2183
|
`)?"":`
|
|
2184
2184
|
`)),f},void 0,"Writes formatted log message to stderr"),t.registerFunction("lm_error",(...p)=>{let f=p.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return e.stderr.write(`error: ${f}
|
|
2185
|
-
`),r.recordError(f),f},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(p,f=!1)=>{try{let y=
|
|
2186
|
-
`);return!!f?[y.trim()].filter(E=>E.length>0):y.split(/\n\s*\n/u).map(E=>E.trim()).filter(Boolean)}catch(y){throw B(e,`batch: ${y instanceof Error?y.message:String(y)}`),new ve(1)}};t.registerFunction("lm_read_prompts",(p,f=!1)=>s(p,f),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",p=>s(p,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",p=>{try{return $e(String(p)).members.map(y=>({alias:y.alias,provider:y.provider,model:y.model,sessionid:y.session,sessiondir:y.sessiondir}))}catch(f){throw new Error(`Failed to read teamfile '${p}': ${f?.message||String(f)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(p,f)=>{try{let y=tt(String(p),String(f),e.dal);return{alias:y.alias,provider:y.provider,model:y.model,sessionid:y.sessionid,sessiondir:y.sessiondir,isLead:y.isLead,teamfile:y.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(p,f,y,g={})=>{if(typeof p!="string"){if(!p||Array.isArray(p)||typeof p!="object"||typeof p.provider!="string"||!p.provider.trim())throw new Error("lm_batch_open: member map requires provider");let C=f??{};if(typeof C!="object"||Array.isArray(C)||y!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let q={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...p},sourceMember:p,options:{...C},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(q),q}if(typeof f!="string"||typeof y!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let E;try{E=tt(String(p),String(f),e.dal)}catch(C){return B(e,`batch: ${C?.message||String(C)}`),null}let v=Number(g?.promptCount??1),b=!!!g?.legacy&&v>1&&await
|
|
2187
|
-
`);try{if(b){let
|
|
2188
|
-
`);try{let
|
|
2189
|
-
`);let b=
|
|
2190
|
-
`);try{let S=await
|
|
2185
|
+
`),r.recordError(f),f},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(p,f=!1)=>{try{let y=lk(String(p),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2186
|
+
`);return!!f?[y.trim()].filter(E=>E.length>0):y.split(/\n\s*\n/u).map(E=>E.trim()).filter(Boolean)}catch(y){throw B(e,`batch: ${y instanceof Error?y.message:String(y)}`),new ve(1)}};t.registerFunction("lm_read_prompts",(p,f=!1)=>s(p,f),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",p=>s(p,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",p=>{try{return $e(String(p)).members.map(y=>({alias:y.alias,provider:y.provider,model:y.model,sessionid:y.session,sessiondir:y.sessiondir}))}catch(f){throw new Error(`Failed to read teamfile '${p}': ${f?.message||String(f)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(p,f)=>{try{let y=tt(String(p),String(f),e.dal);return{alias:y.alias,provider:y.provider,model:y.model,sessionid:y.sessionid,sessiondir:y.sessiondir,isLead:y.isLead,teamfile:y.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(p,f,y,g={})=>{if(typeof p!="string"){if(!p||Array.isArray(p)||typeof p!="object"||typeof p.provider!="string"||!p.provider.trim())throw new Error("lm_batch_open: member map requires provider");let C=f??{};if(typeof C!="object"||Array.isArray(C)||y!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let q={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...p},sourceMember:p,options:{...C},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(q),q}if(typeof f!="string"||typeof y!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let E;try{E=tt(String(p),String(f),e.dal)}catch(C){return B(e,`batch: ${C?.message||String(C)}`),null}let v=Number(g?.promptCount??1),b=!!!g?.legacy&&v>1&&await uk(E),S={...e.env??n},I=await fk(e,{member:E,batchfile:String(y),promptCount:v,parentInvocationId:_r(S.LMCTL_INVOCATION_ID)});I!==null&&(S.LMCTL_INVOCATION_ID=String(I));let x,R,P,k=!1;e.stderr.write(`batch ${_t()}: starting ${v} prompt${v===1?"":"s"} -> ${E.alias} (teamfile=${p} input=${y})
|
|
2187
|
+
`);try{if(b){let K=await j(e,V=>(_s(V,E.teamfile,E.alias),cs(V,E.teamfile,E.alias)));if(K.busy){let V=K.reason==="in-flight"?`${E.alias} is servicing ${K.inFlight.sender_alias} (${K.inFlight.sender_teamfile}) since ${K.inFlight.started_at} \u2014 wait and retry`:K.source==="terminal-lock"?An(K.terminalLock):`${E.alias} is busy (interactive terminal); wait and retry`;return I!==null&&await j(e,O=>{O.finishTrackedInvocation(I,{status:"busy",exit_code:1,error:V,result_summary:"0 prompts completed"})}),B(e,`batch: cannot start bundle: ${V}`),null}let ue=await j(e,V=>mk(S,V)),le=await j(e,V=>cr(V,{receiver_teamfile:E.teamfile,receiver_alias:E.alias,sender_teamfile:ue?.teamfile??E.teamfile,sender_alias:ue?.alias??"operator",ttlMs:mt(S)}));if(!le.acquired){let V=`${E.alias} is servicing ${le.current.sender_alias} (${le.current.sender_teamfile}) since ${le.current.started_at} \u2014 wait and retry`;return I!==null&&await j(e,O=>{O.finishTrackedInvocation(I,{status:"busy",exit_code:1,error:V,result_summary:"0 prompts completed"})}),B(e,`batch: cannot start bundle: ${V}`),null}x={row:le.lease,leaseId:le.leaseId};let Nt=ls(V=>j(e,O=>O.heartbeatAgentInflight(x.row,x.leaseId,V)));P={stop:()=>clearInterval(Nt)};let Qe=gr(e,V=>`batch ${_t()}: opening provider session (${V}s elapsed)
|
|
2188
|
+
`);try{let V={...S};try{let O=await j(e,J=>J.getRootTeam(E.teamfile)?.name??null);O!==null&&(V.LMBEE_TEAM_NAME=O)}catch{}R=await sl({provider:E.provider,sessionId:E.sessionid,cwd:E.sessiondir,env:V,...E.model!==void 0?{model:E.model}:{},...E.effort!==void 0?{effort:E.effort}:{},alias:E.alias,isLead:E.isLead,permissionMode:"yolo",holdOpen:pl(e,{teamfile:E.teamfile,alias:E.alias},V)}),k=!0}catch{P&&P.stop(),P=void 0,await Jl(e,x),x=void 0,k=!1}finally{Qe.stop()}}let q={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(p),alias:String(f),batchfile:String(y),member:E,promptCount:v,useBundle:k,rootId:I,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:x,bundleSession:R,heartbeatTimer:P,closed:!1,env:S};return r.registerBatch(q),q}catch(C){if(P){try{P.stop()}catch{}P=void 0}if(x){try{await Jl(e,x)}catch{}x=void 0}if(R){try{await R.close()}catch{}R=void 0}if(I!==null)try{await j(e,q=>{q.finishTrackedInvocation(I,{status:"error",exit_code:1,error:C?.message||String(C),result_summary:"0 prompts completed"})})}catch{}throw C}},{min:1,max:4},"Opens a batch from a member map or a teamfile with lifecycle management"),t.registerFunction("lm_batch_turn",async(p,f,y,g)=>{let E=typeof p=="string"?r.getBatch(p):p?.id?r.getBatch(p.id)??p:void 0;if(!E)throw new Error("Invalid or unmanaged batch handle");if(E.kind==="agent"){if(r.getBatch(E.id)!==E)throw new Error("Invalid or unmanaged batch handle");if(E.closed||E.failed)return{status:"error",reply:"",error:"Batch is closed or stopped after a failed turn"};if(E.inFlight)return{status:"busy",reply:"",error:"Batch already has an active turn"};E.inFlight=!0;try{let S=E.member.sessionid,I=await u(E.member,String(f),E.options);return E.member.sessionid&&E.sourceMember.provider===E.member.provider&&E.sourceMember.sessionid===S&&(E.sourceMember.sessionid=E.member.sessionid),I.status!=="ok"&&(E.failed=!0),{status:I.status,reply:I.reply.replace(/\n+$/u,""),error:I.error}}finally{E.inFlight=!1}}let v=Number(y),w=Number(g);e.stderr.write(`batch ${_t()}: prompt ${v}/${w} -> ${E.member.alias}
|
|
2189
|
+
`);let b=gr(e,S=>`batch ${_t()}: prompt ${v}/${w} still running (${S}s elapsed)
|
|
2190
|
+
`);try{let S=await gl({teamfile:E.member.teamfile,alias:E.member.alias,prompt:String(f),expectedSession:{provider:E.member.provider,sessionid:E.member.sessionid},permissionMode:"yolo",env:{...E.env},messageType:"batch",...E.heldLease!==void 0?{heldLease:E.heldLease}:{},...E.bundleSession!==void 0?{bundleSession:E.bundleSession}:{},io:e,onEvent:x=>{b.poke(),x.kind==="warning"&&e.stderr.write(x.message)}}),I=S.replyText?String(S.replyText).replace(/\n+$/u,""):"";if(S.status!=="ok"){let x=S.status==="stalled"?"provider stalled":S.status==="empty"?"provider returned no content and no observed activity for this turn":S.message,R=`batch: stopped at prompt ${v}/${w} (${v-1} completed): ${x}; later prompts were not sent`;return E.rootFinish={status:S.status==="busy"?"busy":"error",exit_code:1,error:R,result_summary:`${v-1}/${w} prompts completed`},B(e,R),{status:S.status,reply:I,error:R}}return{status:"ok",reply:I,error:null}}catch(S){let I=`batch: stopped at prompt ${v}/${w} (${v-1} completed): ${S instanceof Error?S.message:String(S)}; later prompts were not sent`;return E.rootFinish={status:"error",exit_code:1,error:I,result_summary:`${v-1}/${w} prompts completed`},B(e,I),{status:"error",reply:"",error:I}}finally{b.stop()}},4,"Executes a prompt turn within a batch session"),t.registerFunction("lm_batch_close",async(p,f="done",y)=>{let g=typeof p=="string"?r.getBatch(p):p?.id?r.getBatch(p.id)??p:void 0;return g?(await bg(g,e,f==="done"?"done":f==="cancelled"?"cancelled":"error",y),!0):!1},{min:1,max:3},"Closes a batch session and cleans up resources"),t.registerFunction("lm_ratelimit_readings",async(p={})=>{try{if(!p||typeof p!="object"||Array.isArray(p))throw new Error("lm_ratelimit_readings: options must be a map");let f=p.providers??(p.provider===void 0?["all"]:[p.provider]);if(!Array.isArray(f)||f.some(g=>typeof g!="string"||!g||g.startsWith("-")))throw new Error("lm_ratelimit_readings: providers must be a list of provider names");let y=p.timeoutSeconds??15;if(typeof y!="number"||!Number.isFinite(y)||y<=0)throw new Error("lm_ratelimit_readings: timeoutSeconds must be a positive finite number");return Vh({providers:f.length?f:["all"],timeoutSeconds:y,env:e.env??n,progress:g=>{e.stderr.write(`${g}
|
|
2191
2191
|
`)}})}catch(f){return{status:"error",error:f instanceof Error?f.message:String(f),readings:[]}}},{min:0,max:1},"Reads live provider quota values without analytics or aggregation");let i=new WeakSet,o=new Set,a=new Set,l=new Map,c=async(p,f,y={},g=!1)=>{let E=(S,I="",x=null)=>({status:S,reply:I,error:x,message_id:null,team_chat_log_id:null}),v,w=!1,b;try{if(!p||typeof p!="object"||Array.isArray(p))throw new Error("lm_agent: member must be a map");for(let C of["provider","alias","model","effort","sessiondir","sessionid"]){let q=p[C];if(q!=null&&(typeof q!="string"||!q.trim()))throw new Error(`lm_agent: ${C} must be a nonempty string when supplied`)}if(!p.provider)throw new Error("lm_agent: provider is required");if(typeof f!="string")throw new Error("lm_agent: prompt must be a string");if(!y||typeof y!="object"||Array.isArray(y))throw new Error("lm_agent: options must be a map");let S=y.permissionMode??"yolo";if(S!=="yolo"&&S!=="plan")throw new Error("lm_agent: permissionMode must be yolo or plan");if(y.idleTimeoutMs!=null&&(typeof y.idleTimeoutMs!="number"||!Number.isFinite(y.idleTimeoutMs)||y.idleTimeoutMs<0))throw new Error("lm_agent: idleTimeoutMs must be a finite nonnegative number");let I=p.provider,x=p.sessiondir??process.cwd(),R=p.sessionid??"";if(v=R?JSON.stringify([I,R]):void 0,i.has(p)||v!==void 0&&(o.has(v)||!g&&a.has(v)))return E("busy","","lm_agent: session already has an active turn in this engine");i.add(p),v!==void 0&&o.add(v),w=!0,e.stderr.write(`agent ${_t()}: prompting ${p.alias??I}
|
|
2192
|
-
`),b=
|
|
2193
|
-
`);let P=R;if(!P&&["agy","pi","dsh"].includes(I)){if(S!=="yolo")throw new Error(`lm_agent: fresh ${I} sessions require yolo seed; supply sessionid for resume`);let C=await
|
|
2194
|
-
`);if(!C.success||!C.sessionId)throw new Error(C.error??"lm_agent: provider did not identify the seeded session");P=C.sessionId,p.sessionid=P,v=JSON.stringify([I,P]),o.add(v)}let k=await
|
|
2195
|
-
`);return P&&k.sessionId!==P?E("error","","lm_agent: provider changed session identity during resume"):(k.sessionId&&(p.sessionid=k.sessionId),k.status==="stalled"?E("stalled",k.text,"provider stalled"):k.status==="empty"?E("empty","","lm_agent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):k.sessionId?E("ok",k.text):E("error",k.text,"lm_agent: provider did not return a session ID"))}catch(S){return E("error","",S instanceof Error?S.message:String(S))}finally{b?.stop(),w&&(i.delete(p),v!==void 0&&o.delete(v))}},u=async(p,f,y={},g=!1)=>{let E=await c(p,f,y,g);if(p?.sessionid&&E.status!=="busy"){let v=JSON.stringify([p.provider,p.sessionid]),w=l.get(v)??{lines:[],options:{}};w.lines.push(`You: ${f}`),E.reply&&w.lines.push(`Agent: ${E.reply}`),E.error&&w.lines.push(`${E.status}: ${E.error}`),w.options={...y},l.set(v,w)}return E};t.registerFunction("lm_agent",u,{min:2,max:3},"Prompts an agent described by a map without a teamfile"),t.registerFunction("lm_session_list",async(p={})=>{if(!p||typeof p!="object"||Array.isArray(p)||p.provider!=null&&(typeof p.provider!="string"||!p.provider.trim())||p.sessiondir!=null&&(typeof p.sessiondir!="string"||!p.sessiondir.trim())||p.all!=null&&typeof p.all!="boolean")throw new Error("lm_session_list: expected options map with provider, sessiondir, and all");return(await
|
|
2192
|
+
`),b=gr(e,C=>`agent ${_t()}: still running (${C}s elapsed)
|
|
2193
|
+
`);let P=R;if(!P&&["agy","pi","dsh"].includes(I)){if(S!=="yolo")throw new Error(`lm_agent: fresh ${I} sessions require yolo seed; supply sessionid for resume`);let C=await il({provider:I,cwd:x,model:p.model,effort:p.effort});for(let q of C.warnings??[])e.stderr.write(`warning: ${q}
|
|
2194
|
+
`);if(!C.success||!C.sessionId)throw new Error(C.error??"lm_agent: provider did not identify the seeded session");P=C.sessionId,p.sessionid=P,v=JSON.stringify([I,P]),o.add(v)}let k=await In({provider:I,cwd:x,sessionId:P,prompt:f,model:p.model,effort:p.effort,alias:p.alias,isLead:!1,permissionMode:S,timeoutMs:y.idleTimeoutMs,requireResume:!!P,env:{...e.env??n},onDelta:()=>b?.poke(),onProgress:()=>b?.poke()});for(let C of k.warnings??[])e.stderr.write(`warning: ${C}
|
|
2195
|
+
`);return P&&k.sessionId!==P?E("error","","lm_agent: provider changed session identity during resume"):(k.sessionId&&(p.sessionid=k.sessionId),k.status==="stalled"?E("stalled",k.text,"provider stalled"):k.status==="empty"?E("empty","","lm_agent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):k.sessionId?E("ok",k.text):E("error",k.text,"lm_agent: provider did not return a session ID"))}catch(S){return E("error","",S instanceof Error?S.message:String(S))}finally{b?.stop(),w&&(i.delete(p),v!==void 0&&o.delete(v))}},u=async(p,f,y={},g=!1)=>{let E=await c(p,f,y,g);if(p?.sessionid&&E.status!=="busy"){let v=JSON.stringify([p.provider,p.sessionid]),w=l.get(v)??{lines:[],options:{}};w.lines.push(`You: ${f}`),E.reply&&w.lines.push(`Agent: ${E.reply}`),E.error&&w.lines.push(`${E.status}: ${E.error}`),w.options={...y},l.set(v,w)}return E};t.registerFunction("lm_agent",u,{min:2,max:3},"Prompts an agent described by a map without a teamfile"),t.registerFunction("lm_session_list",async(p={})=>{if(!p||typeof p!="object"||Array.isArray(p)||p.provider!=null&&(typeof p.provider!="string"||!p.provider.trim())||p.sessiondir!=null&&(typeof p.sessiondir!="string"||!p.sessiondir.trim())||p.all!=null&&typeof p.all!="boolean")throw new Error("lm_session_list: expected options map with provider, sessiondir, and all");return(await ol({provider:p.provider,workspace:p.all?void 0:p.sessiondir??process.cwd()})).map(y=>({provider:y.provider,sessionid:y.sessionId,sessiondir:y.cwd,modifiedAt:y.modifiedAt.toISOString()}))},{min:0,max:1},"Lists native provider sessions"),t.registerFunction("lm_session_delete",async(p,f={})=>{let y=(E,v=null)=>({status:E,error:v});if(!p||typeof p!="object"||Array.isArray(p)||typeof p.provider!="string"||!p.provider.trim()||typeof p.sessionid!="string"||!p.sessionid.trim())return y("error","lm_session_delete: member requires provider and sessionid");if(!f||typeof f!="object"||Array.isArray(f)||f.force!==!0)return y("error","lm_session_delete: force: true is required because cross-process turns cannot be detected");let g=JSON.stringify([p.provider,p.sessionid]);if(i.has(p)||o.has(g)||a.has(g))return y("busy","lm_session_delete: session has an active turn in this engine");o.add(g);try{return await al(p.provider,p.sessionid)?(l.delete(g),p.sessionid=null,y("deleted")):y("not_found")}catch(E){return y("error",E instanceof Error?E.message:String(E))}finally{o.delete(g)}},{min:1,max:2},"Deletes a native session with explicit cross-process race acceptance");let d=async(p,f,y={})=>{if(!Array.isArray(p))throw new Error("lm_fanout: participants must be an array of member maps");if(p.length===0)return[];let g;if(typeof f=="string")g=p.map(()=>f);else if(Array.isArray(f)){if(f.length!==p.length)throw new Error(`lm_fanout: prompts array length (${f.length}) must match participants length (${p.length})`);for(let E of f)if(typeof E!="string")throw new Error("lm_fanout: every prompts[] entry must be a string");g=f}else throw new Error("lm_fanout: prompts must be a string (broadcast to every participant) or an array of strings (one per participant)");if(!y||typeof y!="object"||Array.isArray(y))throw new Error("lm_fanout: options must be a map");return Promise.all(p.map((E,v)=>u(E,g[v],y)))};t.registerFunction("lm_fanout",d,{min:2,max:3},"Dispatches a prompt to every participant in an array concurrently (runtime-sized, unlike parallel()); returns an array of lm_agent-shaped results in the same order as participants. prompts is a single string broadcast to all, or an array of strings (one per participant, same length).");let m=async(p,f={})=>{if(typeof p!="string"||p.length===0)throw new Error("lm_seed: teamfile must be a nonempty string");if(!f||typeof f!="object"||Array.isArray(f))throw new Error("lm_seed: options must be a map");if(f.preamble!==void 0&&typeof f.preamble!="string"&&(typeof f.preamble!="object"||f.preamble===null||Array.isArray(f.preamble)))throw new Error("lm_seed: options.preamble must be a string or a map keyed by alias");let y=f.preamble!==void 0?{preamble:f.preamble}:{};return{status:await fh(p,e,y)===0?"ok":"error"}};t.registerFunction("lm_seed",m,{min:1,max:2},"Seeds a real teamfile over the exact same path lmctl seed takes; options.preamble overrides the default Lead prompt (string) or per-alias prompts (map)."),t.registerFunction("lm_terminal",async(p,f)=>{if(typeof p!="string"||!p||typeof f!="string"||!f)throw new Error("lm_terminal requires a teamfile and alias");if(hr(e)||n.LMCTL_NON_INTERACTIVE==="1")throw new Error("lm_terminal is disabled in non-interactive mode");let{runTerminal:y}=await Promise.resolve().then(()=>(vg(),Sg)),g=await y([p,f],{...e,env:n});return{status:g===0?"ok":"error",code:g}},2,"Opens a tracked member in its native TUI; refuses non-interactive mode.");let h=async p=>{if(typeof p!="string"||p.length===0)throw new Error("lm_lint: teamfile must be a nonempty string");return mh(p,e)};t.registerFunction("lm_lint",h,1,"Validates a teamfile over the exact same path lmctl lint takes, returning { status, errors, warnings, counts } instead of text to parse.");let _=!1,T=async p=>{let f=p!==null&&typeof p=="object";if(_)throw new Error("prompt_human: another operator prompt is active");_=!0;let y,g;try{let E=e.stdin??process.stdin;if(!f)return await Wr(p,E,e.stdout);let v={...p};if(Array.isArray(p)||typeof v.provider!="string"||!v.provider.trim()||typeof v.sessionid!="string"||!v.sessionid.trim())return{command:"error",args:["prompt_human: session map requires provider and sessionid; call lm_agent first"]};let w=JSON.stringify([v.provider,v.sessionid]);if(o.has(w))return{command:"busy",args:["Agent turn is still running"]};a.add(w),g=w;let b=E;if(b.destroyed||b.readableEnded)return{command:"eof",args:[]};y=dk({input:b,output:e.stdout,terminal:!!b.isTTY,crlfDelay:1/0});let S=y[Symbol.asyncIterator](),I=!1;y.on("SIGINT",()=>{I=!0,y?.close()}),e.stdout.write(`Session ${v.alias??v.provider} (${v.sessionid})
|
|
2196
2196
|
`);let x=l.get(w);if(x)for(let R of x.lines)e.stdout.write(`${R}
|
|
2197
2197
|
`);else{let R=await yt(kt()).getSession(v.sessionid,v.provider);if(!R)return{command:"error",args:["Could not load session history"]};for(let P of R.messages)(P.role==="user"||P.role==="assistant")&&e.stdout.write(`${P.role==="user"?"You":"Agent"}: ${P.content}
|
|
2198
2198
|
`)}for(e.stdout.write(`Talk to the agent. Return to the script with /exit [command] [args...].
|
|
2199
2199
|
`);;){e.stdout.write("You> ");let R=await S.next();if(I)return{command:"cancelled",args:[]};if(R.done)return{command:"eof",args:[]};let P=R.value.trim();if(!P)continue;if(/^\/exit(?:\s|$)/u.test(P)){let C=P.split(/\s+/u).slice(1);return{command:C.shift()??"exit",args:C}}let k=await u(v,R.value,x?.options??{},!0);if(k.reply&&e.stdout.write(`Agent: ${k.reply}
|
|
2200
2200
|
`),k.status!=="ok")return e.stdout.write(`${k.status}: ${k.error}
|
|
2201
|
-
`),{command:k.status,args:[k.error??"Agent turn failed"]}}}catch(E){if(!f)throw E;return{command:"error",args:[E instanceof Error?E.message:String(E)]}}finally{y?.close(),g!==void 0&&a.delete(g),_=!1}};t.registerFunction("prompt_human",p=>{if(n.LMCTL_NON_INTERACTIVE==="1"||
|
|
2201
|
+
`),{command:k.status,args:[k.error??"Agent turn failed"]}}}catch(E){if(!f)throw E;return{command:"error",args:[E instanceof Error?E.message:String(E)]}}finally{y?.close(),g!==void 0&&a.delete(g),_=!1}};t.registerFunction("prompt_human",p=>{if(n.LMCTL_NON_INTERACTIVE==="1"||hr(e))throw new Error("prompt_human is disabled in non-interactive mode");if(!t.isAsyncMode&&(p===null||typeof p!="object")){if(_)throw new Error("prompt_human: another operator prompt is active");return Br(p)}return T(p)},{min:0,max:1},{description:"Prompts for a string, or hands an agent session to the operator and returns a decision map",allowOverwrite:!0}),t.registerFunctionDoc({name:"prompt_human",module:"core",category:"System & Process",signature:"prompt_human([question: string]): string|null; prompt_human(session: map): map",description:'Question form reads one line. In the lmctl engine, a session map opens an agent conversation showing script history. /exit retry a b returns {command: "retry", args: ["a", "b"]}; arguments are whitespace-separated. Bare /exit returns command "exit"; closed input returns "eof". Errors, stalls, busy sessions and Ctrl-C return "error", "stalled", "busy" and "cancelled" maps. All map results have args: string[].',example:'agent = { provider: "codex" }; lm_agent(agent, "Review this change"); decision = prompt_human(agent); if (decision.command == "retry") { lm_agent(agent, join(decision.args, " ")); }'}),t.registerFunction("lm_prompt",async(p,f,y,g={})=>{try{let E=await gl({teamfile:String(p),alias:String(f),prompt:String(y),permissionMode:g?.permissionMode??"yolo",idleTimeoutMs:g?.idleTimeoutMs,env:{...e.env??n},messageType:g?.messageType,io:e});return{status:E.status,reply:E.replyText??"",error:E.message??null,message_id:E.messageId??null,team_chat_log_id:E.teamChatLogId??null}}catch(E){return{status:"error",reply:"",error:E?.message||String(E),message_id:null,team_chat_log_id:null}}},{min:3,max:4},"Sends a prompt directly to a team member and returns the reply")}var Ag={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:Kl,register(t,e){xg(t,e.io,e.registry,e.env)}};function kg(t,e,r=new Fr,n=process.env){return t.registerModule(Ag,{io:e,registry:r,env:n})}function Ng(t,e=[],r=new Fr,n=process.env){let s=Ig({scriptArgs:e,io:t,env:n});return kg(s,t,r,n),n.LMCTL_LMBEE_BRIDGE==="1"&&s.registerModule(mg(n,i=>r.registerTemporaryDirectory(i))),s}async function gk(t,e,r={stdout:process.stdout,stderr:process.stderr},n=process.env,s,i={}){let o=new Fr,a=d=>{o.removeTemporaryDirectories();for(let m of o.getOpenBatches()){if(m.kind==="agent"){m.closed=!0;continue}if(m.heartbeatTimer){try{m.heartbeatTimer.stop()}catch{}m.heartbeatTimer=void 0}if(m.heldLease){try{if(r.dal)r.dal.releaseAgentInflight(m.heldLease.row,m.heldLease.leaseId);else{let h=$t({path:st(n?.LMCTL_DB)});try{h.releaseAgentInflight(m.heldLease.row,m.heldLease.leaseId)}finally{h.close()}}}catch{}m.heldLease=void 0}m.rootId!==null&&pk(r,m.rootId,{status:"cancelled",signal:d,error:`batch interrupted by ${d}`},n)}process.exit(d==="SIGINT"?130:143)};process.once("SIGINT",a),process.once("SIGTERM",a);let l=!1,c,u=()=>{if(l)return;l=!0;let d=o.getErrors(),m=c?c.getRecordedErrors():[],h=[...d];for(let _ of m)h.includes(_)||h.push(_);if(h.length>0){r.stderr.write(`
|
|
2202
2202
|
=== LMScript Error Summary (${h.length} error${h.length===1?"":"s"}) ===
|
|
2203
2203
|
`);for(let _=0;_<h.length;_++)r.stderr.write(` ${_+1}. ${h[_]}
|
|
2204
2204
|
`);r.stderr.write(`==========================================
|
|
2205
|
-
`)}};try{let d=
|
|
2205
|
+
`)}};try{let d=Ng(r,e,o,n);c=d;for(let[h,_]of Object.entries(i))d.setGlobal(h,_);let m=await d.runAsync(t,{file:s,stderr:h=>{r.stderr.write(h.endsWith(`
|
|
2206
2206
|
`)?h:`${h}
|
|
2207
2207
|
`)}});if(u(),m.exitCode!==void 0)return m.exitCode;if(!m.success){for(let h of m.diagnostics){let _=h.file?`${h.file}:${h.line}:${h.column}`:`${h.line}:${h.column}`;r.stderr.write(`error:${_}: ${h.message}
|
|
2208
2208
|
`)}return 1}return o.hasErrors()||m.errors&&m.errors.length>0?1:0}catch(d){return u(),d instanceof ve||d?.name==="LMScriptExit"?d.exitCode:(r.stderr.write(`error: ${d instanceof Error?d.message:String(d)}
|
|
2209
|
-
`),1)}finally{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",a),await o.forceCloseAll(r)}}var
|
|
2209
|
+
`),1)}finally{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",a),await o.forceCloseAll(r)}}var _k=`# batchscript.lms - Test-only comparison with procedural lmctl batch
|
|
2210
2210
|
# Arguments: [teamfile, alias, batchfile, flags...]
|
|
2211
2211
|
|
|
2212
2212
|
if (includes(args, "--help") || includes(args, "-h")) {
|
|
@@ -2273,4 +2273,4 @@ for (i = 0; i < len(prompts); i = i + 1) {
|
|
|
2273
2273
|
|
|
2274
2274
|
lm_batch_close(handle, "done");
|
|
2275
2275
|
lm_exit(0);
|
|
2276
|
-
`;export{
|
|
2276
|
+
`;export{_k as BATCH_LMS,Kl as LMCTL_FUNCTION_DOCS,Ze as LMScript,ve as LMScriptExit,Fr as ResourceRegistry,Ig as createBaseScriptEngine,Ng as createLmScriptEngine,Ag as lmctlModule,hk as registerLmctlDocs,xg as registerLmctlHostFunctions,kg as registerLmctlModule,gk as runScriptEngine};
|